@kamilio/wire 0.1.55 → 0.1.57

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 (138) hide show
  1. package/README.md +44 -1
  2. package/dist/adapters/codesignal.d.ts +10 -0
  3. package/dist/adapters/codesignal.d.ts.map +1 -0
  4. package/dist/adapters/codesignal.js +165 -0
  5. package/dist/adapters/codesignal.js.map +1 -0
  6. package/dist/adapters/document-shell.d.ts +7 -0
  7. package/dist/adapters/document-shell.d.ts.map +1 -0
  8. package/dist/adapters/document-shell.js +51 -0
  9. package/dist/adapters/document-shell.js.map +1 -0
  10. package/dist/adapters/root.d.ts.map +1 -1
  11. package/dist/adapters/root.js +74 -8
  12. package/dist/adapters/root.js.map +1 -1
  13. package/dist/auth.d.ts +2 -1
  14. package/dist/auth.d.ts.map +1 -1
  15. package/dist/auth.js +4 -2
  16. package/dist/auth.js.map +1 -1
  17. package/dist/cli.d.ts.map +1 -1
  18. package/dist/cli.js +10 -4
  19. package/dist/cli.js.map +1 -1
  20. package/dist/document-shell-engine.mjs +1880 -0
  21. package/dist/executable.d.ts.map +1 -1
  22. package/dist/executable.js +3 -2
  23. package/dist/executable.js.map +1 -1
  24. package/dist/hooks.d.ts.map +1 -1
  25. package/dist/hooks.js +19 -19
  26. package/dist/hooks.js.map +1 -1
  27. package/node_modules/provider-asana/dist/asana-project.d.ts +7 -1
  28. package/node_modules/provider-asana/dist/asana-project.d.ts.map +1 -1
  29. package/node_modules/provider-asana/dist/asana-task.d.ts +7 -1
  30. package/node_modules/provider-asana/dist/asana-task.d.ts.map +1 -1
  31. package/node_modules/provider-asana/dist/index.d.ts +14 -2
  32. package/node_modules/provider-asana/dist/index.d.ts.map +1 -1
  33. package/node_modules/provider-chatgpt/dist/chatgpt.d.ts +7 -1
  34. package/node_modules/provider-chatgpt/dist/chatgpt.d.ts.map +1 -1
  35. package/node_modules/provider-chatgpt/dist/index.d.ts +7 -1
  36. package/node_modules/provider-chatgpt/dist/index.d.ts.map +1 -1
  37. package/node_modules/provider-gmail/dist/gmail.d.ts +7 -1
  38. package/node_modules/provider-gmail/dist/gmail.d.ts.map +1 -1
  39. package/node_modules/provider-gmail/dist/index.d.ts +7 -1
  40. package/node_modules/provider-gmail/dist/index.d.ts.map +1 -1
  41. package/node_modules/provider-google-docs/dist/doc-blocks.d.ts.map +1 -1
  42. package/node_modules/provider-google-docs/dist/doc-blocks.js +6 -2
  43. package/node_modules/provider-google-docs/dist/doc-blocks.js.map +1 -1
  44. package/node_modules/provider-google-docs/dist/google-docs.d.ts +7 -1
  45. package/node_modules/provider-google-docs/dist/google-docs.d.ts.map +1 -1
  46. package/node_modules/provider-google-docs/dist/google-docs.js +31 -10
  47. package/node_modules/provider-google-docs/dist/google-docs.js.map +1 -1
  48. package/node_modules/provider-google-docs/dist/google-forms.d.ts +7 -1
  49. package/node_modules/provider-google-docs/dist/google-forms.d.ts.map +1 -1
  50. package/node_modules/provider-google-docs/dist/index.d.ts +14 -2
  51. package/node_modules/provider-google-docs/dist/index.d.ts.map +1 -1
  52. package/node_modules/provider-google-docs/src/doc-blocks.ts +8 -2
  53. package/node_modules/provider-google-docs/src/google-docs.ts +26 -10
  54. package/node_modules/provider-lattice/dist/index.d.ts +14 -2
  55. package/node_modules/provider-lattice/dist/index.d.ts.map +1 -1
  56. package/node_modules/provider-notion/dist/index.d.ts +7 -1
  57. package/node_modules/provider-notion/dist/index.d.ts.map +1 -1
  58. package/node_modules/provider-notion/dist/notion-sync.d.ts +2 -2
  59. package/node_modules/provider-notion/dist/notion-sync.d.ts.map +1 -1
  60. package/node_modules/provider-notion/dist/notion-sync.js +24 -15
  61. package/node_modules/provider-notion/dist/notion-sync.js.map +1 -1
  62. package/node_modules/provider-notion/dist/notion.d.ts +7 -1
  63. package/node_modules/provider-notion/dist/notion.d.ts.map +1 -1
  64. package/node_modules/provider-notion/dist/notion.js +1 -1
  65. package/node_modules/provider-notion/dist/notion.js.map +1 -1
  66. package/node_modules/provider-notion/src/notion-sync.ts +23 -15
  67. package/node_modules/provider-notion/src/notion.ts +1 -1
  68. package/node_modules/provider-slack/dist/index.d.ts +7 -1
  69. package/node_modules/provider-slack/dist/index.d.ts.map +1 -1
  70. package/node_modules/provider-slack/dist/slack.d.ts +7 -1
  71. package/node_modules/provider-slack/dist/slack.d.ts.map +1 -1
  72. package/node_modules/provider-zoom/dist/index.d.ts +7 -1
  73. package/node_modules/provider-zoom/dist/index.d.ts.map +1 -1
  74. package/node_modules/provider-zoom/dist/zoom-hub.d.ts +7 -1
  75. package/node_modules/provider-zoom/dist/zoom-hub.d.ts.map +1 -1
  76. package/node_modules/wire-core/dist/core/editor-receipts.d.ts +5 -0
  77. package/node_modules/wire-core/dist/core/editor-receipts.d.ts.map +1 -0
  78. package/node_modules/wire-core/dist/core/editor-receipts.js +9 -0
  79. package/node_modules/wire-core/dist/core/editor-receipts.js.map +1 -0
  80. package/node_modules/wire-core/dist/core/model.d.ts +4 -1
  81. package/node_modules/wire-core/dist/core/model.d.ts.map +1 -1
  82. package/node_modules/wire-core/dist/core/owner.d.ts +3 -0
  83. package/node_modules/wire-core/dist/core/owner.d.ts.map +1 -0
  84. package/node_modules/wire-core/dist/core/owner.js +16 -0
  85. package/node_modules/wire-core/dist/core/owner.js.map +1 -0
  86. package/node_modules/wire-core/dist/core/source.d.ts +4 -1
  87. package/node_modules/wire-core/dist/core/source.d.ts.map +1 -1
  88. package/node_modules/wire-core/dist/core/source.js +12 -2
  89. package/node_modules/wire-core/dist/core/source.js.map +1 -1
  90. package/node_modules/wire-core/dist/index.d.ts +1 -1
  91. package/node_modules/wire-core/dist/index.d.ts.map +1 -1
  92. package/node_modules/wire-core/dist/index.js +1 -1
  93. package/node_modules/wire-core/dist/index.js.map +1 -1
  94. package/node_modules/wire-core/dist/operations.d.ts +11 -2
  95. package/node_modules/wire-core/dist/operations.d.ts.map +1 -1
  96. package/node_modules/wire-core/dist/operations.js +399 -31
  97. package/node_modules/wire-core/dist/operations.js.map +1 -1
  98. package/node_modules/wire-core/dist/runtime/cookies.js +1 -1
  99. package/node_modules/wire-core/dist/runtime/cookies.js.map +1 -1
  100. package/node_modules/wire-core/dist/storage/editor-receipts.d.ts +17 -0
  101. package/node_modules/wire-core/dist/storage/editor-receipts.d.ts.map +1 -0
  102. package/node_modules/wire-core/dist/storage/editor-receipts.js +27 -0
  103. package/node_modules/wire-core/dist/storage/editor-receipts.js.map +1 -0
  104. package/node_modules/wire-core/dist/storage/history-integrity.d.ts +4 -0
  105. package/node_modules/wire-core/dist/storage/history-integrity.d.ts.map +1 -0
  106. package/node_modules/wire-core/dist/storage/history-integrity.js +32 -0
  107. package/node_modules/wire-core/dist/storage/history-integrity.js.map +1 -0
  108. package/node_modules/wire-core/dist/storage/history.d.ts +93 -0
  109. package/node_modules/wire-core/dist/storage/history.d.ts.map +1 -0
  110. package/node_modules/wire-core/dist/storage/history.js +450 -0
  111. package/node_modules/wire-core/dist/storage/history.js.map +1 -0
  112. package/node_modules/wire-core/dist/storage/registry.d.ts +2 -2
  113. package/node_modules/wire-core/dist/storage/registry.d.ts.map +1 -1
  114. package/node_modules/wire-core/dist/storage/registry.js +34 -14
  115. package/node_modules/wire-core/dist/storage/registry.js.map +1 -1
  116. package/node_modules/wire-core/dist/storage/workspace.d.ts.map +1 -1
  117. package/node_modules/wire-core/dist/storage/workspace.js +183 -40
  118. package/node_modules/wire-core/dist/storage/workspace.js.map +1 -1
  119. package/node_modules/wire-core/src/core/editor-receipts.ts +8 -0
  120. package/node_modules/wire-core/src/core/model.ts +4 -1
  121. package/node_modules/wire-core/src/core/owner.ts +16 -0
  122. package/node_modules/wire-core/src/core/source.ts +13 -1
  123. package/node_modules/wire-core/src/index.ts +1 -1
  124. package/node_modules/wire-core/src/operations.ts +339 -33
  125. package/node_modules/wire-core/src/runtime/cookies.ts +1 -1
  126. package/node_modules/wire-core/src/storage/editor-receipts.ts +27 -0
  127. package/node_modules/wire-core/src/storage/history-integrity.ts +25 -0
  128. package/node_modules/wire-core/src/storage/history.ts +331 -0
  129. package/node_modules/wire-core/src/storage/registry.ts +22 -15
  130. package/node_modules/wire-core/src/storage/workspace.ts +129 -34
  131. package/package.json +6 -2
  132. package/src/adapters/codesignal.ts +244 -0
  133. package/src/adapters/document-shell.ts +43 -0
  134. package/src/adapters/root.ts +76 -8
  135. package/src/auth.ts +6 -3
  136. package/src/cli.ts +10 -4
  137. package/src/executable.ts +3 -2
  138. package/src/hooks.ts +19 -18
