@stll/folio-agents 0.1.1 → 0.3.0

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.
package/README.md CHANGED
@@ -18,25 +18,26 @@ bun add @stll/folio-agents
18
18
 
19
19
  ## Tools
20
20
 
21
- | Tool | What it does |
22
- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------- |
23
- | `read_document` | Read the document body as `{ blockId, kind, text }` blocks |
24
- | `find_text` | Search block text for a string; returns block id, occurrence, and context per match |
25
- | `read_comments` | Read comment threads (author, text, resolved, anchored block, replies) |
26
- | `read_changes` | Read pending tracked changes (insertions/deletions) awaiting review |
27
- | `add_comment` | Attach a comment to a block, optionally quoting specific text |
28
- | `suggest_changes` | Propose `replaceInBlock` / `insertAfterBlock` / `insertBeforeBlock` / `replaceBlock` / `deleteBlock` edits as tracked changes |
29
- | `reply_comment` | Reply to a comment thread |
30
- | `resolve_comment` | Resolve or reopen a comment thread |
31
- | `read_page` | Read a page's plain text (live editor only) |
32
- | `read_selection` | Read the current text selection (live editor only) |
33
- | `scroll_to_block` | Scroll the live editor to a block (live editor only) |
21
+ | Tool | What it does |
22
+ | ----------------- | ----------------------------------------------------------------------------------- |
23
+ | `read_document` | Read the document body as `{ blockId, kind, text }` blocks |
24
+ | `find_text` | Search block text for a string; returns block id, occurrence, and context per match |
25
+ | `read_comments` | Read comment threads (author, text, resolved, anchored block, replies) |
26
+ | `read_changes` | Read pending tracked changes (insertions/deletions) awaiting review |
27
+ | `add_comment` | Attach a comment to a block, optionally quoting specific text |
28
+ | `suggest_changes` | Propose block or stable-range edits as tracked changes |
29
+ | `reply_comment` | Reply to a comment thread |
30
+ | `resolve_comment` | Resolve or reopen a comment thread |
31
+ | `read_page` | Read a page's plain text (live editor only) |
32
+ | `read_selection` | Read the current text selection (live editor only) |
33
+ | `scroll_to_block` | Scroll the live editor to a block (live editor only) |
34
34
 
35
35
  Block ids and comment ids always come from a prior tool call
36
36
  (`read_document`, `find_text`, `read_comments`) within the same conversation —
37
37
  never guess them. `suggest_changes` reports a plain-language reason when an
38
38
  operation is skipped (e.g. the block changed since it was last read), so the
39
- model can re-read and retry.
39
+ model can re-read and retry. Successful mutation results include `receipts`
40
+ that identify affected blocks, ranges, insertions, and created comments.
40
41
 
41
42
  ### Untrusted documents
42
43
 
@@ -115,7 +116,7 @@ if (!parsed.ok) {
115
116
  // executeFolioToolCall would.
116
117
  } else {
117
118
  // `parsed.operations` is FolioAIEditOperation[] — route it into your own
118
- // review queue instead of bridge.applyOperations(...).
119
+ // review queue instead of bridge.applyDocumentOperations(...).
119
120
  reviewQueue.enqueue(parsed.operations);
120
121
  }
