@open-document/core 0.13.0 → 0.13.1

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.
@@ -1,4 +1,4 @@
1
- import { t as createViteConfig } from "./config-DKKNIbvO.js";
1
+ import { t as createViteConfig } from "./config-CltJJVsw.js";
2
2
  import path from "node:path";
3
3
  import { build as build$1, mergeConfig } from "vite";
4
4
  //#region src/cli/build.ts
@@ -1,6 +1,6 @@
1
- import { D as listDocIds } from "./config-DKKNIbvO.js";
2
- import { n as closeRenderSession, t as checkLayout } from "./ops-DmEecq1k.js";
3
- import { t as cliContext } from "./context-DXNP8v9I.js";
1
+ import { j as listDocIds } from "./config-CltJJVsw.js";
2
+ import { n as closeRenderSession, t as checkLayout } from "./ops-CSR5RlrE.js";
3
+ import { t as cliContext } from "./context-CWgfsHoE.js";
4
4
  import chalk from "chalk";
5
5
  //#region src/cli/check.ts
6
6
  function line(finding) {
package/dist/cli/bin.js CHANGED
@@ -154,39 +154,39 @@ async function run(argv) {
154
154
  program.name("open-doc").description("Author documents — we handle the Vite/React stack, pagination, and export.").version(version, "-v, --version", "print version").helpOption("-h, --help", "show help").showHelpAfterError(chalk.dim("(run `open-doc --help` for usage)"));
155
155
  program.command("dev").description("Start the dev server").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).addOption(new Option("--host [host]", "expose on the network (optional host)")).option("--open", "open the browser on start").option("--no-skills-check", "skip the built-in skills drift check").option("--mcp", "serve an MCP endpoint at /mcp (requires @open-document/mcp)").action(async (flags) => {
156
156
  if (flags.skillsCheck !== false) await runSkillsDriftCheck(resolveBuiltinSkillsDir());
157
- const { dev } = await import("../dev-YXumw5iX.js");
157
+ const { dev } = await import("../dev-B8H2qT6G.js");
158
158
  await dev(flags);
159
159
  });
160
160
  program.command("build").description("Build a static site").option("--out-dir <dir>", "output directory (defaults to `dist`)").action(async (flags) => {
161
- const { build } = await import("../build-CbgIk6bA.js");
161
+ const { build } = await import("../build-CvsOak5B.js");
162
162
  await build(flags);
163
163
  });
164
164
  program.command("preview").description("Preview the production build").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).addOption(new Option("--host [host]", "expose on the network (optional host)")).option("--open", "open the browser on start").action(async (flags) => {
165
- const { preview } = await import("../preview-_mHpBhMk.js");
165
+ const { preview } = await import("../preview-DYMUNjXL.js");
166
166
  await preview(flags);
167
167
  });
168
168
  program.command("export [docIds...]").description("Render documents headlessly to PDF, HTML, PNG, or DOCX").addOption(new Option("-f, --format <format>", "output format").choices([...EXPORT_FORMATS])).option("-o, --out-dir <dir>", "directory to write into (defaults to `out`)").option("--all", "export every document under docs/").option("--each", "one copy per row of the document's `records`").option("--name <pattern>", "with --each: file name, e.g. \"certificate-{name}\" ({#} is the row number)").action(async (docIds, flags) => {
169
- const { exportDocs } = await import("../export-D2QLtF84.js");
169
+ const { exportDocs } = await import("../export-DX30_s2q.js");
170
170
  await exportDocs(docIds, flags);
171
171
  });
172
172
  program.command("diff <docId>").description("Show what changed in a document since a git revision, page by page").option("-s, --since <rev>", "revision to compare against (defaults to HEAD)").option("-o, --out-dir <dir>", "directory to write the report into (defaults to `out`)").option("--json", "print the result as JSON").action(async (docId, flags) => {
173
- const { diffDoc } = await import("../diff-CTFfU4Tz.js");
173
+ const { diffDoc } = await import("../diff-BvIjjgnc.js");
174
174
  await diffDoc(docId, flags);
175
175
  });
176
176
  program.command("check [docIds...]").description("Report layout faults — clipped content, blank sheets, stranded headings").option("--json", "print the full report as JSON").action(async (docIds, flags) => {
177
- const { checkDocs } = await import("../check-BTroj-5Z.js");
177
+ const { checkDocs } = await import("../check-CbUBwYmf.js");
178
178
  await checkDocs(docIds, flags);
179
179
  });
180
180
  program.command("templates").description("List the templates a new document can start from").option("--json", "print them as JSON").action(async (flags) => {
181
- const { printTemplates } = await import("../templates-MMblHwmT.js");
181
+ const { printTemplates } = await import("../templates-B5Tz0AKb.js");
182
182
  await printTemplates(flags);
183
183
  });
184
184
  program.command("new [docId]").description("Create a document under docs/ from a template (see `open-doc templates`)").option("-t, --template <name>", "template to start from (defaults to blank)").option("--title <title>", "title of the new document").action(async (docId, flags) => {
185
- const { newDoc } = await import("../templates-MMblHwmT.js");
185
+ const { newDoc } = await import("../templates-B5Tz0AKb.js");
186
186
  await newDoc(docId, flags);
187
187
  });
188
188
  program.command("import <file>").description("Turn a Markdown file into a document under docs/").option("--id <id>", "document id (defaults to a slug of the title)").option("--title <title>", "override the title").option("--subtitle <subtitle>", "subtitle, also used as the cover eyebrow").option("--lang <tag>", "language of the text, e.g. zh-Hant-TW (detected for CJK when omitted)").option("--author <author>", "author line on the cover").option("--theme <theme>", "theme id to back-link from meta.theme").addOption(new Option("--page-size <size>", "page size").choices(PAGE_SIZE_NAMES)).addOption(new Option("--orientation <orientation>", "page orientation").choices(ORIENTATIONS)).option("--no-cover", "skip the title page").option("--contents", "add a self-filling contents page").action(async (file, flags) => {
189
- const { importDoc } = await import("../import-CcmrFetU.js");
189
+ const { importDoc } = await import("../import-DgsdJT5e.js");
190
190
  await importDoc(file, flags);
191
191
  });