@@ -1,11 +1,15 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
 
4
+ import { FileRegistry, SqliteRegistry } from "./storage/registry.js";
5
+ import { DocumentHistory, requireHistoryVolume, withHistoryLock, working, type HistoryDiff, type HistoryEntry, type HistoryStatus } from "./storage/history.js";
6
+ import { editorFile, editorView, plainMarkdown } from "./storage/editor-receipts.js";
7
+ import { assertWireOwner } from "./core/owner.js";
4
8
  import { stableJsonCompact } from "./core/json.js";
5
9
  import { extractRelationships, markdownFilename } from "./core/transform.js";
6
10
  import type { FetchedDocument, JsonObject, JsonValue, Registry, Resource, ResourceData, ServiceCatalog, Source } from "./core/model.js";
7
11
  import { resourceId } from "./core/resource.js";
8
- import { fetchSource, parseSourceUrl, synchronizeSource, uploadSource } from "./core/source.js";
12
+ import { fetchSource, parseSourceUrl, synchronizeSource, uploadSource, WireMergeConflict } from "./core/source.js";
9
13
  import type { InitializedWire, SwitchedWireBackend, WatchCapability, WatchHandle, WireBackend, WireConfig, WireWatchConfig, WireWorkspace } from "./ports.js";
10
14
 
11
15
  export type { WireWorkspace } from "./ports.js";