121
122
  ```
package/dist/bridge.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { FolioAgentChange, FolioAgentComment } from "./types.js";
2
- import { FolioAIEditApplyResult, FolioAIEditOperation, FolioAIEditSnapshot } from "@stll/folio-core/server";
2
+ import { FolioAIEditSnapshot, FolioDocumentOperationBatch, FolioDocumentOperationResult, FolioDocumentStory, FolioDocumentStoryHandle } from "@stll/folio-core/server";
3
3
 
4
4
  //#region src/bridge.d.ts
5
5
  /**
@@ -18,13 +18,14 @@ import { FolioAIEditApplyResult, FolioAIEditOperation, FolioAIEditSnapshot } fro
18
18
  type FolioAgentBridge = {
19
19
  /** Snapshot the current document into AI-facing blocks + anchors. */snapshot(): FolioAIEditSnapshot;
20
20
  /**
21
- * Apply operations against the current document. The bridge decides mode
22
- * (tracked-changes by default) and author internally — callers only supply
23
- * the operations.
21
+ * Apply a versioned operation batch against the current document. The
22
+ * bridge decides mode (tracked-changes by default) and author internally.
24
23
  */
25
- applyOperations(operations: FolioAIEditOperation[]): FolioAIEditApplyResult; /** The comment threads present in the document. */
24
+ applyDocumentOperations(batch: FolioDocumentOperationBatch): FolioDocumentOperationResult; /** The comment threads present in the document. */
26
25
  getComments(): FolioAgentComment[]; /** The pending tracked changes (insertions/deletions) present in the document. */
27
- getChanges(): FolioAgentChange[]; /** Reply to a comment thread. Returns `false` when the target comment does not exist. */
26
+ getChanges(): FolioAgentChange[]; /** Discover typed document stories when the surface exposes package parts. */
27
+ listStories?(): FolioDocumentStory[]; /** Read one previously discovered story. */
28
+ readStory?(handle: FolioDocumentStoryHandle): FolioDocumentStory | null; /** Reply to a comment thread. Returns `false` when the target comment does not exist. */
28
29
  replyToComment(commentId: string, text: string): boolean; /** Mark a comment thread resolved or reopen it. Returns `false` when the target comment does not exist. */
29
30
  resolveComment(commentId: string, resolved: boolean): boolean; /** Scroll the live editor to the given block and select it. */
30
31
  scrollToBlock?(blockId: string): boolean; /** The user's current text selection in the live editor, as plain text. */
@@ -1,9 +1,14 @@
1
1
  import { FolioAgentBridge } from "../bridge.js";
2
- import { FolioAIEditApplyMode, FolioAIEditApplyResult, FolioAIEditOperation, FolioAIEditSnapshot } from "@stll/folio-core/server";
2
+ import { FolioAIEditApplyMode, FolioAIEditApplyResult, FolioAIEditOperation, FolioAIEditSnapshot, FolioDocumentOperationBatch, FolioDocumentOperationResult } from "@stll/folio-core/server";
3
3
  import { FolioCommentAnchor, FolioReviewChange as FolioReviewChange$1 } from "@stll/folio-core/ai-edits";
4
4
  import { Comment } from "@stll/folio-core/types/content";
5
5
 
6
6
  //#region src/bridges/editor-ref.d.ts
7
+ type FolioAgentEditorApplyDocumentOperationsOptions = {
8
+ snapshot: FolioAIEditSnapshot;
9
+ batch: FolioDocumentOperationBatch;
10
+ author?: string;
11
+ };
7
12
  /**
8
13
  * Minimal structural slice of `DocxEditorRef` (`packages/react`) this bridge
9
14
  * drives — declared locally per AGENTS.md's react-free-core rule (agents
@@ -24,7 +29,8 @@ type FolioAgentEditorRefLike = {
24
29
  operations: FolioAIEditOperation[];
25
30
  mode?: FolioAIEditApplyMode;
26
31
  author?: string;
27
- }): FolioAIEditApplyResult; /** `DocxEditorRef.scrollToBlock`. */
32
+ }): FolioAIEditApplyResult; /** `DocxEditorRef.applyDocumentOperations`, when available on newer refs. */
33
+ applyDocumentOperations?(options: FolioAgentEditorApplyDocumentOperationsOptions): FolioDocumentOperationResult; /** `DocxEditorRef.scrollToBlock`. */
28
34
  scrollToBlock(blockId: string, snapshot?: FolioAIEditSnapshot): boolean; /** `DocxEditorRef.getTotalPages`. */
29
35
  getTotalPages(): number;
30
36
  /**
@@ -87,4 +93,4 @@ type CreateEditorRefBridgeOptions = {
87
93
  */
88
94
  declare const createEditorRefBridge: (options: CreateEditorRefBridgeOptions) => FolioAgentBridge;
89
95
  //#endregion
90
- export { CreateEditorRefBridgeOptions, FolioAgentEditorRefLike, createEditorRefBridge };
96
+ export { CreateEditorRefBridgeOptions, FolioAgentEditorApplyDocumentOperationsOptions, FolioAgentEditorRefLike, createEditorRefBridge };
@@ -1,4 +1,5 @@
1
1
  import { toAgentChange } from "./shared.js";
2
+ import { FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, assertSupportedFolioDocumentOperationVersion, getFolioDocumentOperationIssues, getFolioDocumentOperationReceipts } from "@stll/folio-core/server";
2
3
  import { createReply } from "@stll/folio-core/docx/replyToComment";
3
4
  //#region src/bridges/editor-ref.ts
4
5
  const toAgentCommentReply = (reply) => ({
@@ -58,12 +59,67 @@ const createEditorRefBridge = (options) => {
58
59
  };
59
60
  const bridge = {
60
61
  snapshot: requireSnapshot,
61
- applyOperations: (operations) => ref.applyAIEditOperations({
62
- snapshot: requireSnapshot(),
63
- operations,
64
- mode,
65
- author
66
- }),
62
+ applyDocumentOperations: (batch) => {
63
+ assertSupportedFolioDocumentOperationVersion(batch.version);
64
+ const snapshot = requireSnapshot();
65
+ const versionedBatch = {
66
+ ...batch,
67
+ mode
68
+ };
69
+ if (ref.applyDocumentOperations) {
70
+ const result = ref.applyDocumentOperations({
71
+ snapshot,
72
+ batch: versionedBatch,
73
+ author
74
+ });
75
+ return {
76
+ ...result,
77
+ issues: result.issues ?? getFolioDocumentOperationIssues(versionedBatch.operations, result.skipped),
78
+ receipts: result.receipts ?? getFolioDocumentOperationReceipts(versionedBatch.operations, result.applied)
79
+ };
80
+ }
81
+ if (versionedBatch.dryRun === true) {
82
+ const skipped = versionedBatch.operations.map(({ id }) => ({
83
+ id,
84
+ reason: "unsupportedMode"
85
+ }));
86
+ return {
87
+ version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
88
+ status: "previewed",
89
+ applied: [],
90
+ skipped,
91
+ issues: getFolioDocumentOperationIssues(versionedBatch.operations, skipped),
92
+ receipts: []
93
+ };
94
+ }
95
+ if (versionedBatch.atomic === true) {
96
+ const skipped = versionedBatch.operations.map(({ id }) => ({
97
+ id,
98
+ reason: "unsupportedMode"
99
+ }));
100
+ return {
101
+ version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
102
+ status: "rejected",
103
+ applied: [],
104
+ skipped,
105
+ issues: getFolioDocumentOperationIssues(versionedBatch.operations, skipped),
106
+ receipts: []
107
+ };
108
+ }
109
+ const result = ref.applyAIEditOperations({
110
+ snapshot,
111
+ operations: versionedBatch.operations,
112
+ mode: versionedBatch.mode,
113
+ author
114
+ });
115
+ return {
116
+ version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
117
+ status: "committed",
118
+ ...result,
119
+ issues: getFolioDocumentOperationIssues(versionedBatch.operations, result.skipped),
120
+ receipts: getFolioDocumentOperationReceipts(versionedBatch.operations, result.applied)
121
+ };
122
+ },
67
123
  getComments: () => {
68
124
  const comments = getComments();
69
125
  const anchors = ref.getCommentAnchors?.();
@@ -117,10 +173,7 @@ const createEditorRefBridge = (options) => {
117
173
  const next = comments.map((comment) => {
118
174
  if (comment.id !== targetId) return comment;
119
175
  found = true;
120
- return {
121
- ...comment,
122
- done: resolved
123
- };
176
+ return Object.assign({}, comment, { done: resolved });
124
177
  });
125
178
  if (!found) return false;
126
179
  setComments(next);
@@ -33,9 +33,14 @@ const createReviewerBridge = (reviewer, options = {}) => {
33
33
  const mode = options.mode ?? "tracked-changes";
34
34
  return {
35
35
  snapshot: () => reviewer.snapshot(),
36
- applyOperations: (operations) => reviewer.applyOperations(operations, { mode }),
36
+ applyDocumentOperations: (batch) => reviewer.applyDocumentOperations({
37
+ ...batch,
38
+ mode
39
+ }),
37
40
  getComments: () => reviewer.getComments().map(toAgentComment),
38
41
  getChanges: () => reviewer.getChanges().map(toAgentChange),
42
+ listStories: () => reviewer.listStories(),
43
+ readStory: (handle) => reviewer.readStory(handle),
39
44
  replyToComment: (commentId, text) => {
40
45
  const parentId = parseCommentId(commentId);
41
46
  if (parentId === null) return false;
package/dist/compare.d.ts CHANGED
@@ -1,53 +1,15 @@
1
- import { WordDiffSegment } from "@stll/folio-core/ai-edits";
1
+ import { FolioBlockDiff, FolioVersionDiff, FolioVersionDiffSegment } from "@stll/folio-core/server";
2
2
 
3
3
  //#region src/compare.d.ts
4
- /** One word-level diff segment within a `modified` block. Mirrors {@link WordDiffSegment}. */
5
- type FolioAgentVersionDiffSegment = WordDiffSegment;
6
- /** One block-level change between two document versions, in revised-side document order. */
7
- type FolioAgentBlockDiff = {
8
- type: "added";
9
- blockId: string;
10
- kind: string;
11
- text: string;
12
- } | {
13
- type: "deleted";
14
- blockId: string;
15
- kind: string;
16
- text: string;
17
- } | {
18
- type: "modified";
19
- blockId: string;
20
- kind: string;
21
- segments: FolioAgentVersionDiffSegment[];
22
- };
23
- /** Result of {@link compareDocxVersions}. */
24
- type FolioAgentVersionDiff = {
25
- /** Every added, deleted, or modified block, in revised-side document order (deletions slotted where they sat). */changes: FolioAgentBlockDiff[]; /** Counts across every paired/unpaired block, including the unchanged blocks `changes` omits. */
26
- summaryCounts: {
27
- added: number;
28
- deleted: number;
29
- modified: number;
30
- unchanged: number;
31
- };
32
- };
33
- /** True when an `unpairedBaseCount * unpairedRevisedCount` LCS table would exceed {@link MAX_LCS_CELLS}. */
34
- declare const exceedsLcsBudget: (unpairedBaseCount: number, unpairedRevisedCount: number) => boolean;
35
- /**
36
- * Compare two `.docx` buffers and return a structured, block-level diff.
37
- * See the module doc comment for the as-accepted comparison semantics and
38
- * the three-pass alignment algorithm.
39
- */
4
+ /** Backward-compatible name for a core word-level version-diff segment. */
5
+ type FolioAgentVersionDiffSegment = FolioVersionDiffSegment;
6
+ /** Backward-compatible name for a core block-level version diff. */
7
+ type FolioAgentBlockDiff = FolioBlockDiff;
8
+ /** Backward-compatible name for a structured core version diff. */
9
+ type FolioAgentVersionDiff = FolioVersionDiff;
10
+ /** Compare two `.docx` buffers using folio-core's version comparison semantics. */
40
11
  declare const compareDocxVersions: (base: ArrayBuffer, revised: ArrayBuffer) => Promise<FolioAgentVersionDiff>;
41
- /**
42
- * Render a {@link FolioAgentVersionDiff} as compact, deterministic text for a
43
- * model prompt: a header line with the summary counts, then one line per
44
- * change — `~ [blockId] modified: …`, `+ [blockId] added: …`,
45
- * `- [blockId] deleted: …`. A modified block's segments render inline using
46
- * `git diff --word-diff` porcelain conventions (`[-removed-]`, `{+added+}`,
47
- * plain text for unchanged runs, truncated to ~30 characters on each side
48
- * when long). The format is stable across calls — do not change it without
49
- * checking `compare.test.ts`.
50
- */
12
+ /** Render a structured version diff as compact, deterministic model input. */
51
13
  declare const formatVersionDiffForLLM: (diff: FolioAgentVersionDiff) => string;
52
14
  //#endregion
53
- export { FolioAgentBlockDiff, FolioAgentVersionDiff, FolioAgentVersionDiffSegment, compareDocxVersions, exceedsLcsBudget, formatVersionDiffForLLM };
15
+ export { FolioAgentBlockDiff, FolioAgentVersionDiff, FolioAgentVersionDiffSegment, compareDocxVersions, formatVersionDiffForLLM };
package/dist/compare.js CHANGED
@@ -1,169 +1,13 @@
1
- import { diffWordSegments } from "@stll/folio-core/ai-edits";
2
- import { FolioDocxReviewer, getFolioParaIdFromBlockId } from "@stll/folio-core/server";
1
+ import { compareDocxVersions as compareDocxVersions$1 } from "@stll/folio-core/server";
3
2
  //#region src/compare.ts
4
- /**
5
- * Document version-diff engine: compare two `.docx` buffers block by block
6
- * and produce a structured, LLM-summarizable diff.
7
- *
8
- * Both buffers are parsed through {@link FolioDocxReviewer} — the same
9
- * headless parsing + clean-text path `read_document` / `read_changes` use —
10
- * so the comparison runs over each document's AS-ACCEPTED view: any pending
11
- * tracked changes already present in EITHER buffer count as applied before
12
- * the two are compared. Two documents that agree once their own pending
13
- * redlines are accepted report as unchanged, even if the underlying
14
- * tracked-change history differs.
15
- *
16
- * ## Alignment
17
- *
18
- * Blocks are paired across the two snapshots in three passes, each only
19
- * considering blocks the previous pass left unpaired:
20
- *
21
- * 1. **Stable-id pairing.** Blocks whose ids are equal AND not a `seq-NNNN`
22
- * positional fallback ({@link getFolioParaIdFromBlockId} returns non-null)
23
- * are paired directly. This covers both id shapes a snapshot can carry:
24
- * - A real Word `w14:paraId`: stable identity, independent of text — an
25
- * equal-id pair with different text is a genuine edit (`modified`).
26
- * - `FolioDocxReviewer`'s deterministic fallback id (assigned when the
27
- * source paragraph has no `w14:paraId`), which hashes the paragraph's
28
- * TEXT plus its document ordinal. It is structurally indistinguishable
29
- * from a real paraId ({@link getFolioParaIdFromBlockId} can't tell them
30
- * apart), but pairing on equality is still safe: two equal deterministic
31
- * ids necessarily came from identical text at an identical ordinal, so
32
- * the pair is always text-equal (`unchanged`) — never a false
33
- * `modified`. What it can't do is FIND a paragraph whose ordinal shifted
34
- * (an insertion/deletion earlier in the document) even though its text
35
- * is unchanged: that pair has two different fallback ids and falls
36
- * through to pass 2.
37
- * 2. **Exact-text pairing.** An order-preserving LCS over remaining blocks,
38
- * matched by exact text equality. This is what recovers same-text blocks
39
- * that pass 1 missed because a fallback id shifted with the ordinal. Its
40
- * O(m·n) table is skipped ({@link exceedsLcsBudget}) once the unpaired
41
- * counts on both sides would exceed a fixed cell budget, so a document
42
- * with few/no stable ids can't force a quadratic-sized allocation; those
43
- * blocks fall through to pass 3 instead.
44
- * 3. **Positional fallback.** Whatever a monotonicity filter leaves
45
- * unpaired is split into the gaps between anchored pairs (pass 1 + 2,
46
- * time-ordered); within each gap the shorter side is zipped positionally
47
- * against the longer one (`modified`), and any excess on either side is
48
- * reported as `added` / `deleted`.
49
- *
50
- * The combined anchor set from passes 1 and 2 is re-filtered to the longest
51
- * increasing subsequence by revised-side index before pass 3 runs, so a
52
- * pathological crossing match (content reordered across versions) can't
53
- * produce an out-of-order gap — the alignment always walks both documents
54
- * forward.
55
- */
56
- const isStableBlockId = (id) => getFolioParaIdFromBlockId(id) !== null;
57
- const index = (blocks) => blocks.map((block, blockIndex) => ({
58
- block,
59
- index: blockIndex
60
- }));
61
- /**
62
- * Longest increasing subsequence by `revisedIndex`, assuming `pairs` is
63
- * already sorted by `baseIndex` ascending. Drops any pair that would make
64
- * the alignment walk backward in the revised document — the guard against
65
- * both id collisions (pass 1) and any crossing match (pass 1 + 2 combined).
66
- */
67
- const longestIncreasingByRevisedIndex = (pairs) => {
68
- if (pairs.length === 0) return [];
69
- const lengths = Array.from({ length: pairs.length }).fill(1);
70
- const predecessors = Array.from({ length: pairs.length }).fill(-1);
71
- let bestEnd = 0;
72
- for (let i = 0; i < pairs.length; i++) {
73
- for (let j = 0; j < i; j++) {
74
- const current = pairs[j];
75
- const candidate = pairs[i];
76
- if (!current || !candidate) continue;
77
- if (current.revisedIndex < candidate.revisedIndex && (lengths[j] ?? 0) + 1 > (lengths[i] ?? 0)) {
78
- lengths[i] = (lengths[j] ?? 0) + 1;
79
- predecessors[i] = j;
80
- }
81
- }
82
- if ((lengths[i] ?? 0) > (lengths[bestEnd] ?? 0)) bestEnd = i;
83
- }
84
- const ordered = [];
85
- for (let cursor = bestEnd; cursor !== -1; cursor = predecessors[cursor] ?? -1) {
86
- const pair = pairs[cursor];
87
- if (pair) ordered.push(pair);
88
- }
89
- return ordered.toReversed();
90
- };
91
- /** Pass 1: pair blocks with equal, non-`seq-NNNN` ids. See the module doc comment. */
92
- const pairByStableId = (base, revised) => {
93
- const revisedIndexById = /* @__PURE__ */ new Map();
94
- revised.forEach((block, revisedIndex) => {
95
- if (isStableBlockId(block.id)) revisedIndexById.set(block.id, revisedIndex);
96
- });
97
- const candidates = [];
98
- base.forEach((block, baseIndex) => {
99
- if (!isStableBlockId(block.id)) return;
100
- const revisedIndex = revisedIndexById.get(block.id);
101
- if (revisedIndex !== void 0) candidates.push({
102
- baseIndex,
103
- revisedIndex
104
- });
105
- });
106
- return longestIncreasingByRevisedIndex(candidates);
107
- };
108
- /**
109
- * Cell budget for pass 2's O(m·n) exact-text LCS table (`dp` below allocates
110
- * `(m + 1) * (n + 1)` numbers). A document with no `w14:paraId`s — or an
111
- * adversarial one crafted to defeat pass 1 — can leave thousands of blocks
112
- * unpaired on both sides; without a cap, `pairByExactText` would allocate a
113
- * quadratic-sized table for it. Past this budget, {@link exceedsLcsBudget}
114
- * makes pass 2 back off entirely so alignment falls through to pass 3's
115
- * linear positional zip instead — pairing is less precise for these
116
- * degenerate inputs, but memory use stays bounded.
117
- */
118
- const MAX_LCS_CELLS = 4e6;
119
- /** True when an `unpairedBaseCount * unpairedRevisedCount` LCS table would exceed {@link MAX_LCS_CELLS}. */
120
- const exceedsLcsBudget = (unpairedBaseCount, unpairedRevisedCount) => unpairedBaseCount * unpairedRevisedCount > MAX_LCS_CELLS;
121
- /** Pass 2: order-preserving LCS by exact text equality over the blocks pass 1 left unpaired. */
122
- const pairByExactText = (base, revised) => {
123
- const m = base.length;
124
- const n = revised.length;
125
- if (m === 0 || n === 0) return [];
126
- if (exceedsLcsBudget(m, n)) return [];
127
- const stride = n + 1;
128
- const dp = new Int32Array((m + 1) * stride);
129
- for (let i = m - 1; i >= 0; i--) {
130
- const rowOffset = i * stride;
131
- const nextRowOffset = (i + 1) * stride;
132
- for (let j = n - 1; j >= 0; j--) {
133
- const baseText = base[i]?.block.text;
134
- const revisedText = revised[j]?.block.text;
135
- dp[rowOffset + j] = baseText === revisedText ? (dp[nextRowOffset + j + 1] ?? 0) + 1 : Math.max(dp[nextRowOffset + j] ?? 0, dp[rowOffset + j + 1] ?? 0);
136
- }
137
- }
138
- const pairs = [];
139
- let i = 0;
140
- let j = 0;
141
- while (i < m && j < n) {
142
- const baseEntry = base[i];
143
- const revisedEntry = revised[j];
144
- if (!baseEntry || !revisedEntry) break;
145
- if (baseEntry.block.text === revisedEntry.block.text) {
146
- pairs.push({
147
- baseIndex: baseEntry.index,
148
- revisedIndex: revisedEntry.index
149
- });
150
- i++;
151
- j++;
152
- continue;
153
- }
154
- if ((dp[(i + 1) * stride + j] ?? 0) >= (dp[i * stride + j + 1] ?? 0)) i++;
155
- else j++;
156
- }
157
- return pairs;
158
- };
3
+ /** Compare two `.docx` buffers using folio-core's version comparison semantics. */
4
+ const compareDocxVersions = (base, revised) => compareDocxVersions$1(base, revised);
159
5
  const ELLIPSIS = "…";
160
6
  const UNCHANGED_EDGE_CHARS = 30;
161
- /** Collapse a long `equal`-type run to ~30 chars on each side with an ellipsis in between. */
162
7
  const truncateUnchangedRun = (text) => {
163
8
  if (text.length <= 61) return text;
164
9
  return `${text.slice(0, UNCHANGED_EDGE_CHARS)}${ELLIPSIS}${text.slice(-30)}`;
165
10
  };
166
- /** Render one word-diff segment: plain for `equal` (truncated if long), bracketed for `del` / `ins`. */
167
11
  const renderSegment = (segment) => {
168
12
  switch (segment.type) {
169
13
  case "equal": return truncateUnchangedRun(segment.text);
@@ -173,113 +17,20 @@ const renderSegment = (segment) => {
173
17
  }
174
18
  };
175
19
  const formatChangeLine = (change) => {
176
- if (change.type === "added") return `+ [${change.blockId}] added: ${change.text}`;
177
- if (change.type === "deleted") return `- [${change.blockId}] deleted: ${change.text}`;
178
- return `~ [${change.blockId}] modified: ${change.segments.map(renderSegment).join("")}`;
179
- };
180
- /**
181
- * Compare two `.docx` buffers and return a structured, block-level diff.
182
- * See the module doc comment for the as-accepted comparison semantics and
183
- * the three-pass alignment algorithm.
184
- */
185
- const compareDocxVersions = async (base, revised) => {
186
- const [baseReviewer, revisedReviewer] = await Promise.all([FolioDocxReviewer.fromBuffer(base), FolioDocxReviewer.fromBuffer(revised)]);
187
- const baseBlocks = baseReviewer.snapshot().blocks;
188
- const revisedBlocks = revisedReviewer.snapshot().blocks;
189
- const stableIdAnchors = pairByStableId(baseBlocks, revisedBlocks);
190
- const usedBaseIndexes = new Set(stableIdAnchors.map((anchor) => anchor.baseIndex));
191
- const usedRevisedIndexes = new Set(stableIdAnchors.map((anchor) => anchor.revisedIndex));
192
- const exactTextAnchors = pairByExactText(index(baseBlocks).filter(({ index: i }) => !usedBaseIndexes.has(i)), index(revisedBlocks).filter(({ index: i }) => !usedRevisedIndexes.has(i)));
193
- const anchors = longestIncreasingByRevisedIndex([...stableIdAnchors, ...exactTextAnchors].toSorted((a, b) => a.baseIndex - b.baseIndex));
194
- const changes = [];
195
- const counts = {
196
- added: 0,
197
- deleted: 0,
198
- modified: 0,
199
- unchanged: 0
200
- };
201
- /** Pass 3: positionally zip the leftover blocks in one gap between anchors. */
202
- const emitGap = (baseFrom, baseTo, revisedFrom, revisedTo) => {
203
- const baseSlice = baseBlocks.slice(baseFrom, baseTo);
204
- const revisedSlice = revisedBlocks.slice(revisedFrom, revisedTo);
205
- const pairedCount = Math.min(baseSlice.length, revisedSlice.length);
206
- for (let k = 0; k < pairedCount; k++) {
207
- const baseBlock = baseSlice[k];
208
- const revisedBlock = revisedSlice[k];
209
- if (!baseBlock || !revisedBlock) continue;
210
- if (baseBlock.text === revisedBlock.text) {
211
- counts.unchanged++;
212
- continue;
213
- }
214
- counts.modified++;
215
- changes.push({
216
- type: "modified",
217
- blockId: revisedBlock.id,
218
- kind: revisedBlock.kind,
219
- segments: diffWordSegments(baseBlock.text, revisedBlock.text)
220
- });
221
- }
222
- for (let k = pairedCount; k < baseSlice.length; k++) {
223
- const baseBlock = baseSlice[k];
224
- if (!baseBlock) continue;
225
- counts.deleted++;
226
- changes.push({
227
- type: "deleted",
228
- blockId: baseBlock.id,
229
- kind: baseBlock.kind,
230
- text: baseBlock.text
231
- });
232
- }
233
- for (let k = pairedCount; k < revisedSlice.length; k++) {
234
- const revisedBlock = revisedSlice[k];
235
- if (!revisedBlock) continue;
236
- counts.added++;
237
- changes.push({
238
- type: "added",
239
- blockId: revisedBlock.id,
240
- kind: revisedBlock.kind,
241
- text: revisedBlock.text
242
- });
243
- }
244
- };
245
- let baseCursor = 0;
246
- let revisedCursor = 0;
247
- for (const anchor of anchors) {
248
- emitGap(baseCursor, anchor.baseIndex, revisedCursor, anchor.revisedIndex);
249
- const baseBlock = baseBlocks[anchor.baseIndex];
250
- const revisedBlock = revisedBlocks[anchor.revisedIndex];
251
- if (baseBlock && revisedBlock) if (baseBlock.text === revisedBlock.text) counts.unchanged++;
252
- else {
253
- counts.modified++;
254
- changes.push({
255
- type: "modified",
256
- blockId: revisedBlock.id,
257
- kind: revisedBlock.kind,
258
- segments: diffWordSegments(baseBlock.text, revisedBlock.text)
259
- });
260
- }
261
- baseCursor = anchor.baseIndex + 1;
262
- revisedCursor = anchor.revisedIndex + 1;
20
+ switch (change.type) {
21
+ case "added": return `+ [${change.blockId}] added: ${change.text}`;
22
+ case "deleted": return `- [${change.blockId}] deleted: ${change.text}`;
23
+ case "modified": return `~ [${change.blockId}] modified: ${change.segments.map(renderSegment).join("")}`;
24
+ case "formatChanged": return `~ [${change.blockId}] format changed (${change.changedProperties.join(", ")}): ${truncateUnchangedRun(change.text)}`;
25
+ case "movedFrom": return `< [${change.blockId}] moved away (move ${change.moveGroupId}): ${truncateUnchangedRun(change.text)}`;
26
+ case "movedTo": return `> [${change.blockId}] moved here (move ${change.moveGroupId}): ${truncateUnchangedRun(change.text)}`;
27
+ default: return "";
263
28
  }
264
- emitGap(baseCursor, baseBlocks.length, revisedCursor, revisedBlocks.length);
265
- return {
266
- changes,
267
- summaryCounts: counts
268
- };
269
29
  };
270
- /**
271
- * Render a {@link FolioAgentVersionDiff} as compact, deterministic text for a
272
- * model prompt: a header line with the summary counts, then one line per
273
- * change — `~ [blockId] modified: …`, `+ [blockId] added: …`,
274
- * `- [blockId] deleted: …`. A modified block's segments render inline using
275
- * `git diff --word-diff` porcelain conventions (`[-removed-]`, `{+added+}`,
276
- * plain text for unchanged runs, truncated to ~30 characters on each side
277
- * when long). The format is stable across calls — do not change it without
278
- * checking `compare.test.ts`.
279
- */
30
+ /** Render a structured version diff as compact, deterministic model input. */
280
31
  const formatVersionDiffForLLM = (diff) => {
281
- const { added, deleted, modified, unchanged } = diff.summaryCounts;
282
- return [`Version diff: ${added} added, ${deleted} deleted, ${modified} modified, ${unchanged} unchanged`, ...diff.changes.map(formatChangeLine)].join("\n");
32
+ const { added, deleted, modified, formatChanged, moved, unchanged } = diff.summaryCounts;
33
+ return [`Version diff: ${added} added, ${deleted} deleted, ${modified} modified, ${formatChanged} format-changed, ${moved} moved, ${unchanged} unchanged`, ...diff.changes.map(formatChangeLine)].join("\n");
283
34
  };
284
35
  //#endregion
285
- export { compareDocxVersions, exceedsLcsBudget, formatVersionDiffForLLM };
36
+ export { compareDocxVersions, formatVersionDiffForLLM };