192
192
  program.command("sync:skills").description("Sync built-in skills from @open-document/core into this workspace").option("--dry-run", "show what would change without writing").action(async (flags) => {
@@ -647,53 +647,67 @@ async function listDocuments(ctx) {
647
647
  async function readDocument(ctx, docId) {
648
648
  const entry = resolveEntry(ctx, docId);
649
649
  if (!entry) throw new OpsError(404, `document not found: ${docId}`);
650
+ const source = await fs.readFile(entry, "utf8");
650
651
  return {
651
652
  id: docId,
652
653
  entry: path.relative(ctx.userCwd, entry),
653
- source: await fs.readFile(entry, "utf8")
654
+ source,
655
+ hash: hashSource(source)
654
656
  };
655
657
  }
656
658
  async function createDocument(ctx, docId, source) {
657
659
  const dir = docDir(ctx, docId);
658
- if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
659
- await fs.mkdir(dir, { recursive: true });
660
660
  const entry = path.join(dir, "index.tsx");
661
- await fs.writeFile(entry, source, "utf8");
662
- return {
663
- id: docId,
664
- entry: path.relative(ctx.userCwd, entry)
665
- };
661
+ return withFileLock(entry, async () => {
662
+ if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
663
+ await fs.mkdir(dir, { recursive: true });
664
+ await fs.writeFile(entry, source, "utf8");
665
+ return {
666
+ id: docId,
667
+ entry: path.relative(ctx.userCwd, entry),
668
+ hash: hashSource(source)
669
+ };
670
+ });
666
671
  }
667
672
  /**
668
- * Whole-file overwrite. `expected` is the source the caller believes is on
669
- * disk; passing it turns a blind overwrite into a conflict check, which is what
670
- * keeps two agents (or an agent and a person) from clobbering each other.
673
+ * Whole-file overwrite. `expected` (full source) or `expectedHash` (16-char
674
+ * SHA-256 digest from `readDocument`) turns a blind overwrite into an atomic
675
+ * conflict check inside a per-file write lock, keeping two agents (or an agent
676
+ * and a person on GCS FUSE) from clobbering each other.
671
677
  */
672
- async function writeDocument(ctx, docId, source, expected) {
678
+ async function writeDocument(ctx, docId, source, expected, expectedHash) {
673
679
  const entry = resolveEntry(ctx, docId);
674
680
  if (!entry) throw new OpsError(404, `document not found: ${docId}`);
675
- if (expected !== void 0) {
676
- if (await fs.readFile(entry, "utf8") !== expected) throw new OpsError(409, "document changed on disk since it was read");
677
- }
678
- await fs.writeFile(entry, source, "utf8");
679
- return {
680
- id: docId,
681
- entry: path.relative(ctx.userCwd, entry)
682
- };
681
+ return withFileLock(entry, async () => {
682
+ if (expected !== void 0 || expectedHash !== void 0) assertExpectedSource(await fs.readFile(entry, "utf8"), {
683
+ expected,
684
+ expectedHash
685
+ });
686
+ await fs.writeFile(entry, source, "utf8");
687
+ return {
688
+ id: docId,
689
+ entry: path.relative(ctx.userCwd, entry),
690
+ hash: hashSource(source)
691
+ };
692
+ });
683
693
  }
684
- async function renameDocument(ctx, docId, rawTitle) {
694
+ async function renameDocument(ctx, docId, rawTitle, opts = {}) {
685
695
  const title = validateDocTitle(rawTitle);
686
696
  if (!title) throw new OpsError(400, "invalid title");
687
697
  const entry = resolveEntry(ctx, docId);
688
698
  if (!entry) throw new OpsError(404, `document not found: ${docId}`);
689
- const source = await fs.readFile(entry, "utf8");
690
- const next = setMetaTitle(source, title);
691
- if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
692
- if (next !== source) await fs.writeFile(entry, next, "utf8");
693
- return {
694
- id: docId,
695
- title
696
- };
699
+ return withFileLock(entry, async () => {
700
+ const source = await fs.readFile(entry, "utf8");
701
+ assertExpectedSource(source, opts);
702
+ const next = setMetaTitle(source, title);
703
+ if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
704
+ if (next !== source) await fs.writeFile(entry, next, "utf8");
705
+ return {
706
+ id: docId,
707
+ title,
708
+ hash: hashSource(next)
709
+ };
710
+ });
697
711
  }
698
712
  async function duplicateDocument(ctx, docId, newId) {
699
713
  const dir = docDir(ctx, docId);
@@ -707,17 +721,19 @@ async function duplicateDocument(ctx, docId, newId) {
707
721
  } else targetId = nextCopyId(docId, taken);
708
722
  await fs.cp(dir, docDir(ctx, targetId), { recursive: true });
709
723
  const entry = resolveEntry(ctx, targetId);
710
- if (entry) {
724
+ if (entry) await withFileLock(entry, async () => {
711
725
  const source = await fs.readFile(entry, "utf8");
712
726
  const renamed = setMetaTitle(source, copyTitle(readMetaTitle(source) ?? docId));
713
727
  if (renamed && renamed !== source) await fs.writeFile(entry, renamed, "utf8");
714
- }
715
- const manifest = await readManifest(ctx.manifestPath);
716
- const folderId = manifest.assignments[docId];
717
- if (folderId) {
718
- manifest.assignments[targetId] = folderId;
719
- await writeManifest(ctx.manifestPath, manifest);
720
- }
728
+ });
729
+ await withFileLock(ctx.manifestPath, async () => {
730
+ const manifest = await readManifest(ctx.manifestPath);
731
+ const folderId = manifest.assignments[docId];
732
+ if (folderId) {
733
+ manifest.assignments[targetId] = folderId;
734
+ await writeManifest(ctx.manifestPath, manifest);
735
+ }
736
+ });
721
737
  return { id: targetId };
722
738
  }
723
739
  async function deleteDocument(ctx, docId) {
@@ -727,10 +743,53 @@ async function deleteDocument(ctx, docId) {
727
743
  recursive: true,
728
744
  force: true
729
745
  });
730
- const manifest = await readManifest(ctx.manifestPath);
731
- if (manifest.assignments[docId]) {
732
- delete manifest.assignments[docId];
733
- await writeManifest(ctx.manifestPath, manifest);
746
+ await withFileLock(ctx.manifestPath, async () => {
747
+ const manifest = await readManifest(ctx.manifestPath);
748
+ if (manifest.assignments[docId]) {
749
+ delete manifest.assignments[docId];
750
+ await writeManifest(ctx.manifestPath, manifest);
751
+ }
752
+ });
753
+ }
754
+ //#endregion
755
+ //#region src/ops/concurrency.ts
756
+ /**
757
+ * Deterministic 16-char SHA-256 hex digest of a document's UTF-8 source.
758
+ * Used as a lightweight optimistic concurrency token (`hash` / `expectedHash`)
759
+ * so clients and MCP agents do not need to re-send the full source string.
760
+ */
761
+ function hashSource(source) {
762
+ return createHash("sha256").update(source, "utf8").digest("hex").slice(0, 16);
763
+ }
764
+ /**
765
+ * Verifies that `current` on disk still matches what the caller last read,
766
+ * either via full-source comparison (`expected`) or SHA-256 digest (`expectedHash`).
767
+ */
768
+ function assertExpectedSource(current, opts) {
769
+ if (opts?.expected !== void 0 && current !== opts.expected) throw new OpsError(409, "document changed on disk since it was read");
770
+ if (opts?.expectedHash !== void 0 && hashSource(current) !== opts.expectedHash) throw new OpsError(409, "document changed on disk since it was read (hash mismatch)");
771
+ }
772
+ const fileQueues = /* @__PURE__ */ new Map();
773
+ /**
774
+ * Serializes async read-modify-write operations on the same file path in FIFO order.
775
+ * Prevents concurrent edits (e.g. over high-latency GCS FUSE mounts or parallel
776
+ * MCP tool calls) from reading the same stale snapshot and overwriting each other.
777
+ */
778
+ async function withFileLock(filePath, fn) {
779
+ const key = path.resolve(filePath);
780
+ const prev = fileQueues.get(key) ?? Promise.resolve();
781
+ let release;
782
+ const gate = new Promise((resolve) => {
783
+ release = resolve;
784
+ });
785
+ const tail = prev.then(() => gate);
786
+ fileQueues.set(key, tail);
787
+ await prev;
788
+ try {
789
+ return await fn();
790
+ } finally {
791
+ release();
792
+ if (fileQueues.get(key) === tail) fileQueues.delete(key);
734
793
  }
735
794
  }
736
795
  //#endregion
@@ -855,11 +914,13 @@ async function revertChange(ctx, docId, opts) {
855
914
  if (!file || !hunk) throw new OpsError(409, "that change is no longer there — reload the changes");
856
915
  if (file.binary) throw new OpsError(422, "a binary file cannot be reverted here");
857
916
  const target = path.join(ctx.docsRoot, docId, file.path);
858
- const next = revertHunkIn(await fs.readFile(target, "utf8"), hunk);
859
- if (next === null) throw new OpsError(409, "the file changed since the diff was read");
860
- if (/\.(tsx?|jsx?)$/.test(file.path) && !parseStrict(next)) throw new OpsError(422, "reverting this change alone would break the source — revert the changes around it too");
861
- await fs.writeFile(target, next, "utf8");
862
- return { ok: true };
917
+ return withFileLock(target, async () => {
918
+ const next = revertHunkIn(await fs.readFile(target, "utf8"), hunk);
919
+ if (next === null) throw new OpsError(409, "the file changed since the diff was read");
920
+ if (/\.(tsx?|jsx?)$/.test(file.path) && !parseStrict(next)) throw new OpsError(422, "reverting this change alone would break the source — revert the changes around it too");
921
+ await fs.writeFile(target, next, "utf8");
922
+ return { ok: true };
923
+ });
863
924
  }
864
925
  //#endregion
865
926
  //#region src/files/assets.ts
@@ -1461,7 +1522,9 @@ async function writeAsset(ctx, scope, filename, data) {
1461
1522
  await fs.mkdir(dir, { recursive: true });
1462
1523
  const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, name);
1463
1524
  if (!file) throw new OpsError(400, "invalid filename");
1464
- await fs.writeFile(file, data);
1525
+ await withFileLock(file, async () => {
1526
+ await fs.writeFile(file, data);
1527
+ });
1465
1528
  return {
1466
1529
  scope,
1467
1530
  filename: name,
@@ -1473,7 +1536,9 @@ async function deleteAsset(ctx, scope, filename) {
1473
1536
  const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
1474
1537
  if (!file) throw new OpsError(400, "invalid filename");
1475
1538
  if (!existsSync(file)) throw new OpsError(404, `asset not found: ${scope}/${filename}`);
1476
- await fs.rm(file);
1539
+ await withFileLock(file, async () => {
1540
+ await fs.rm(file);
1541
+ });
1477
1542
  }
1478
1543
  /** Which documents import this asset — check before deleting one. */
1479
1544
  async function findAssetUsages(ctx, scope, filename) {
@@ -1507,23 +1572,27 @@ async function createFolder(ctx, rawName, rawIcon) {
1507
1572
  if (!name) throw new OpsError(400, "invalid folder name");
1508
1573
  const icon = validateIcon(rawIcon ?? DEFAULT_FOLDER_ICON);
1509
1574
  if (!icon) throw new OpsError(400, "invalid icon");
1510
- const manifest = await readManifest(ctx.manifestPath);
1511
- const folder = {
1512
- id: newFolderId(),
1513
- name,
1514
- icon
1515
- };
1516
- manifest.folders.push(folder);
1517
- await writeManifest(ctx.manifestPath, manifest);
1518
- return folder;
1575
+ return withFileLock(ctx.manifestPath, async () => {
1576
+ const manifest = await readManifest(ctx.manifestPath);
1577
+ const folder = {
1578
+ id: newFolderId(),
1579
+ name,
1580
+ icon
1581
+ };
1582
+ manifest.folders.push(folder);
1583
+ await writeManifest(ctx.manifestPath, manifest);
1584
+ return folder;
1585
+ });
1519
1586
  }
1520
1587
  /** Filing only edits assignments — a document id never moves on disk. */
1521
1588
  async function fileDocument(ctx, docId, folderId) {
1522
- const manifest = await readManifest(ctx.manifestPath);
1523
- if (folderId !== null && !manifest.folders.some((f) => f.id === folderId)) throw new OpsError(404, `folder not found: ${folderId}`);
1524
- if (folderId === null) delete manifest.assignments[docId];
1525
- else manifest.assignments[docId] = folderId;
1526
- await writeManifest(ctx.manifestPath, manifest);
1589
+ await withFileLock(ctx.manifestPath, async () => {
1590
+ const manifest = await readManifest(ctx.manifestPath);
1591
+ if (folderId !== null && !manifest.folders.some((f) => f.id === folderId)) throw new OpsError(404, `folder not found: ${folderId}`);
1592
+ if (folderId === null) delete manifest.assignments[docId];
1593
+ else manifest.assignments[docId] = folderId;
1594
+ await writeManifest(ctx.manifestPath, manifest);
1595
+ });
1527
1596
  }
1528
1597
  //#endregion
1529
1598
  //#region src/ops/templates.ts
@@ -3157,21 +3226,31 @@ async function readText(ctx, docId, locs, shown, prop) {
3157
3226
  const { source } = await sourceOf(ctx, docId);
3158
3227
  const resolved = resolveTextTarget(source, locs, shown, prop);
3159
3228
  if (!resolved) throw new OpsError(404, "no editable text at that location");
3160
- return resolved;
3229
+ return {
3230
+ ...resolved,
3231
+ hash: hashSource(source)
3232
+ };
3161
3233
  }
3162
3234
  /**
3163
3235
  * `expected` is the text the caller believes is there; when it no longer
3164
3236
  * matches the write is refused rather than silently overwriting someone else's
3165
- * edit. `index` picks a run when the element mixes text and markup. A run that
3166
- * carries code, emphasis or links must be written as `segments`, or the write
3167
- * is refused rather than dropping the formatting.
3237
+ * edit. `expectedHash` optionally verifies the file-level SHA-256 digest.
3238
+ * All reads and writes on the same document are serialized via `withFileLock`.
3168
3239
  */
3169
3240
  async function writeText(ctx, docId, loc, text, opts = {}) {
3170
- const { entry, source } = await sourceOf(ctx, docId);
3171
- const result = replaceTextAt(source, loc, text, opts);
3172
- if (!result.ok) throw new OpsError(result.status, result.error);
3173
- if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3174
- return { ok: true };
3241
+ const entry = resolveEntry(ctx, docId);
3242
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
3243
+ return withFileLock(entry, async () => {
3244
+ const source = await fs.readFile(entry, "utf8");
3245
+ assertExpectedSource(source, { expectedHash: opts.expectedHash });
3246
+ const result = replaceTextAt(source, loc, text, opts);
3247
+ if (!result.ok) throw new OpsError(result.status, result.error);
3248
+ if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3249
+ return {
3250
+ ok: true,
3251
+ hash: hashSource(result.source)
3252
+ };
3253
+ });
3175
3254
  }
3176
3255
  /**
3177
3256
  * Several run replacements in one read and one write, so an editing session
@@ -3179,12 +3258,20 @@ async function writeText(ctx, docId, loc, text, opts = {}) {
3179
3258
  * that each re-paginate the document. Per-edit failures are reported, not
3180
3259
  * thrown: the edits that still apply are written.
3181
3260
  */
3182
- async function writeTexts(ctx, docId, edits) {
3261
+ async function writeTexts(ctx, docId, edits, opts = {}) {
3183
3262
  if (edits.length === 0) throw new OpsError(400, "at least one edit is required");
3184
- const { entry, source } = await sourceOf(ctx, docId);
3185
- const result = replaceTextsAt(source, edits);
3186
- if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3187
- return { results: result.results };
3263
+ const entry = resolveEntry(ctx, docId);
3264
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
3265
+ return withFileLock(entry, async () => {
3266
+ const source = await fs.readFile(entry, "utf8");
3267
+ assertExpectedSource(source, opts);
3268
+ const result = replaceTextsAt(source, edits);
3269
+ if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3270
+ return {
3271
+ results: result.results,
3272
+ hash: hashSource(result.source)
3273
+ };
3274
+ });
3188
3275
  }
3189
3276
  /** What the element at `loc` sets in its `style`, key by key, for the element panel's Format section. */
3190
3277
  async function readStyle(ctx, docId, loc, tag) {
@@ -3196,24 +3283,38 @@ async function readStyle(ctx, docId, loc, tag) {
3196
3283
  * against the same read of the file and written once. Per-edit failures are
3197
3284
  * reported, not thrown, like `writeTexts`.
3198
3285
  */
3199
- async function writeEdits(ctx, docId, texts, styles) {
3286
+ async function writeEdits(ctx, docId, texts, styles, opts = {}) {
3200
3287
  if (texts.length + styles.length === 0) throw new OpsError(400, "at least one edit is required");
3201
- const { entry, source } = await sourceOf(ctx, docId);
3202
- const result = replaceEditsAt(source, texts, styles);
3203
- if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3204
- return {
3205
- texts: result.texts,
3206
- styles: result.styles
3207
- };
3288
+ const entry = resolveEntry(ctx, docId);
3289
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
3290
+ return withFileLock(entry, async () => {
3291
+ const source = await fs.readFile(entry, "utf8");
3292
+ assertExpectedSource(source, opts);
3293
+ const result = replaceEditsAt(source, texts, styles);
3294
+ if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3295
+ return {
3296
+ texts: result.texts,
3297
+ styles: result.styles,
3298
+ hash: hashSource(result.source)
3299
+ };
3300
+ });
3208
3301
  }
3209
3302
  /** Leaves a `@doc-comment` marker in the source for a later agent pass to act on. */
3210
- async function addComment(ctx, docId, loc, note, hint) {
3303
+ async function addComment(ctx, docId, loc, note, hint, opts = {}) {
3211
3304
  if (note.trim() === "") throw new OpsError(400, "note is empty");
3212
- const { entry, source } = await sourceOf(ctx, docId);
3213
- const inserted = insertMarker(source, loc, note.trim(), hint);
3214
- if (!inserted) throw new OpsError(422, "cannot anchor a comment here — pick the surrounding element");
3215
- await fs.writeFile(entry, inserted.source, "utf8");
3216
- return { id: inserted.id };
3305
+ const entry = resolveEntry(ctx, docId);
3306
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
3307
+ return withFileLock(entry, async () => {
3308
+ const source = await fs.readFile(entry, "utf8");
3309
+ assertExpectedSource(source, opts);
3310
+ const inserted = insertMarker(source, loc, note.trim(), hint);
3311
+ if (!inserted) throw new OpsError(422, "cannot anchor a comment here — pick the surrounding element");
3312
+ await fs.writeFile(entry, inserted.source, "utf8");
3313
+ return {
3314
+ id: inserted.id,
3315
+ hash: hashSource(inserted.source)
3316
+ };
3317
+ });
3217
3318
  }
3218
3319
  //#endregion
3219
3320
  //#region src/vite/routes/edit.ts
@@ -3304,9 +3405,13 @@ function registerEditRoutes(server, ctx) {
3304
3405
  column
3305
3406
  }));
3306
3407
  if (!entry || locs.length === 0) return json(res, 400, { error: "invalid target" });
3307
- const resolved = resolveTextTarget(await fs.readFile(entry, "utf8"), locs, url.searchParams.get("shown") ?? void 0, url.searchParams.get("prop") ?? void 0);
3408
+ const source = await fs.readFile(entry, "utf8");
3409
+ const resolved = resolveTextTarget(source, locs, url.searchParams.get("shown") ?? void 0, url.searchParams.get("prop") ?? void 0);
3308
3410
  if (!resolved) return json(res, 404, { error: "element not found" });
3309
- return json(res, 200, resolved);
3411
+ return json(res, 200, {
3412
+ ...resolved,
3413
+ hash: hashSource(source)
3414
+ });
3310
3415
  }
3311
3416
  if (method === "PUT" && url.pathname === "/text") {
3312
3417
  const check = validateMutationRequest(req, { requireJsonBody: true });
@@ -3317,19 +3422,15 @@ function registerEditRoutes(server, ctx) {
3317
3422
  if (!loc || typeof text !== "string") return json(res, 400, { error: "invalid payload" });
3318
3423
  const entry = entryFor(loc.docId);
3319
3424
  if (!entry) return json(res, 404, { error: "document not found" });
3320
- const source = await fs.readFile(entry, "utf8");
3321
- const result = replaceTextAt(source, loc, text, {
3425
+ const out = await writeText(ctx, loc.docId, loc, text, {
3322
3426
  index: typeof body.index === "number" ? body.index : void 0,
3323
3427
  expected: typeof body.expected === "string" ? body.expected : void 0,
3428
+ expectedHash: typeof body.expectedHash === "string" ? body.expectedHash : void 0,
3324
3429
  shown: typeof body.shown === "string" ? body.shown : void 0,
3325
3430
  prop: typeof body.prop === "string" ? body.prop : void 0
3326
3431
  });
3327
- if (!result.ok) return json(res, result.status, { error: result.error });
3328
- if (result.source !== source) {
3329
- await fs.writeFile(entry, result.source, "utf8");
3330
- server.watcher.emit("change", entry);
3331
- }
3332
- return json(res, 200, { ok: true });
3432
+ server.watcher.emit("change", entry);
3433
+ return json(res, 200, out);
3333
3434
  }
3334
3435
  if (method === "PUT" && url.pathname === "/texts") {
3335
3436
  const check = validateMutationRequest(req, { requireJsonBody: true });
@@ -3338,7 +3439,7 @@ function registerEditRoutes(server, ctx) {
3338
3439
  if (typeof body.docId !== "string" || !Array.isArray(body.edits)) return json(res, 400, { error: "invalid payload" });
3339
3440
  const edits = readTextEdits(body.docId, body.edits);
3340
3441
  if (!edits) return json(res, 400, { error: "invalid payload" });
3341
- const out = await writeTexts(ctx, body.docId, edits);
3442
+ const out = await writeTexts(ctx, body.docId, edits, { expectedHash: typeof body.expectedHash === "string" ? body.expectedHash : void 0 });
3342
3443
  const entry = entryFor(body.docId);
3343
3444
  if (entry) server.watcher.emit("change", entry);
3344
3445
  return json(res, 200, out);
@@ -3361,7 +3462,7 @@ function registerEditRoutes(server, ctx) {
3361
3462
  const texts = readTextEdits(body.docId, body.texts ?? []);
3362
3463
  const styles = readStyleEdits(body.docId, body.styles ?? []);
3363
3464
  if (!texts || !styles) return json(res, 400, { error: "invalid payload" });
3364
- const out = await writeEdits(ctx, body.docId, texts, styles);
3465
+ const out = await writeEdits(ctx, body.docId, texts, styles, { expectedHash: typeof body.expectedHash === "string" ? body.expectedHash : void 0 });
3365
3466
  const entry = entryFor(body.docId);
3366
3467
  if (entry) server.watcher.emit("change", entry);
3367
3468
  return json(res, 200, out);
@@ -3375,13 +3476,12 @@ function registerEditRoutes(server, ctx) {
3375
3476
  if (!loc || typeof note !== "string" || note.trim() === "") return json(res, 400, { error: "invalid payload" });
3376
3477
  const entry = entryFor(loc.docId);
3377
3478
  if (!entry) return json(res, 404, { error: "document not found" });
3378
- const inserted = insertMarker(await fs.readFile(entry, "utf8"), loc, note.trim(), typeof body.hint === "string" ? body.hint : void 0);
3379
- if (!inserted) return json(res, 422, { error: "cannot anchor a comment here — pick the surrounding element" });
3380
- await fs.writeFile(entry, inserted.source, "utf8");
3479
+ const inserted = await addComment(ctx, loc.docId, loc, note, typeof body.hint === "string" ? body.hint : void 0, { expectedHash: typeof body.expectedHash === "string" ? body.expectedHash : void 0 });
3381
3480
  server.watcher.emit("change", entry);
3382
3481
  return json(res, 200, {
3383
3482
  ok: true,
3384
- id: inserted.id
3483
+ id: inserted.id,
3484
+ hash: inserted.hash
3385
3485
  });
3386
3486
  }
3387
3487
  return next();
@@ -3406,9 +3506,12 @@ function registerEditRoutes(server, ctx) {
3406
3506
  if (!check.ok) return json(res, check.status, { error: check.error });
3407
3507
  const id = url.searchParams.get("id") ?? "";
3408
3508
  if (!entry || !/^c-[a-f0-9]+$/.test(id)) return json(res, 400, { error: "invalid id" });
3409
- const next = removeMarker(await fs.readFile(entry, "utf8"), id);
3410
- if (next === null) return json(res, 404, { error: "comment not found" });
3411
- await fs.writeFile(entry, next, "utf8");
3509
+ if (!await withFileLock(entry, async () => {
3510
+ const nextSource = removeMarker(await fs.readFile(entry, "utf8"), id);
3511
+ if (nextSource === null) return false;
3512
+ await fs.writeFile(entry, nextSource, "utf8");
3513
+ return true;
3514
+ })) return json(res, 404, { error: "comment not found" });
3412
3515
  server.watcher.emit("change", entry);
3413
3516
  return json(res, 200, { ok: true });
3414
3517
  }
@@ -3434,15 +3537,17 @@ function registerFolderRoutes(server, ctx) {
3434
3537
  if (!name) return json(res, 400, { error: "invalid name" });
3435
3538
  const icon = validateIcon(body.icon);
3436
3539
  if (!icon) return json(res, 400, { error: "invalid icon" });
3437
- const manifest = await readManifest(ctx.manifestPath);
3438
- const folder = {
3439
- id: newFolderId(),
3440
- name,
3441
- icon
3442
- };
3443
- manifest.folders.push(folder);
3444
- await writeManifest(ctx.manifestPath, manifest);
3445
- return json(res, 200, folder);
3540
+ return json(res, 200, await withFileLock(ctx.manifestPath, async () => {
3541
+ const manifest = await readManifest(ctx.manifestPath);
3542
+ const created = {
3543
+ id: newFolderId(),
3544
+ name,
3545
+ icon
3546
+ };
3547
+ manifest.folders.push(created);
3548
+ await writeManifest(ctx.manifestPath, manifest);
3549
+ return created;
3550
+ }));
3446
3551
  }
3447
3552
  if (method === "PUT" && url.pathname === "/assign") {
3448
3553
  const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
@@ -3454,23 +3559,29 @@ function registerFolderRoutes(server, ctx) {
3454
3559
  if (body.folderId === null) folderId = null;
3455
3560
  else if (typeof body.folderId === "string" && FOLDER_ID_RE.test(body.folderId)) folderId = body.folderId;
3456
3561
  else return json(res, 400, { error: "invalid folderId" });
3457
- const manifest = await readManifest(ctx.manifestPath);
3458
- if (folderId && !manifest.folders.some((f) => f.id === folderId)) return json(res, 404, { error: "folder not found" });
3459
- if (folderId === null) delete manifest.assignments[docId];
3460
- else manifest.assignments[docId] = folderId;
3461
- await writeManifest(ctx.manifestPath, manifest);
3562
+ if (!await withFileLock(ctx.manifestPath, async () => {
3563
+ const manifest = await readManifest(ctx.manifestPath);
3564
+ if (folderId && !manifest.folders.some((f) => f.id === folderId)) return false;
3565
+ if (folderId === null) delete manifest.assignments[docId];
3566
+ else manifest.assignments[docId] = folderId;
3567
+ await writeManifest(ctx.manifestPath, manifest);
3568
+ return true;
3569
+ })) return json(res, 404, { error: "folder not found" });
3462
3570
  return json(res, 200, { ok: true });
3463
3571
  }
3464
3572
  if (method === "PUT" && url.pathname === "/reorder") {
3465
3573
  const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
3466
3574
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
3467
3575
  const body = await readBody(req);
3468
- const manifest = await readManifest(ctx.manifestPath);
3469
- const ids = validateReorder(body.ids, manifest.folders);
3470
- if (!ids) return json(res, 400, { error: "invalid ids" });
3471
- const byId = new Map(manifest.folders.map((f) => [f.id, f]));
3472
- manifest.folders = ids.map((id) => byId.get(id));
3473
- await writeManifest(ctx.manifestPath, manifest);
3576
+ if (!await withFileLock(ctx.manifestPath, async () => {
3577
+ const manifest = await readManifest(ctx.manifestPath);
3578
+ const ids = validateReorder(body.ids, manifest.folders);
3579
+ if (!ids) return false;
3580
+ const byId = new Map(manifest.folders.map((f) => [f.id, f]));
3581
+ manifest.folders = ids.map((id) => byId.get(id));
3582
+ await writeManifest(ctx.manifestPath, manifest);
3583
+ return true;
3584
+ })) return json(res, 400, { error: "invalid ids" });
3474
3585
  return json(res, 200, { ok: true });
3475
3586
  }
3476
3587
  const idMatch = url.pathname.match(/^\/([^/]+)$/);
@@ -3481,31 +3592,50 @@ function registerFolderRoutes(server, ctx) {
3481
3592
  const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
3482
3593
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
3483
3594
  const body = await readBody(req);
3484
- const manifest = await readManifest(ctx.manifestPath);
3485
- const folder = manifest.folders.find((f) => f.id === id);
3486
- if (!folder) return json(res, 404, { error: "folder not found" });
3487
- if (body.name !== void 0) {
3488
- const name = validateName(body.name);
3489
- if (!name) return json(res, 400, { error: "invalid name" });
3490
- folder.name = name;
3491
- }
3492
- if (body.icon !== void 0) {
3493
- const icon = validateIcon(body.icon);
3494
- if (!icon) return json(res, 400, { error: "invalid icon" });
3495
- folder.icon = icon;
3496
- }
3497
- await writeManifest(ctx.manifestPath, manifest);
3498
- return json(res, 200, folder);
3595
+ const outcome = await withFileLock(ctx.manifestPath, async () => {
3596
+ const manifest = await readManifest(ctx.manifestPath);
3597
+ const folder = manifest.folders.find((f) => f.id === id);
3598
+ if (!folder) return {
3599
+ status: 404,
3600
+ error: "folder not found"
3601
+ };
3602
+ if (body.name !== void 0) {
3603
+ const name = validateName(body.name);
3604
+ if (!name) return {
3605
+ status: 400,
3606
+ error: "invalid name"
3607
+ };
3608
+ folder.name = name;
3609
+ }
3610
+ if (body.icon !== void 0) {
3611
+ const icon = validateIcon(body.icon);
3612
+ if (!icon) return {
3613
+ status: 400,
3614
+ error: "invalid icon"
3615
+ };
3616
+ folder.icon = icon;
3617
+ }
3618
+ await writeManifest(ctx.manifestPath, manifest);
3619
+ return {
3620
+ status: 200,
3621
+ folder
3622
+ };
3623
+ });
3624
+ if (outcome.status !== 200) return json(res, outcome.status, { error: outcome.error });
3625
+ return json(res, 200, outcome.folder);
3499
3626
  }
3500
3627
  if (method === "DELETE") {
3501
3628
  const requestCheck = validateMutationRequest(req);
3502
3629
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
3503
- const manifest = await readManifest(ctx.manifestPath);
3504
- const before = manifest.folders.length;
3505
- manifest.folders = manifest.folders.filter((f) => f.id !== id);
3506
- if (manifest.folders.length === before) return json(res, 404, { error: "folder not found" });
3507
- for (const [docId, folderId] of Object.entries(manifest.assignments)) if (folderId === id) delete manifest.assignments[docId];
3508
- await writeManifest(ctx.manifestPath, manifest);
3630
+ if (!await withFileLock(ctx.manifestPath, async () => {
3631
+ const manifest = await readManifest(ctx.manifestPath);
3632
+ const before = manifest.folders.length;
3633
+ manifest.folders = manifest.folders.filter((f) => f.id !== id);
3634
+ if (manifest.folders.length === before) return false;
3635
+ for (const [docId, folderId] of Object.entries(manifest.assignments)) if (folderId === id) delete manifest.assignments[docId];
3636
+ await writeManifest(ctx.manifestPath, manifest);
3637
+ return true;
3638
+ })) return json(res, 404, { error: "folder not found" });
3509
3639
  return json(res, 200, { ok: true });
3510
3640
  }
3511
3641
  }
@@ -3943,41 +4073,68 @@ function designPlugin(opts) {
3943
4073
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
3944
4074
  const patch = (await readBody(req)).patch;
3945
4075
  if (!patch || typeof patch !== "object") return json(res, 400, { error: "missing patch object" });
3946
- let source;
3947
- try {
3948
- source = await fs.readFile(file, "utf8");
3949
- } catch {
3950
- return json(res, 404, { error: "document not found" });
3951
- }
3952
- const parsed = parseDocDesign(source);
3953
- if (!parsed.ok && parsed.exists) return json(res, 422, { error: parsed.error });
3954
- const merged = mergeDesign(parsed.ok ? parsed.design : defaultDesign, patch);
3955
- const written = applyDesignWrite(source, merged);
3956
- if (!written.ok) return json(res, written.status, { error: written.error });
3957
- if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
3958
- return json(res, 200, {
3959
- ok: true,
3960
- design: merged,
3961
- created: written.created
4076
+ const outcome = await withFileLock(file, async () => {
4077
+ let source;
4078
+ try {
4079
+ source = await fs.readFile(file, "utf8");
4080
+ } catch {
4081
+ return {
4082
+ status: 404,
4083
+ payload: { error: "document not found" }
4084
+ };
4085
+ }
4086
+ const parsed = parseDocDesign(source);
4087
+ if (!parsed.ok && parsed.exists) return {
4088
+ status: 422,
4089
+ payload: { error: parsed.error }
4090
+ };
4091
+ const merged = mergeDesign(parsed.ok ? parsed.design : defaultDesign, patch);
4092
+ const written = applyDesignWrite(source, merged);
4093
+ if (!written.ok) return {
4094
+ status: written.status,
4095
+ payload: { error: written.error }
4096
+ };
4097
+ if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
4098
+ return {
4099
+ status: 200,
4100
+ payload: {
4101
+ ok: true,
4102
+ design: merged,
4103
+ created: written.created
4104
+ }
4105
+ };
3962
4106
  });
4107
+ return json(res, outcome.status, outcome.payload);
3963
4108
  }
3964
4109
  if (method === "POST" && url.pathname === "/reset") {
3965
4110
  const requestCheck = validateMutationRequest(req);
3966
4111
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
3967
- let source;
3968
- try {
3969
- source = await fs.readFile(file, "utf8");
3970
- } catch {
3971
- return json(res, 404, { error: "document not found" });
3972
- }
3973
- const written = applyDesignWrite(source, defaultDesign);
3974
- if (!written.ok) return json(res, written.status, { error: written.error });
3975
- if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
3976
- return json(res, 200, {
3977
- ok: true,
3978
- design: defaultDesign,
3979
- created: written.created
4112
+ const outcome = await withFileLock(file, async () => {
4113
+ let source;
4114
+ try {
4115
+ source = await fs.readFile(file, "utf8");
4116
+ } catch {
4117
+ return {
4118
+ status: 404,
4119
+ payload: { error: "document not found" }
4120
+ };
4121
+ }
4122
+ const written = applyDesignWrite(source, defaultDesign);
4123
+ if (!written.ok) return {
4124
+ status: written.status,
4125
+ payload: { error: written.error }
4126
+ };
4127
+ if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
4128
+ return {
4129
+ status: 200,
4130
+ payload: {
4131
+ ok: true,
4132
+ design: defaultDesign,
4133
+ created: written.created
4134
+ }
4135
+ };
3980
4136
  });
4137
+ return json(res, outcome.status, outcome.payload);
3981
4138
  }
3982
4139
  return next();
3983
4140
  } catch (err) {
@@ -4248,4 +4405,4 @@ async function createViteConfig(opts) {
4248
4405
  };
4249
4406
  }
4250
4407
  //#endregion
4251
- export { renameDocument as A, createDocument as C, listDocIds$1 as D, duplicateDocument as E, writeDocument as M, makeContext as N, listDocuments as O, OpsError as S, docDir as T, writeAsset as _, writeTexts as a, readChanges as b, suggestDocId as c, fileDocument as d, findAssetUsages as f, readTheme as g, listThemes as h, writeText as i, resolveEntry as j, readDocument as k, createFolder as l, listFolders as m, addComment as n, createFromTemplate as o, listAssets as p, readText as r, listTemplates as s, createViteConfig as t, deleteAsset as u, validateAssetName as v, deleteDocument as w, revertChange as x, listRevisions as y };
4408
+ export { duplicateDocument as A, assertExpectedSource as C, createDocument as D, OpsError as E, resolveEntry as F, writeDocument as I, makeContext as L, listDocuments as M, readDocument as N, deleteDocument as O, renameDocument as P, revertChange as S, withFileLock as T, readTheme as _, writeText as a, listRevisions as b, listTemplates as c, deleteAsset as d, fileDocument as f, listThemes as g, listFolders as h, writeEdits as i, listDocIds$1 as j, docDir as k, suggestDocId as l, listAssets as m, addComment as n, writeTexts as o, findAssetUsages as p, readText as r, createFromTemplate as s, createViteConfig as t, createFolder as u, writeAsset as v, hashSource as w, readChanges as x, validateAssetName as y };
@@ -1,6 +1,6 @@
1
1
  import { n as readCoreVersion } from "./package-version-C89gtYSk.js";
2
2
  import { n as loadUserConfig } from "./open-doc-plugin-DnX5usgI.js";
3
- import { N as makeContext } from "./config-DKKNIbvO.js";
3
+ import { L as makeContext } from "./config-CltJJVsw.js";
4
4
  //#region src/cli/context.ts
5
5
  /** The same context the dev API and the MCP server run on, for commands that call `ops/`. */
6
6
  async function cliContext(userCwd = process.cwd()) {
@@ -1,4 +1,4 @@
1
- import { t as createViteConfig } from "./config-DKKNIbvO.js";
1
+ import { t as createViteConfig } from "./config-CltJJVsw.js";
2
2
  import { createServer, mergeConfig } from "vite";
3
3
  //#region src/cli/dev.ts
4
4
  async function dev(opts = {}) {
@@ -1,5 +1,5 @@
1
- import { s as diffDocument } from "./ops-DmEecq1k.js";
2
- import { t as cliContext } from "./context-DXNP8v9I.js";
1
+ import { s as diffDocument } from "./ops-CSR5RlrE.js";
2
+ import { t as cliContext } from "./context-CWgfsHoE.js";
3
3
  import chalk from "chalk";
4
4
  //#region src/cli/diff.ts
5
5
  const MARK = {
@@ -1,7 +1,7 @@
1
1
  import { r as EXPORT_FORMATS } from "./sdk-CqNZzbkz.js";
2
- import { D as listDocIds } from "./config-DKKNIbvO.js";
3
- import { n as closeRenderSession, r as exportDocument } from "./ops-DmEecq1k.js";
4
- import { t as cliContext } from "./context-DXNP8v9I.js";
2
+ import { j as listDocIds } from "./config-CltJJVsw.js";
3
+ import { n as closeRenderSession, r as exportDocument } from "./ops-CSR5RlrE.js";
4
+ import { t as cliContext } from "./context-CWgfsHoE.js";
5
5
  import chalk from "chalk";
6
6
  //#region src/cli/export.ts
7
7
  const FORMATS = EXPORT_FORMATS;
@@ -1,5 +1,5 @@
1
- import { a as importMarkdown } from "./ops-DmEecq1k.js";
2
- import { t as cliContext } from "./context-DXNP8v9I.js";
1
+ import { a as importMarkdown } from "./ops-CSR5RlrE.js";
2
+ import { t as cliContext } from "./context-CWgfsHoE.js";
3
3
  import chalk from "chalk";
4
4
  import path from "node:path";
5
5
  //#region src/cli/import.ts
@@ -93,6 +93,28 @@ declare function revertChange(ctx: ApiContext, docId: string, opts: {
93
93
  ok: true;
94
94
  }>;
95
95
  //#endregion
96
+ //#region src/ops/concurrency.d.ts
97
+ /**
98
+ * Deterministic 16-char SHA-256 hex digest of a document's UTF-8 source.
99
+ * Used as a lightweight optimistic concurrency token (`hash` / `expectedHash`)
100
+ * so clients and MCP agents do not need to re-send the full source string.
101
+ */
102
+ declare function hashSource(source: string): string;
103
+ /**
104
+ * Verifies that `current` on disk still matches what the caller last read,
105
+ * either via full-source comparison (`expected`) or SHA-256 digest (`expectedHash`).
106
+ */
107
+ declare function assertExpectedSource(current: string, opts?: {
108
+ expected?: string;
109
+ expectedHash?: string;
110
+ }): void;
111
+ /**
112
+ * Serializes async read-modify-write operations on the same file path in FIFO order.
113
+ * Prevents concurrent edits (e.g. over high-latency GCS FUSE mounts or parallel
114
+ * MCP tool calls) from reading the same stale snapshot and overwriting each other.
115
+ */
116
+ declare function withFileLock<T>(filePath: string, fn: () => Promise<T>): Promise<T>;
117
+ //#endregion
96
118
  //#region src/app/lib/diagnostics.d.ts
97
119
  type LayoutRule = 'unresolved-ref' | 'duplicate-id' | 'heading-skip' | 'page-overflow' | 'off-page' | 'blank-page' | 'oversized-block' | 'orphan-heading' | 'tiny-text' | 'broken-image';
98
120
  type LayoutSeverity = 'error' | 'warn';
@@ -189,23 +211,30 @@ declare function readDocument(ctx: ApiContext, docId: string): Promise<{
189
211
  id: string;
190
212
  entry: string;
191
213
  source: string;
214
+ hash: string;
192
215
  }>;
193
216
  declare function createDocument(ctx: ApiContext, docId: string, source: string): Promise<{
194
217
  id: string;
195
218
  entry: string;
219
+ hash: string;
196
220
  }>;
197
221
  /**
198
- * Whole-file overwrite. `expected` is the source the caller believes is on
199
- * disk; passing it turns a blind overwrite into a conflict check, which is what
200
- * keeps two agents (or an agent and a person) from clobbering each other.
222
+ * Whole-file overwrite. `expected` (full source) or `expectedHash` (16-char
223
+ * SHA-256 digest from `readDocument`) turns a blind overwrite into an atomic
224
+ * conflict check inside a per-file write lock, keeping two agents (or an agent
225
+ * and a person on GCS FUSE) from clobbering each other.
201
226
  */
202
- declare function writeDocument(ctx: ApiContext, docId: string, source: string, expected?: string): Promise<{
227
+ declare function writeDocument(ctx: ApiContext, docId: string, source: string, expected?: string, expectedHash?: string): Promise<{
203
228
  id: string;
204
229
  entry: string;
230
+ hash: string;
205
231
  }>;
206
- declare function renameDocument(ctx: ApiContext, docId: string, rawTitle: unknown): Promise<{
232
+ declare function renameDocument(ctx: ApiContext, docId: string, rawTitle: unknown, opts?: {
233
+ expectedHash?: string;
234
+ }): Promise<{
207
235
  id: string;
208
236
  title: string;
237
+ hash: string;
209
238
  }>;
210
239
  declare function duplicateDocument(ctx: ApiContext, docId: string, newId?: string): Promise<{
211
240
  id: string;
@@ -383,6 +412,33 @@ declare function createFromTemplate(ctx: ApiContext, opts: {
383
412
  entry: string;
384
413
  }>;
385
414
  //#endregion
415
+ //#region src/app/lib/inspector/format.d.ts
416
+ /**
417
+ * The element panel's Format section, shared by the viewer and the dev server:
418
+ * which style keys it may write, which design tokens each one offers, and what
419
+ * a value has to look like before it is spliced into a document's source.
420
+ */
421
+ declare const STYLE_PROPS: readonly ["fontFamily", "fontSize", "fontWeight", "fontStyle", "textAlign", "lineHeight", "letterSpacing", "color", "background"];
422
+ type StyleProp = (typeof STYLE_PROPS)[number];
423
+ /** `null` takes the key off the element, so the value comes from wherever it did before. */
424
+ type StyleValue = string | number | null;
425
+ type StyleChanges = Partial<Record<StyleProp, StyleValue>>;
426
+ /** What the source says about one key: a literal, a design token, or code the panel can only show. */
427
+ type StyleSource = {
428
+ kind: 'literal';
429
+ value: string | number;
430
+ } | {
431
+ kind: 'token';
432
+ token: string;
433
+ } | {
434
+ kind: 'code';
435
+ code: string;
436
+ };
437
+ /** `from` names the shared style object the key comes from, when it is not the element's own. */
438
+ type StyleOrigin = StyleSource & {
439
+ from?: string;
440
+ };
441
+ //#endregion
386
442
  //#region src/editing/edit-ops.d.ts
387
443
  type EditTarget = {
388
444
  line: number;
@@ -414,6 +470,15 @@ type TextEditOutcome = {
414
470
  error: string;
415
471
  };
416
472
  //#endregion
473
+ //#region src/editing/style-ops.d.ts
474
+ type StyleEdit = EditTarget & {
475
+ /** The tag the viewer clicked; a mismatch means the location points elsewhere now. */
476
+ tag: string;
477
+ changes: StyleChanges;
478
+ /** What the viewer was shown for each changed key; a write over anything else is refused. */
479
+ expected?: Partial<Record<StyleProp, StyleOrigin | null>>;
480
+ };
481
+ //#endregion
417
482
  //#region src/ops/text.d.ts
418
483
  type Loc = {
419
484
  line: number;
@@ -428,17 +493,19 @@ declare function readText(ctx: ApiContext, docId: string, locs: Loc[], shown?: s
428
493
  /**
429
494
  * `expected` is the text the caller believes is there; when it no longer
430
495
  * matches the write is refused rather than silently overwriting someone else's
431
- * edit. `index` picks a run when the element mixes text and markup. A run that
432
- * carries code, emphasis or links must be written as `segments`, or the write
433
- * is refused rather than dropping the formatting.
496
+ * edit. `expectedHash` optionally verifies the file-level SHA-256 digest.
497
+ * All reads and writes on the same document are serialized via `withFileLock`.
434
498
  */
435
499
  declare function writeText(ctx: ApiContext, docId: string, loc: Loc, text: string, opts?: {
436
500
  index?: number;
437
501
  expected?: string;
502
+ expectedHash?: string;
503
+ shown?: string;
438
504
  segments?: TextSegment[];
439
505
  prop?: string;
440
506
  }): Promise<{
441
507
  ok: true;
508
+ hash: string;
442
509
  }>;
443
510
  /**
444
511
  * Several run replacements in one read and one write, so an editing session
@@ -446,12 +513,30 @@ declare function writeText(ctx: ApiContext, docId: string, loc: Loc, text: strin
446
513
  * that each re-paginate the document. Per-edit failures are reported, not
447
514
  * thrown: the edits that still apply are written.
448
515
  */
449
- declare function writeTexts(ctx: ApiContext, docId: string, edits: TextEdit[]): Promise<{
516
+ declare function writeTexts(ctx: ApiContext, docId: string, edits: TextEdit[], opts?: {
517
+ expectedHash?: string;
518
+ }): Promise<{
450
519
  results: TextEditOutcome[];
520
+ hash: string;
521
+ }>;
522
+ /**
523
+ * One save from the element panel: retyped text and style changes, located
524
+ * against the same read of the file and written once. Per-edit failures are
525
+ * reported, not thrown, like `writeTexts`.
526
+ */
527
+ declare function writeEdits(ctx: ApiContext, docId: string, texts: TextEdit[], styles: StyleEdit[], opts?: {
528
+ expectedHash?: string;
529
+ }): Promise<{
530
+ texts: TextEditOutcome[];
531
+ styles: TextEditOutcome[];
532
+ hash: string;
451
533
  }>;
452
534
  /** Leaves a `@doc-comment` marker in the source for a later agent pass to act on. */
453
- declare function addComment(ctx: ApiContext, docId: string, loc: Loc, note: string, hint?: string): Promise<{
535
+ declare function addComment(ctx: ApiContext, docId: string, loc: Loc, note: string, hint?: string, opts?: {
536
+ expectedHash?: string;
537
+ }): Promise<{
454
538
  id: string;
539
+ hash: string;
455
540
  }>;
456
541
  //#endregion
457
- export { type ApiContext, type AssetSummary, type ChangesResult, type DiffResult, type DocumentSummary, EXPORT_FORMATS, type ExportFormat, type ExportResult, type ImportMarkdownOptions, type ImportResult, type LayoutFinding, type LayoutReport, type Loc, ORIENTATIONS, OpsError, type Orientation, PAGE_SIZE_NAMES, type PageChange, type PageSizeName, type PageStatus, type Revision, type TemplateSummary, type ThemeSummary, addComment, checkLayout, closeRenderSession, createDocument, createFolder, createFromTemplate, deleteAsset, deleteDocument, diffDocument, docDir, duplicateDocument, exportDocument, fileDocument, findAssetUsages, importMarkdown, listAssets, listDocIds, listDocuments, listFolders, listRevisions, listTemplates, listThemes, makeContext, readChanges, readDocument, readText, readTheme, renameDocument, renderDocPage, resolveEntry, revertChange, slugify, suggestDocId, writeAsset, writeDocument, writeText, writeTexts };
542
+ export { type ApiContext, type AssetSummary, type ChangesResult, type DiffResult, type DocumentSummary, EXPORT_FORMATS, type ExportFormat, type ExportResult, type ImportMarkdownOptions, type ImportResult, type LayoutFinding, type LayoutReport, type Loc, ORIENTATIONS, OpsError, type Orientation, PAGE_SIZE_NAMES, type PageChange, type PageSizeName, type PageStatus, type Revision, type TemplateSummary, type ThemeSummary, addComment, assertExpectedSource, checkLayout, closeRenderSession, createDocument, createFolder, createFromTemplate, deleteAsset, deleteDocument, diffDocument, docDir, duplicateDocument, exportDocument, fileDocument, findAssetUsages, hashSource, importMarkdown, listAssets, listDocIds, listDocuments, listFolders, listRevisions, listTemplates, listThemes, makeContext, readChanges, readDocument, readText, readTheme, renameDocument, renderDocPage, resolveEntry, revertChange, slugify, suggestDocId, withFileLock, writeAsset, writeDocument, writeEdits, writeText, writeTexts };
package/dist/ops/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { i as ORIENTATIONS, o as PAGE_SIZE_NAMES, r as EXPORT_FORMATS } from "../sdk-CqNZzbkz.js";
2
- import { A as renameDocument, C as createDocument, D as listDocIds, E as duplicateDocument, M as writeDocument, N as makeContext, O as listDocuments, S as OpsError, T as docDir, _ as writeAsset, a as writeTexts, b as readChanges, c as suggestDocId, d as fileDocument, f as findAssetUsages, g as readTheme, h as listThemes, i as writeText, j as resolveEntry, k as readDocument, l as createFolder, m as listFolders, n as addComment, o as createFromTemplate, p as listAssets, r as readText, s as listTemplates, u as deleteAsset, w as deleteDocument, x as revertChange, y as listRevisions } from "../config-DKKNIbvO.js";
3
- import { a as importMarkdown, i as renderDocPage, n as closeRenderSession, o as slugify, r as exportDocument, s as diffDocument, t as checkLayout } from "../ops-DmEecq1k.js";
4
- export { EXPORT_FORMATS, ORIENTATIONS, OpsError, PAGE_SIZE_NAMES, addComment, checkLayout, closeRenderSession, createDocument, createFolder, createFromTemplate, deleteAsset, deleteDocument, diffDocument, docDir, duplicateDocument, exportDocument, fileDocument, findAssetUsages, importMarkdown, listAssets, listDocIds, listDocuments, listFolders, listRevisions, listTemplates, listThemes, makeContext, readChanges, readDocument, readText, readTheme, renameDocument, renderDocPage, resolveEntry, revertChange, slugify, suggestDocId, writeAsset, writeDocument, writeText, writeTexts };
2
+ import { A as duplicateDocument, C as assertExpectedSource, D as createDocument, E as OpsError, F as resolveEntry, I as writeDocument, L as makeContext, M as listDocuments, N as readDocument, O as deleteDocument, P as renameDocument, S as revertChange, T as withFileLock, _ as readTheme, a as writeText, b as listRevisions, c as listTemplates, d as deleteAsset, f as fileDocument, g as listThemes, h as listFolders, i as writeEdits, j as listDocIds, k as docDir, l as suggestDocId, m as listAssets, n as addComment, o as writeTexts, p as findAssetUsages, r as readText, s as createFromTemplate, u as createFolder, v as writeAsset, w as hashSource, x as readChanges } from "../config-CltJJVsw.js";
3
+ import { a as importMarkdown, i as renderDocPage, n as closeRenderSession, o as slugify, r as exportDocument, s as diffDocument, t as checkLayout } from "../ops-CSR5RlrE.js";
4
+ export { EXPORT_FORMATS, ORIENTATIONS, OpsError, PAGE_SIZE_NAMES, addComment, assertExpectedSource, checkLayout, closeRenderSession, createDocument, createFolder, createFromTemplate, deleteAsset, deleteDocument, diffDocument, docDir, duplicateDocument, exportDocument, fileDocument, findAssetUsages, hashSource, importMarkdown, listAssets, listDocIds, listDocuments, listFolders, listRevisions, listTemplates, listThemes, makeContext, readChanges, readDocument, readText, readTheme, renameDocument, renderDocPage, resolveEntry, revertChange, slugify, suggestDocId, withFileLock, writeAsset, writeDocument, writeEdits, writeText, writeTexts };
@@ -1,6 +1,6 @@
1
1
  import { c as isPageSizeName, i as ORIENTATIONS, o as PAGE_SIZE_NAMES, s as isOrientation } from "./sdk-CqNZzbkz.js";
2
2
  import { t as DOC_ID_RE } from "./open-doc-plugin-DnX5usgI.js";
3
- import { C as createDocument, D as listDocIds, S as OpsError, j as resolveEntry, t as createViteConfig, v as validateAssetName } from "./config-DKKNIbvO.js";
3
+ import { D as createDocument, E as OpsError, F as resolveEntry, j as listDocIds, t as createViteConfig, y as validateAssetName } from "./config-CltJJVsw.js";
4
4
  import path from "node:path";
5
5
  import fs from "node:fs/promises";
6
6
  import { existsSync } from "node:fs";
@@ -1,4 +1,4 @@
1
- import { t as createViteConfig } from "./config-DKKNIbvO.js";
1
+ import { t as createViteConfig } from "./config-CltJJVsw.js";
2
2
  import { mergeConfig, preview as preview$1 } from "vite";
3
3
  //#region src/cli/preview.ts
4
4
  async function preview(opts = {}) {
@@ -1,6 +1,6 @@
1
- import { o as createFromTemplate, s as listTemplates } from "./config-DKKNIbvO.js";
2
- import "./ops-DmEecq1k.js";
3
- import { t as cliContext } from "./context-DXNP8v9I.js";
1
+ import { c as listTemplates, s as createFromTemplate } from "./config-CltJJVsw.js";
2
+ import "./ops-CSR5RlrE.js";
3
+ import { t as cliContext } from "./context-CWgfsHoE.js";
4
4
  import chalk from "chalk";
5
5
  //#region src/cli/templates.ts
6
6
  /**
@@ -1,3 +1,3 @@
1
1
  import { r as openDocPlugin } from "../open-doc-plugin-DnX5usgI.js";
2
- import { t as createViteConfig } from "../config-DKKNIbvO.js";
2
+ import { t as createViteConfig } from "../config-CltJJVsw.js";
3
3
  export { createViteConfig, openDocPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-document/core",
3
- "version": "0.13.0",
3
+ "version": "0.13.1",
4
4
  "description": "Runtime and CLI for open-doc — write documents in docs/, we handle the pages, print layout, and export.",
5
5
  "type": "module",
6
6
  "exports": {