@@ -63,7 +67,13 @@ export type WireWatchSyncHook = (command: WireWatchSyncCommand, result: WireResu
63
67
  export const wireWatchHooks = Symbol("wireWatchHooks");
64
68
 
65
69
  export type Wire = Readonly<{
66
- attach(url: string, path: string): Promise<WireResult>;
70
+ attach(url: string, path: string, editorReceipts?: boolean): Promise<WireResult>;
71
+ adopt(url: string, existingFilePath: string, editorReceipts?: boolean): Promise<WireResult>;
72
+ historyStatus(value: string, path: string): Promise<HistoryStatus>;
73
+ historyLog(value: string, path: string): Promise<readonly HistoryEntry[]>;
74
+ historyDiff(value: string, path: string, from?: string, to?: string): Promise<HistoryDiff>;
75
+ resolveConflict(value: string, path: string, choice: "local" | "remote" | "working" | "editor" | "shell"): Promise<HistoryStatus>;
76
+ checkpoint(value: string, path: string, expected: string, markdown: string, token: string): Promise<HistoryStatus>;
67
77
  create(url: string, path: string): Promise<WireResult>;
68
78
  view(url: string): Promise<FetchedDocument>;
69
79
  downloadSource(url: string, path: string): Promise<WireResult>;
@@ -210,8 +220,29 @@ function errorMessage(error: unknown): string {
210
220
  return String(error);
211
221
  }
212
222
 
223
+ export { withHistoryLock };
224
+ export const sourceLock = (source: Source) => source.service === "google-docs" && source.type === "document" ? "google-docs:" + String(source["document_id"] ?? source.identifier.split("#tab=")[0]) : resourceId(source);
225
+
213
226
  export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInput>): Wire {
214
- const store = async (url: string, path: string, fetched: FetchedDocument, previousMarkdown: string | null | undefined, action: WireAction, fixedOutputPath: string | undefined, summaryMarkdown: string | undefined, summaryAfterMarkdown: string): Promise<WireResult> => {
227
+ const durable = (registry: Registry) => registry instanceof FileRegistry || registry instanceof SqliteRegistry;
228
+ const locked = async <T>(root: string, registry: Registry, key: string, fn: () => Promise<T>) => durable(registry) ? withHistoryLock(root, key, fn) : fn();
229
+ const owner = async (registry: Registry, source: Source, url: string) => assertWireOwner(await registry.listResources(), source, dependencies.catalog.find(s => s.matches(new URL(url)))!);
230
+ const historyFor = async (root: string, registry: Registry, source: Source) => durable(registry) ? DocumentHistory.load(root, resourceId(source), dependencies.now) : null;
231
+ const removeDetached = (registry: Registry) => async (before: Resource) => {
232
+ const current = (await registry.listResources()).find(r => r.id === before.id);
233
+ if (!current) return;
234
+ if (stableJsonCompact(current) !== stableJsonCompact(before)) throw new Error("Registration changed during detach. The newer registration was kept.");
235
+ await registry.delete(before.id);
236
+ };
237
+ const restore = async (root: string, registry: Registry, source: Source, path?: string) => {
238
+ const history = await historyFor(root, registry, source);
239
+ await history?.recover(path, r => registry.put(r), removeDetached(registry));
240
+ return history;
241
+ };
242
+ const checkReceiptLink = (resource: Resource | null, h?: DocumentHistory | null) => {
243
+ if (resource && (primaryLink(resource).data["editor_receipts"] === true) !== !!h?.refs.editorReceipts) throw new Error("Missing Wire editor receipt history or link registration. Restore the link and its private history before syncing.");
244
+ };
245
+ const store = async (url: string, path: string, fetched: FetchedDocument, previousMarkdown: string | null | undefined, action: WireAction, fixedOutputPath: string | undefined, summaryMarkdown: string | undefined, summaryAfterMarkdown: string, history?: DocumentHistory | null, enableReceipts = false, expectedRaw?: string | null): Promise<WireResult> => {
215
246
  const source = parseSourceUrl(url, dependencies.catalog);
216
247
  const root = await wireRoot(dependencies, path);
217
248
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
@@ -225,32 +256,42 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
225
256
  await dependencies.filesystem.exists(candidate) || (await registry.findByPath(dependencies.workspace.relativePath(candidate, root))).length > 0);
226
257
  }
227
258
  const relativePath = dependencies.workspace.relativePath(outputPath, root);
228
- const onDisk = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
259
+ checkReceiptLink(current, history);
260
+ plainMarkdown(fetched.markdown);
261
+ const raw = history ? await working(outputPath) : await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
262
+ const view = raw === null ? null : history ? history.view(raw) : editorView(raw);
263
+ const onDisk = view?.markdown ?? null;
264
+ if (expectedRaw !== undefined && raw !== expectedRaw && (enableReceipts || history?.refs.editorReceipts)) throw new Error("Local file changed during sync; run wire sync again.");
265
+ if (!current && fixedOutputPath === undefined && onDisk !== null) throw new Error("Another file appeared at the proposed attachment path; retry attach.");
229
266
  const previous = (previousMarkdown === undefined ? onDisk : previousMarkdown) ?? "";
230
267
  const concurrentEdit = previousMarkdown !== undefined && onDisk !== previousMarkdown && onDisk !== fetched.markdown;
231
268
  const retry = `Local file changed during sync: ${relativePath}. Local changes were preserved. Run wire sync again.`;
232
269
  // Only advance the common base if the editor saw that version. Otherwise a retry
233
270
  // could mistake remote additions that never reached disk for local deletions.
234
- if (concurrentEdit && current !== null && fetched.markdown !== previousMarkdown) throw new Error(retry);
271
+ if (concurrentEdit && current !== null && fetched.markdown !== previousMarkdown) {
272
+ if (history) { await history.observe(fetched); await history.save(); }
273
+ throw new Error(retry);
274
+ }
235
275
  if (action === "attached" && current !== null) {
236
276
  const snapshot = current.data.find((item) => item.namespace === source.service && item.key === "snapshot")!.value;
237
- const baseMarkdown = markdownSnapshot(syncBase(source.service, snapshot, current.data));
277
+ const baseMarkdown = markdownSnapshot(syncBase(source.service, snapshot, current.data)) ?? (history?.refs.base ? await history.text(history.refs.base) : null);
238
278
  if (baseMarkdown !== null && previous !== baseMarkdown) throw new Error(`Local edits exist for ${primaryLink(current).path}. Run \`wire sync ${primaryLink(current).path}\` before attaching this URL again.`);
239
279
  }
240
- if (!concurrentEdit && onDisk !== fetched.markdown) await dependencies.filesystem.writeText(outputPath, fetched.markdown);
280
+
241
281
  const id = resourceId(source);
242
282
  const primary = current?.filesystem_links.find((link) => link.path === relativePath && link.role === "primary");
283
+ const link = { path: relativePath, role: "primary", data: { ...(primary?.data ?? { format: "markdown" }), ...(enableReceipts ? {editor_receipts: true} : {}) } };
243
284
  const resource: Resource = {
244
285
  id,
245
286
  type: source.type,
246
287
  identifiers: [{ service: source.service, identifier: source.identifier }],
247
288
  urls: [url],
248
289
  filesystem_links: current === null
249
- ? [{ path: relativePath, role: "primary", data: { format: "markdown" } }]
290
+ ? [link]
250
291
  : [
251
- ...current.filesystem_links.filter((link) => !(link.path === relativePath && link.role === "primary")),
252
- primary ?? { path: relativePath, role: "primary", data: { format: "markdown" } },
253
- ],
292
+ ...current.filesystem_links.filter((link) => !(link.path === relativePath && link.role === "primary")),
293
+ link,
294
+ ],
254
295
  data: [
255
296
  ...(current?.data.filter((item) => item.namespace !== "wire" && !(item.namespace === source.service && item.key === "snapshot")) ?? []),
256
297
  { namespace: "wire", key: "title", value: fetched.title },
@@ -259,16 +300,78 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
259
300
  ],
260
301
  relationships: extractRelationships(fetched.markdown, id, dependencies.catalog),
261
302
  };
262
- const stored = await registry.put(resource);
303
+ let stored: Resource;
304
+ if (history) {
305
+ if (history.refs.conflict) throw new Error("Unresolved Wire conflict. Review the saved revisions and use wire resolve.");
306
+ const currentBase = history.refs.base;
307
+ if (onDisk !== null && currentBase !== null && onDisk !== await history.text(currentBase) && (previousMarkdown === undefined || previousMarkdown === onDisk)) await history.captureLocal(onDisk, view?.shown ?? undefined);
308
+ const draft = history.refs.draft;
309
+ let next: string;
310
+ if (currentBase === null) {
311
+ const input = previousMarkdown === undefined || previousMarkdown === null || previousMarkdown === fetched.markdown ? null : await history.revision("local", previousMarkdown, []);
312
+ next = await history.revision("attach", fetched.markdown, [input]);
313
+ }
314
+ else if (draft !== null && draft !== currentBase && action !== "downloaded") {
315
+ const remote = history.refs.remote;
316
+ const merged = remote !== null && (remote !== currentBase || (view?.base != null && view.base !== currentBase));
317
+ next = await history.revision(merged ? "merge" : "local", fetched.markdown, merged ? [draft, remote] : [draft]);
318
+ } else next = await history.observe(fetched);
319
+ const refs: typeof history.refs = { ...history.refs, base: next, remote: next, draft: null, strict: false, resolution: null, resolutionParent: null, conflict: null };
320
+ delete refs.editorDraft;
321
+ // A confirmed push of the exact draft the editor already saw is safe to
322
+ // acknowledge even if another save arrived while it was in flight.
323
+ if (concurrentEdit && previousMarkdown === fetched.markdown) {
324
+ await history.publish(outputPath, onDisk ?? "", onDisk ?? "", refs, resource, r => registry.put(r), true);
325
+ stored = await registry.get(resource.id);
326
+ } else if (concurrentEdit) {
327
+ if (current !== null) throw new Error(retry);
328
+ refs.base = previousMarkdown == null ? next : await history.revision("local", previousMarkdown, []);
329
+ refs.resolution = fetched;
330
+ refs.resolutionParent = next;
331
+ await history.publish(outputPath, onDisk ?? "", onDisk ?? "", refs, resource, r => registry.put(r), true);
332
+ stored = await registry.get(resource.id);
333
+ } else {
334
+ if (enableReceipts || refs.editorReceipts) refs.editorReceipts = { ...refs.editorReceipts };
335
+ const materialized = refs.editorReceipts ? editorFile(fetched.markdown, refs.editorReceipts, next, next) : fetched.markdown;
336
+ await history.publish(outputPath, raw, materialized, refs, resource, r => registry.put(r));
337
+ stored = await registry.get(resource.id);
338
+ }
339
+ } else {
340
+ if (!concurrentEdit && onDisk !== fetched.markdown) await dependencies.filesystem.writeText(outputPath, fetched.markdown);
341
+ stored = await registry.put(resource);
342
+ }
263
343
  if (concurrentEdit) throw new Error(retry);
264
344
  const changes = changeSummary(summaryMarkdown ?? previous, summaryAfterMarkdown);
265
345
  const resolvedAction = action === "attached" && current !== null && previous !== "" ? changes.added === 0 && changes.modified === 0 && changes.removed === 0 ? "synced" : "downloaded" : action;
266
346
  return { resource: stored, path: outputPath, markdown: fetched.markdown, summary: { action: resolvedAction, ...changes, remote: url, local: outputPath } };
267
347
  };
268
348
 
269
- const attach = async (url: string, path: string): Promise<WireResult> => {
270
- const fetched = await fetchSource(dependencies.fetchInput, url, dependencies.catalog);
271
- return store(url, path, fetched, undefined, "attached", undefined, undefined, fetched.markdown);
349
+ const attach = async (url: string, path: string, editorReceipts = false): Promise<WireResult> => {
350
+ return attachAt(url, path, undefined, editorReceipts);
351
+ };
352
+ const attachAt = async (url: string, path: string, fixed?: string, editorReceipts = false): Promise<WireResult> => {
353
+ const root = await wireRoot(dependencies, path), initial = await dependencies.workspace.openRegistry(root, dependencies.home);
354
+ const source = parseSourceUrl(url, dependencies.catalog);
355
+ return locked(root, initial, sourceLock(source), async () => {
356
+ const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
357
+ await owner(registry, source, url);
358
+ const h = await restore(root, registry, source);
359
+ const current = findResource(await registry.listResources(), source, dependencies.catalog);
360
+ checkReceiptLink(current, h);
361
+ if (editorReceipts && (!h || source.service !== "google-docs" || source.type !== "document" || dependencies.catalog.find(s => s.matches(new URL(url)))?.owner !== undefined)) throw new Error("Editor receipts require a generic Google Docs Markdown link with durable history.");
362
+ if (current && fixed !== undefined && join(dirname(root), primaryLink(current).path) !== fixed) throw new Error("This URL is already attached at another path.");
363
+ if (fixed !== undefined && (await registry.findByPath(dependencies.workspace.relativePath(fixed, root))).some(r => r.id !== resourceId(source))) throw new Error("This file already has another registration.");
364
+ if (h && current) await h.seed(markdownSnapshot(current.data.find(i => i.namespace === source.service && i.key === "snapshot")?.value ?? null));
365
+ if (h?.refs.conflict) throw new Error("Unresolved Wire conflict. Use wire resolve.");
366
+ if (h?.refs.strict) throw new Error("Sync the pending Wire draft before attaching again.");
367
+ const trackedPath = current ? join(dirname(root), primaryLink(current).path) : fixed;
368
+ if (h) await requireHistoryVolume(h.dir, trackedPath ? dirname(trackedPath) : path);
369
+ const raw = trackedPath && h ? await working(trackedPath) : undefined;
370
+ const existing = raw == null ? raw : h!.view(raw).markdown;
371
+ const fetched = await fetchSource(dependencies.fetchInput, url, dependencies.catalog);
372
+ if (fixed !== undefined && (h ? existing : await dependencies.filesystem.readText(fixed)) !== fetched.markdown) throw new Error("Cannot adopt: the existing file differs from the remote document.");
373
+ return store(url, path, fetched, fixed === undefined ? undefined : fetched.markdown, "attached", fixed, undefined, fetched.markdown, h, editorReceipts, raw);
374
+ });
272
375
  };
273
376
  const create = attach;
274
377
 
@@ -353,29 +456,67 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
353
456
  return registry.get(value);
354
457
  };
355
458
 
356
- const sync = async (value: string, path: string): Promise<WireResult> => {
459
+ const syncInner = async (value: string, path: string): Promise<WireResult> => {
357
460
  const candidatePath = resolve(path, value);
358
461
  const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidatePath) ? candidatePath : path);
359
462
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
360
463
  const relativePath = dependencies.workspace.relativePath(candidatePath, root);
361
464
  const pathResources = await registry.findByPath(relativePath);
362
465
  if (pathResources.length === 0 && await dependencies.filesystem.exists(candidatePath)) {
363
- const markdown = await dependencies.filesystem.readText(candidatePath);
364
- const uploaded = await uploadSource(dependencies.fetchInput, dependencies.catalog, markdown, candidatePath);
365
- return store(uploaded.url, dirname(candidatePath), uploaded, markdown, "uploaded", candidatePath, undefined, uploaded.markdown);
466
+ if (durable(registry)) await requireHistoryVolume(join(root, "history"), dirname(candidatePath));
467
+ const markdown = durable(registry) ? await working(candidatePath) : await dependencies.filesystem.readText(candidatePath);
468
+ if (markdown === null) throw new Error("Cannot upload a missing Markdown file.");
469
+ const uploaded = await uploadSource(dependencies.fetchInput, dependencies.catalog, plainMarkdown(markdown), candidatePath);
470
+ const source = parseSourceUrl(uploaded.url, dependencies.catalog);
471
+ return locked(root, registry, sourceLock(source), async () => store(uploaded.url, dirname(candidatePath), uploaded, markdown, "uploaded", candidatePath, undefined, uploaded.markdown, await restore(root, registry, source)));
366
472
  }
367
- const resource = await resolveResource(registry, value, root, path);
473
+ let resource = await resolveResource(registry, value, root, path);
368
474
  const outputPath = join(dirname(root), primaryLink(resource).path);
369
475
  const outputDirectory = dirname(outputPath);
370
476
  const source = legacyDefaultTab(resource, dependencies.catalog) ?? parseSourceUrl(resource.urls[0]!, dependencies.catalog);
477
+ await owner(registry, source, resource.urls[0]!);
478
+ const history = await restore(root, registry, source, outputPath);
479
+ resource = await registry.get(resource.id);
480
+ if (history) await requireHistoryVolume(history.dir, outputDirectory);
481
+ if (history?.refs.conflict && !("editor" in history.refs.conflict)) throw new Error("Unresolved Wire conflict. Inspect wire conflicts and use wire resolve.");
371
482
  const snapshot = resource.data.find((item) => item.namespace === source.service && item.key === "snapshot")?.value;
372
483
  if (snapshot === undefined) throw new Error(`Missing saved snapshot for ${primaryLink(resource).path}. Keep the local file and download a separate copy to reconcile before syncing.`);
373
484
  if (!(await dependencies.filesystem.exists(outputPath))) throw new Error(`Linked file missing: ${primaryLink(resource).path} - restore it or run wire detach`);
374
- const markdown = await dependencies.filesystem.readText(outputPath);
375
- const base = syncBase(source.service, snapshot, resource.data);
376
- const baseMarkdown = markdownSnapshot(base);
485
+ checkReceiptLink(resource, history);
486
+ let raw = history ? await working(outputPath) : await dependencies.filesystem.readText(outputPath);
487
+ if (raw === null) throw new Error("Linked file missing: " + outputPath);
488
+ let view = history ? history.view(raw) : editorView(raw);
489
+ await history?.checkPendingDraft(view);
490
+ if (history?.refs.conflict && "editor" in history.refs.conflict) {
491
+ const c = history.refs.conflict;
492
+ const merge = dependencies.catalog.find(s => s.matches(new URL(resource.urls[0]!)))?.mergeDrafts;
493
+ const base = c.editorBase === c.shellBase ? history.commonAncestor(c.editor, c.shell) : null;
494
+ let merged: string | undefined;
495
+ // A user may already be reconciling the file. Never overwrite edits
496
+ // that arrived after the two local versions were captured.
497
+ const editor = await history.text(c.editor);
498
+ if (merge && base && view.markdown === editor && view.base === c.editorBase) {
499
+ const before = await history.text(base), shell = await history.text(c.shell);
500
+ try { merged = merge(before, editor, shell); } catch { /* retain the saved conflict */ }
501
+ }
502
+ if (merged === undefined) 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>.");
503
+ const draft = await history.revision("merge", merged, [c.editor,c.shell]);
504
+ const receipts = { ...history.refs.editorReceipts! };
505
+ const next = editorFile(merged, receipts, draft, c.editorBase);
506
+ await history.publish(outputPath, raw, next, { ...history.refs, conflict: null, editorReceipts: receipts, editorDraft: draft, draft, strict: true }, null, r => registry.put(r));
507
+ raw = next;
508
+ view = history.view(raw);
509
+ }
510
+ const markdown = view.markdown;
511
+ // A stale receipt proves Markdown ancestry, not native paragraph positions.
512
+ // Never attach a newer snapshot's verified revision or IDs to older bytes.
513
+ const base = view.base && history && view.base !== history.refs.base && view.base !== history.refs.resolutionParent
514
+ ? { markdown: await history.text(view.base) }
515
+ : history?.refs.resolution && (!view.base || view.base === history.refs.resolutionParent) ? storedSnapshot(history.refs.resolution) : syncBase(source.service, snapshot, resource.data);
516
+ if (history) await history.seed(markdownSnapshot(snapshot));
517
+ const baseMarkdown = markdownSnapshot(base) ?? (history?.refs.base ? await history.text(history.refs.base) : null);
377
518
  const localChanged = baseMarkdown !== null && markdown !== baseMarkdown;
378
- if (localChanged && !serviceCanSynchronize(resource.urls[0]!, dependencies.catalog)) throw new Error(`${source.service} is download-only and the local file has edits. Run \`wire download ${primaryLink(resource).path}\` to discard them.`);
519
+ if (localChanged && !history?.refs.strict && !serviceCanSynchronize(resource.urls[0]!, dependencies.catalog)) throw new Error(`${source.service} is download-only and the local file has edits. Run \`wire download ${primaryLink(resource).path}\` to discard them.`);
379
520
  if (source.service === "google-docs" && source["document_tab"] === "t.0") {
380
521
  const registered = findResource(await registry.listResources(), source, dependencies.catalog);
381
522
  if (registered && legacyDefaultTab(registered, dependencies.catalog)) {
@@ -388,35 +529,108 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
388
529
  await registry.rekey(registered, { service: source.service, identifier: source.identifier });
389
530
  }
390
531
  }
391
- const fetched = await synchronizeSource(dependencies.fetchInput, resource.urls[0]!, dependencies.catalog, base, markdown, outputPath);
532
+ if (history && (localChanged || history.refs.draft !== null)) await history.captureLocal(markdown, view.shown ?? undefined);
533
+ const strict = (history?.refs.strict === true || view.base !== null) && localChanged;
534
+ if (history && strict && source.service !== "notion" && !(source.service === "google-docs" && source.type === "document")) {
535
+ const remote = await fetchSource(dependencies.fetchInput, resource.urls[0]!, dependencies.catalog);
536
+ await history.observe(remote); await history.save();
537
+ if (remote.markdown !== markdown) 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.");
538
+ return store(resource.urls[0]!, outputDirectory, remote, markdown, "synced", undefined, undefined, remote.markdown, history);
539
+ }
540
+ const observed: { remote?: FetchedDocument } = {};
541
+ let observations = Promise.resolve();
542
+ const fork = view.base ?? (history?.refs.resolution ? history.refs.resolutionParent : history?.refs.base);
543
+ let fetched;
544
+ try {
545
+ fetched = await synchronizeSource(dependencies.fetchInput, resource.urls[0]!, dependencies.catalog, base, markdown, outputPath, remote => {
546
+ plainMarkdown(remote.markdown);
547
+ observed.remote = remote;
548
+ observations = observations.then(async () => { if (history) { await history.observe(remote); await history.save(); } });
549
+ return observations;
550
+ }, strict);
551
+ await observations;
552
+ } catch (error) {
553
+ await observations;
554
+ if (history && error instanceof WireMergeConflict && observed.remote && history.refs.draft && history.refs.remote) {
555
+ if (fork) {
556
+ history.refs.conflict = { base: fork, local: history.refs.draft, remote: history.refs.remote };
557
+ history.refs.resolution = observed.remote;
558
+ history.refs.resolutionParent = history.refs.remote;
559
+ await history.save();
560
+ throw new Error("Unresolved Wire conflict. " + error.message + " Inspect wire conflicts and use wire resolve.", { cause: error });
561
+ }
562
+ }
563
+ throw error;
564
+ }
565
+ if (history && !observed.remote && fetched.markdown !== markdown) { await history.observe(fetched); await history.save(); }
392
566
  const uploaded = fetched.wroteRemote ?? (localChanged && fetched.markdown !== baseMarkdown);
393
567
  const action = uploaded ? "uploaded" : fetched.markdown === markdown || (localChanged && fetched.markdown === baseMarkdown) ? "synced" : "downloaded";
394
- return store(resource.urls[0]!, outputDirectory, fetched, markdown, action, undefined, action === "uploaded" && baseMarkdown !== null ? baseMarkdown : undefined, action === "uploaded" ? markdown : fetched.markdown);
568
+ return store(resource.urls[0]!, outputDirectory, fetched, markdown, action, undefined, action === "uploaded" && baseMarkdown !== null ? baseMarkdown : undefined, action === "uploaded" ? markdown : fetched.markdown, history, false, raw);
395
569
  };
396
570
 
397
- const download = async (value: string, path: string): Promise<WireResult> => {
571
+ const underResourceLock = async <T>(value: string, path: string, fn: () => Promise<T>) => {
572
+ const candidate = resolve(path, value);
573
+ const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidate) ? candidate : path), registry = await dependencies.workspace.openRegistry(root, dependencies.home);
574
+ const ids = await registry.findByPath(dependencies.workspace.relativePath(candidate, root));
575
+ 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));
576
+ return locked(root, registry, key, fn);
577
+ };
578
+ const sync = (v: string, p: string) => underResourceLock(v, p, () => syncInner(v, p));
579
+ const downloadInner = async (value: string, path: string): Promise<WireResult> => {
398
580
  const candidatePath = resolve(path, value);
399
581
  const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidatePath) ? candidatePath : path);
400
582
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
401
583
  const resource = await resolveResource(registry, value, root, path);
402
584
  const outputPath = join(dirname(root), primaryLink(resource).path);
403
- const markdown = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
585
+ const source = parseSourceUrl(resource.urls[0]!, dependencies.catalog);
586
+ await owner(registry, source, resource.urls[0]!);
587
+ const h = await restore(root, registry, source, outputPath);
588
+ await h?.seed(markdownSnapshot(resource.data.find(i => i.namespace === source.service && i.key === "snapshot")?.value ?? null));
589
+ if (h?.refs.conflict) throw new Error("Unresolved Wire conflict. Use wire resolve.");
590
+ checkReceiptLink(resource, h);
591
+ const raw = h ? await working(outputPath) : await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
592
+ const markdown = raw === null ? null : (h ? h.view(raw) : editorView(raw)).markdown;
593
+ if (h?.refs.strict && h.refs.draft) throw new Error("Sync the pending Wire draft before downloading over it.");
404
594
  const fetched = await fetchSource(dependencies.fetchInput, resource.urls[0]!, dependencies.catalog);
405
- return store(resource.urls[0]!, dirname(outputPath), fetched, markdown, "downloaded", undefined, undefined, fetched.markdown);
595
+ return store(resource.urls[0]!, dirname(outputPath), fetched, markdown, "downloaded", undefined, undefined, fetched.markdown, h, false, raw);
406
596
  };
407
597
 
408
- const detach = async (value: string, path: string): Promise<WireResult> => {
598
+ const download = (v: string, p: string) => underResourceLock(v, p, () => downloadInner(v, p));
599
+ const detachInner = async (value: string, path: string): Promise<WireResult> => {
409
600
  const candidatePath = resolve(path, value);
410
601
  const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidatePath) ? candidatePath : path);
411
602
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
412
603
  const resource = await resolveResource(registry, value, root, path);
413
604
  const outputPath = join(dirname(root), primaryLink(resource).path);
414
- const previous = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : "";
605
+ const source = parseSourceUrl(resource.urls[0]!, dependencies.catalog);
606
+ await owner(registry, source, resource.urls[0]!);
607
+ const h = await historyFor(root, registry, source);
608
+ const recovered = await h?.recover(outputPath, r => registry.put(r), removeDetached(registry));
609
+ if (recovered) {
610
+ const markdown = await h!.text(h!.refs.base!);
611
+ return { resource: recovered, path: outputPath, markdown, summary: { action: "detached", added: 0, modified: 0, removed: 0, remote: recovered.urls[0]!, local: outputPath } };
612
+ }
613
+ checkReceiptLink(resource, h);
614
+ const initialRaw = h ? await working(outputPath) : await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
615
+ const previousView = initialRaw === null ? null : (h ? h.view(initialRaw) : editorView(initialRaw));
616
+ const previous = previousView?.markdown ?? "";
617
+ if (h?.refs.conflict || h?.refs.strict) throw new Error("Resolve and sync the Wire draft before detaching.");
415
618
  const fetched = await fetchSource(dependencies.fetchInput, resource.urls[0]!, dependencies.catalog);
416
- await dependencies.filesystem.writeText(outputPath, fetched.markdown);
417
- await registry.delete(resource.id);
619
+ if (h) {
620
+ const onDisk = await working(outputPath);
621
+ if (onDisk !== initialRaw) throw new Error("Local file changed during detach; retry.");
622
+ if (previousView) await h.captureLocal(previousView.markdown, previousView.shown ?? undefined);
623
+ const next = await h.observe(fetched);
624
+ const {editorReceipts, ...plainRefs} = h.refs;
625
+ if (editorReceipts) plainRefs.retiredEditorReceipts = { ...plainRefs.retiredEditorReceipts, ...editorReceipts };
626
+ await h.detach(outputPath, onDisk, fetched.markdown, { ...plainRefs, base: next, remote: next, draft: null }, resource, removeDetached(registry));
627
+ } else {
628
+ await dependencies.filesystem.writeText(outputPath, fetched.markdown);
629
+ await registry.delete(resource.id);
630
+ }
418
631
  return { resource, path: outputPath, markdown: fetched.markdown, summary: { action: "detached", ...changeSummary(previous, fetched.markdown), remote: resource.urls[0]!, local: outputPath } };
419
632
  };
633
+ const detach = (v: string, p: string) => underResourceLock(v, p, () => detachInner(v, p));
420
634
  const unlink = detach;
421
635
 
422
636
  const runWatchHooks = async (hooks: readonly WireWatchSyncHook[], command: WireWatchSyncCommand, result: WireResult): Promise<WireResult> => {
@@ -453,6 +667,12 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
453
667
  if (!checkRemote && await dependencies.filesystem.readText(outputPath) === lastSyncedMarkdown) continue;
454
668
  const result = config.mode === "download" ? await runWatchHooks(hooks, "download", await download(value, path)) : await runWatchHooks(hooks, "sync", await sync(value, path));
455
669
  lastSyncedMarkdown = result.markdown;
670
+ if (primaryLink(result.resource).data["editor_receipts"] === true) {
671
+ const h = await historyFor(root, registry, parseSourceUrl(result.resource.urls[0]!, dependencies.catalog));
672
+ if (h?.refs.editorReceipts && h.refs.base && await h.text(h.refs.base) === result.markdown) {
673
+ lastSyncedMarkdown = editorFile(result.markdown, h.refs.editorReceipts, h.refs.base, h.refs.base);
674
+ }
675
+ }
456
676
  } catch (error) {
457
677
  console.warn(`Wire watch: ${errorMessage(error)}`);
458
678
  }
@@ -530,8 +750,94 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
530
750
  return resolveResource(registry, value, root, path);
531
751
  };
532
752
 
753
+ const withDocument = async <T>(v: string, p: string, run: (h: DocumentHistory, path: string, registry: Registry, resource: Resource) => Promise<T>) => underResourceLock(v, p, async () => {
754
+ const candidate = resolve(p, v), root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidate) ? candidate : p);
755
+ const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
756
+ let r = await resolveResource(registry, v, root, p);
757
+ const path = join(dirname(root), primaryLink(r).path);
758
+ const source = parseSourceUrl(r.urls[0]!, dependencies.catalog);
759
+ const h = await restore(root, registry, source, path);
760
+ if (!h) throw new Error("This registry does not provide durable document history.");
761
+ r = await registry.get(r.id);
762
+ checkReceiptLink(r, h);
763
+ await h.seed(markdownSnapshot(r.data.find(i => i.namespace === source.service && i.key === "snapshot")?.value ?? null));
764
+ return run(h, path, registry, r);
765
+ });
766
+ const historyStatus = (v: string, p: string) => withDocument(v, p, async (h, path) => {
767
+ const raw = await working(path);
768
+ if (raw !== null) await h.checkPendingDraft(h.view(raw));
769
+ return h.status(path);
770
+ });
771
+ const historyLog = (v: string, p: string) => withDocument(v, p, h => h.log());
772
+ const historyDiff = (v: string, p: string, from = "base", to = "working") => withDocument(v, p, async (h, path) => {
773
+ const raw = await working(path);
774
+ const current = raw === null ? null : h.view(raw).markdown;
775
+ const text = async (ref: string) => {
776
+ if (ref === "working") { if (current === null) throw new Error("Linked Markdown is missing."); return current; }
777
+ const c = h.refs.conflict;
778
+ const id = c && "editor" in c && (ref === "editor" || ref === "shell") ? c[ref]
779
+ : ref === "base" ? (c && "base" in c ? c.base : h.refs.base)
780
+ : ref === "remote" ? h.refs.remote : ref === "local" ? (c && "local" in c ? c.local : h.refs.draft ?? h.refs.base) : ref;
781
+ if (!id) throw new Error("No saved " + ref + " revision.");
782
+ return h.text(id);
783
+ };
784
+ return { from, to, before: await text(from), after: await text(to), token: h.token(raw) };
785
+ });
786
+ const checkpoint = (v: string, p: string, expected: string, markdown: string, token: string) => withDocument(v, p, async (h, path, reg) => {
787
+ const raw = await working(path);
788
+ const view = raw === null ? null : h.view(raw);
789
+ if (!view || view.markdown !== expected || token !== h.token(raw)) throw new Error("Stale shell edit. The document changed; rerun the command.");
790
+ if (expected !== markdown) {
791
+ await h.checkPendingDraft(view);
792
+ if (h.refs.conflict && "editor" in h.refs.conflict) 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.");
793
+ plainMarkdown(markdown);
794
+ const prior = await h.captureLocal(expected, view.shown ?? undefined);
795
+ const draft = await h.revision("local", markdown, [prior]);
796
+ const refs = { ...h.refs, draft, strict: true, ...(view.base ? {editorDraft: draft} : {}) };
797
+ if (refs.editorReceipts) refs.editorReceipts = { ...refs.editorReceipts };
798
+ const next = refs.editorReceipts && view.base ? editorFile(markdown, refs.editorReceipts, draft, view.base) : markdown;
799
+ await h.publish(path, raw, next, refs, null, r => reg.put(r));
800
+ }
801
+ return h.status(path);
802
+ });
803
+ const resolveConflict = (v: string, p: string, choice: "local" | "remote" | "working" | "editor" | "shell") => withDocument(v, p, async (h, path, reg) => {
804
+ const raw = await working(path);
805
+ if (raw === null) throw new Error("Linked Markdown is missing.");
806
+ const view = h.view(raw), current = view.markdown;
807
+ await h.checkPendingDraft(view);
808
+ const conflict = h.refs.conflict;
809
+ if (!conflict) throw new Error("No saved conflict for this document.");
810
+ let next: string, basis: string, parents: string[];
811
+ if ("editor" in conflict) {
812
+ if (!["working","editor","shell"].includes(choice)) throw new Error("Both drafts are local. Choose editor, shell or working.");
813
+ if (choice !== "working" && current !== await h.text(conflict.editor)) throw new Error("Working file changed since the conflict. Choose working to retain those edits.");
814
+ // The file being reconciled is the editor branch. Keep its remote basis
815
+ // for an edited working resolution; never silently adopt a later base.
816
+ basis = choice === "shell" ? conflict.shellBase : conflict.editorBase;
817
+ if (choice === "working" && view.base !== conflict.editorBase) throw new Error("The working file has a different receipt. Restore the conflicted editor receipt before resolving.");
818
+ next = choice === "working" ? current : await h.text(choice === "shell" ? conflict.shell : conflict.editor);
819
+ parents = [conflict.editor, conflict.shell];
820
+ } else {
821
+ if (!h.refs.resolution) throw new Error("Missing saved provider conflict snapshot.");
822
+ if (!["working","local","remote"].includes(choice)) throw new Error("Choose local, remote or working.");
823
+ const local = await h.text(conflict.local);
824
+ if (choice !== "working" && current !== local) throw new Error("Working file changed since the conflict. Choose working to retain those edits.");
825
+ next = choice === "working" ? current : choice === "local" ? local : await h.text(conflict.remote);
826
+ basis = conflict.remote;
827
+ parents = [conflict.local, conflict.remote];
828
+ }
829
+ const draft = await h.revision("resolve", next, parents);
830
+ const refs = { ...h.refs, draft, strict: true, conflict: null, ...(h.refs.editorReceipts ? {editorDraft: draft} : {}) };
831
+ if (refs.editorReceipts) refs.editorReceipts = { ...refs.editorReceipts };
832
+ const materialized = refs.editorReceipts ? editorFile(next, refs.editorReceipts, draft, basis) : next;
833
+ await h.publish(path, raw, materialized, refs, null, r => reg.put(r));
834
+ return h.status(path);
835
+ });
836
+
533
837
  return Object.freeze({
534
838
  attach,
839
+ adopt: (url: string, path: string, editorReceipts = false) => attachAt(url, dirname(resolve(path)), resolve(path), editorReceipts),
840
+ historyStatus, historyDiff, historyLog, checkpoint, resolveConflict,
535
841
  create,
536
842
  view,
537
843
  downloadSource,
@@ -166,7 +166,7 @@ export function serializeNetscapeCookies(cookies: readonly Cookie[], metadata: R
166
166
 
167
167
  export function createCookiesCapability(filesystem: FilesystemCapability, home: () => string, repositoryRoot?: () => string | undefined, overrideFile?: (service: string) => string | undefined): CookiesCapability {
168
168
  const paths = (service: string) => {
169
- if (service === "ashby") return [cookiesFile(home(), service)];
169
+ if (service === "ashby" || service === "codesignal") return [cookiesFile(home(), service)];
170
170
  const overridePath = overrideFile?.(service);
171
171
  const repositoryRootPath = repositoryRoot?.();
172
172
  return [
@@ -0,0 +1,27 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { invalidReceipt, plainMarkdown, receiptEnvelope } from "../core/editor-receipts.js";
3
+ export { hasEditorReceipt, plainMarkdown } from "../core/editor-receipts.js";
4
+
5
+ // Receipts travel with an editor's buffer. Only this link's private history
6
+ // can associate one with the text shown and the remote base that text used.
7
+ export type EditorReceipts = Record<string, { shown: string; base: string; crlf: boolean }>;
8
+ const prefix = "wire-editor-basis:";
9
+ export function editorView(raw: string, receipts?: EditorReceipts) {
10
+ if (!receipts) return { markdown: plainMarkdown(raw), shown: null, base: null };
11
+ const mark = /\n<!-- wire-editor-basis:v1:([a-f0-9]{48}) -->/.exec(raw);
12
+ if (!mark || raw.match(receiptEnvelope)?.length !== 1) throw invalidReceipt();
13
+ const record = receipts[mark[1]!];
14
+ if (!record || record.crlf !== (raw[mark.index - 1] === "\r")) throw invalidReceipt();
15
+ const suffix = raw.slice(mark.index + mark[0].length);
16
+ if (suffix && !/^(?:\r\n|\n)/.test(suffix)) throw invalidReceipt();
17
+ return { markdown: raw.slice(0, mark.index - Number(record.crlf)) + suffix, shown: record.shown, base: record.base };
18
+ }
19
+
20
+ export function editorFile(text: string, receipts: EditorReceipts, shown: string, base: string) {
21
+ plainMarkdown(text);
22
+ const crlf = text.endsWith("\r") || text.includes("\r\n");
23
+ const existing = Object.entries(receipts).find(([, r]) => r.shown === shown && r.base === base && r.crlf === crlf);
24
+ const key = existing?.[0] ?? randomBytes(24).toString("hex");
25
+ receipts[key] = { shown, base, crlf };
26
+ return text + (crlf ? "\r\n" : "\n") + "<!-- " + prefix + "v1:" + key + " -->";
27
+ }
@@ -0,0 +1,25 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { HistoryRefs } from "./history.js";
3
+
4
+ const digest = /^[a-f0-9]{64}$/;
5
+ export const transactionId = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
6
+
7
+ export function validateRefs(refs: HistoryRefs) {
8
+ const corrupt = () => { throw new Error("Corrupt Wire history references. Restore the private history from a backup before syncing."); };
9
+ const known = new Set<string>();
10
+ if (!refs || !Array.isArray(refs.revisions)) return corrupt();
11
+ for (const r of refs.revisions) {
12
+ if (!r || !digest.test(r.blob) || !Array.isArray(r.parents) || r.parents.some(p => !known.has(p)) || known.has(r.id)) return corrupt();
13
+ if (createHash("sha256").update(JSON.stringify([r.kind,r.blob,r.parents])).digest("hex") !== r.id) return corrupt();
14
+ known.add(r.id);
15
+ }
16
+ for (const ref of [refs.base, refs.remote, refs.draft, refs.resolutionParent, refs.editorDraft]) if (ref != null && !known.has(ref)) return corrupt();
17
+ for (const receipts of [refs.editorReceipts, refs.retiredEditorReceipts]) if (receipts !== undefined) {
18
+ if (!receipts || typeof receipts !== "object" || Array.isArray(receipts)) return corrupt();
19
+ for (const [key, record] of Object.entries(receipts)) {
20
+ if (!/^[a-f0-9]{48}$/.test(key) || !record || typeof record.crlf !== "boolean" || !known.has(record.shown) || !known.has(record.base)) return corrupt();
21
+ }
22
+ }
23
+ const c = refs.conflict;
24
+ if (c && !("editor" in c ? [c.editor,c.shell,c.editorBase,c.shellBase] : [c.base,c.local,c.remote]).every(ref => known.has(ref))) return corrupt();
25
+ }