@beyondwork/docx-react-component 1.0.58 → 1.0.59

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 (134) hide show
  1. package/README.md +2 -2
  2. package/package.json +2 -1
  3. package/src/api/awareness-identity-types.ts +4 -2
  4. package/src/api/comment-negotiation-types.ts +4 -1
  5. package/src/api/external-custody-types.ts +16 -0
  6. package/src/api/internal/build-ref-projections.ts +108 -0
  7. package/src/api/package-version.ts +1 -1
  8. package/src/api/participants-types.ts +11 -1
  9. package/src/api/public-types.ts +978 -10
  10. package/src/api/scope-metadata-resolver-types.ts +6 -0
  11. package/src/compare/diff-engine.ts +3 -0
  12. package/src/core/commands/formatting-commands.ts +1 -0
  13. package/src/core/commands/index.ts +225 -16
  14. package/src/core/commands/legacy-form-field-commands.ts +181 -0
  15. package/src/core/commands/table-structure-commands.ts +149 -31
  16. package/src/core/selection/mapping.ts +20 -0
  17. package/src/core/state/editor-state.ts +2 -1
  18. package/src/index.ts +28 -0
  19. package/src/io/docx-session.ts +22 -3
  20. package/src/io/export/export-session.ts +11 -7
  21. package/src/io/export/ooxml-namespaces.ts +47 -0
  22. package/src/io/export/reattach-preserved-parts.ts +4 -16
  23. package/src/io/export/serialize-comments.ts +3 -131
  24. package/src/io/export/serialize-ffdata.ts +89 -0
  25. package/src/io/export/serialize-headers-footers.ts +5 -0
  26. package/src/io/export/serialize-main-document.ts +224 -34
  27. package/src/io/export/serialize-numbering.ts +22 -2
  28. package/src/io/export/serialize-revisions.ts +99 -0
  29. package/src/io/export/serialize-tables.ts +9 -0
  30. package/src/io/export/split-review-boundaries.ts +1 -0
  31. package/src/io/export/table-properties-xml.ts +14 -0
  32. package/src/io/load-scheduler.ts +70 -28
  33. package/src/io/normalize/normalize-text.ts +13 -0
  34. package/src/io/ooxml/_mini-xml.ts +198 -0
  35. package/src/io/ooxml/canonicalize-payload.ts +1 -4
  36. package/src/io/ooxml/chart/chart-style-table.ts +4 -3
  37. package/src/io/ooxml/chart/parse-chart-space.ts +2 -4
  38. package/src/io/ooxml/chart/parse-series.ts +2 -1
  39. package/src/io/ooxml/chart/resolve-color.ts +2 -2
  40. package/src/io/ooxml/chart/types.ts +6 -434
  41. package/src/io/ooxml/comment-presentation-payload.ts +6 -5
  42. package/src/io/ooxml/highlight-colors.ts +8 -5
  43. package/src/io/ooxml/parse-anchor.ts +68 -53
  44. package/src/io/ooxml/parse-comments.ts +14 -142
  45. package/src/io/ooxml/parse-complex-content.ts +3 -106
  46. package/src/io/ooxml/parse-drawing.ts +100 -195
  47. package/src/io/ooxml/parse-ffdata.ts +93 -0
  48. package/src/io/ooxml/parse-fields.ts +7 -146
  49. package/src/io/ooxml/parse-fill.ts +88 -8
  50. package/src/io/ooxml/parse-font-table.ts +5 -105
  51. package/src/io/ooxml/parse-footnotes.ts +28 -152
  52. package/src/io/ooxml/parse-headers-footers.ts +106 -212
  53. package/src/io/ooxml/parse-inline-media.ts +3 -200
  54. package/src/io/ooxml/parse-main-document.ts +180 -217
  55. package/src/io/ooxml/parse-numbering.ts +154 -335
  56. package/src/io/ooxml/parse-object.ts +147 -0
  57. package/src/io/ooxml/parse-ole-relationship.ts +82 -0
  58. package/src/io/ooxml/parse-paragraph-formatting.ts +7 -10
  59. package/src/io/ooxml/parse-picture-sdt.ts +85 -0
  60. package/src/io/ooxml/parse-picture.ts +72 -42
  61. package/src/io/ooxml/parse-revisions.ts +285 -51
  62. package/src/io/ooxml/parse-settings.ts +6 -99
  63. package/src/io/ooxml/parse-shapes.ts +25 -140
  64. package/src/io/ooxml/parse-styles.ts +3 -218
  65. package/src/io/ooxml/parse-tables.ts +76 -256
  66. package/src/io/ooxml/parse-theme.ts +1 -4
  67. package/src/io/ooxml/property-grab-bag.ts +5 -47
  68. package/src/io/ooxml/xml-element-serialize.ts +32 -0
  69. package/src/io/ooxml/xml-parser.ts +183 -0
  70. package/src/legal/bookmarks.ts +1 -1
  71. package/src/legal/cross-references.ts +1 -1
  72. package/src/legal/defined-terms.ts +1 -1
  73. package/src/legal/{_document-root.ts → document-root.ts} +8 -0
  74. package/src/legal/signature-blocks.ts +1 -1
  75. package/src/model/canonical-document.ts +159 -6
  76. package/src/model/chart-types.ts +439 -0
  77. package/src/model/snapshot.ts +3 -1
  78. package/src/review/store/comment-remapping.ts +24 -11
  79. package/src/review/store/revision-actions.ts +482 -2
  80. package/src/review/store/revision-store.ts +15 -0
  81. package/src/review/store/revision-types.ts +76 -0
  82. package/src/runtime/collab/remote-cursor-awareness.ts +24 -0
  83. package/src/runtime/collab/runtime-collab-sync.ts +33 -0
  84. package/src/runtime/diagnostics/build-diagnostic.ts +151 -0
  85. package/src/runtime/diagnostics/code-metadata-table.ts +221 -0
  86. package/src/runtime/document-runtime.ts +476 -34
  87. package/src/runtime/document-search.ts +115 -0
  88. package/src/runtime/edit-ops/index.ts +18 -2
  89. package/src/runtime/footnote-resolver.ts +130 -0
  90. package/src/runtime/layout/layout-engine-instance.ts +31 -4
  91. package/src/runtime/layout/layout-engine-version.ts +37 -1
  92. package/src/runtime/layout/page-graph.ts +14 -1
  93. package/src/runtime/layout/resolved-formatting-state.ts +21 -0
  94. package/src/runtime/numbering-prefix.ts +17 -0
  95. package/src/runtime/query-scopes.ts +5 -8
  96. package/src/runtime/resolved-numbering-geometry.ts +37 -6
  97. package/src/runtime/revision-runtime.ts +27 -1
  98. package/src/runtime/selection/post-edit-validator.ts +60 -6
  99. package/src/runtime/structure-ops/index.ts +20 -4
  100. package/src/runtime/surface-projection.ts +290 -21
  101. package/src/runtime/table-schema.ts +6 -0
  102. package/src/runtime/theme-color-resolver.ts +2 -2
  103. package/src/runtime/units.ts +9 -0
  104. package/src/runtime/workflow-rail-segments.ts +4 -0
  105. package/src/ui/WordReviewEditor.tsx +187 -43
  106. package/src/ui/editor-runtime-boundary.ts +10 -0
  107. package/src/ui/editor-shell-view.tsx +4 -1
  108. package/src/ui/headless/chrome-registry.ts +53 -0
  109. package/src/ui/headless/selection-tool-resolver.ts +11 -1
  110. package/src/ui-tailwind/chrome/chrome-preset-model.ts +13 -0
  111. package/src/ui-tailwind/chrome/tw-command-palette-mount.tsx +96 -0
  112. package/src/ui-tailwind/chrome/tw-context-menu.tsx +2 -1
  113. package/src/ui-tailwind/chrome/tw-image-context-toolbar.tsx +5 -4
  114. package/src/ui-tailwind/chrome/tw-mode-dock.tsx +6 -2
  115. package/src/ui-tailwind/chrome/use-container-breakpoint.ts +111 -0
  116. package/src/ui-tailwind/chrome-overlay/tw-chrome-overlay.tsx +0 -9
  117. package/src/ui-tailwind/chrome-overlay/tw-object-selection-overlay.tsx +1 -0
  118. package/src/ui-tailwind/chrome-overlay/tw-page-stack-overlay-layer.tsx +6 -7
  119. package/src/ui-tailwind/editor-surface/pm-schema.ts +87 -25
  120. package/src/ui-tailwind/editor-surface/pm-state-from-snapshot.ts +9 -0
  121. package/src/ui-tailwind/editor-surface/shape-renderer.ts +76 -14
  122. package/src/ui-tailwind/editor-surface/tw-page-block-view.helpers.ts +18 -1
  123. package/src/ui-tailwind/editor-surface/tw-page-block-view.tsx +2 -0
  124. package/src/ui-tailwind/editor-surface/tw-table-node-view.tsx +18 -2
  125. package/src/ui-tailwind/index.ts +9 -0
  126. package/src/ui-tailwind/page-chrome-model.ts +77 -5
  127. package/src/ui-tailwind/page-stack/tw-page-stack-chrome-layer.tsx +56 -1
  128. package/src/ui-tailwind/page-stack/tw-region-block-renderer.tsx +2 -0
  129. package/src/ui-tailwind/review/tw-comment-sidebar.tsx +116 -113
  130. package/src/ui-tailwind/review/tw-review-rail-footer.tsx +2 -2
  131. package/src/ui-tailwind/theme/tokens.ts +14 -0
  132. package/src/ui-tailwind/toolbar/tw-shell-header.tsx +5 -0
  133. package/src/ui-tailwind/tw-review-workspace.tsx +29 -87
  134. package/src/validation/diagnostics.ts +1 -0
@@ -1,3 +1,4 @@
1
+ import type { ReactNode } from "react";
1
2
  import type { PersistedEditorSnapshot as RuntimePersistedEditorSnapshot } from "../core/state/editor-state.ts";
2
3
  import type { HarnessDebugPorts } from "../internal/harness-debug-ports.ts";
3
4
  import type { BlockNode, CanonicalParagraphFormatting, CanonicalRunFormatting, TextMark } from "../model/canonical-document.ts";
@@ -490,6 +491,39 @@ export interface SearchOptions {
490
491
  inStory?: EditorStoryTarget;
491
492
  }
492
493
 
494
+ /**
495
+ * §C4 — Post-match formatting filter for `findTextWithStyle`.
496
+ */
497
+ export interface TextStyleFilter {
498
+ /** Match only inside heading paragraphs (outlineLevel set or styleId matches /^Heading\d/i). */
499
+ inHeading?: boolean;
500
+ /** Run-level marks that ALL segments in the match must carry (AND per property, AND across segments). */
501
+ hasFormatting?: {
502
+ bold?: boolean;
503
+ italic?: boolean;
504
+ underline?: boolean;
505
+ strikethrough?: boolean;
506
+ };
507
+ /** Run-level marks where ALL segments must have AT LEAST ONE (OR per property, AND across segments). */
508
+ anyFormatting?: {
509
+ bold?: boolean;
510
+ italic?: boolean;
511
+ underline?: boolean;
512
+ strikethrough?: boolean;
513
+ };
514
+ }
515
+
516
+ /** Phase C §C5 — options for programmatic selection changes. */
517
+ export interface SetSelectionOptions {
518
+ /**
519
+ * When `true`, the selection change is applied locally but suppresses
520
+ * the next awareness cursor publish. Useful for agent-driven
521
+ * programmatic navigation that should not broadcast a cursor flicker
522
+ * to collaborators.
523
+ */
524
+ silent?: boolean;
525
+ }
526
+
493
527
  export interface SearchResultSnapshot {
494
528
  resultId: string;
495
529
  anchor: EditorAnchorProjection;
@@ -832,6 +866,8 @@ export interface SurfaceDrawingAnchor {
832
866
  simplePos?: boolean;
833
867
  /** docPr.id / .name / .descr — used for accessibility chrome and selection labels. */
834
868
  docPr?: { id: string; name?: string; descr?: string };
869
+ /** Polygon coords (21600ths-of-image units) for tight/through wrap clipping. Lane 6d N9.b. */
870
+ wrapPolygon?: Array<{ x: number; y: number }>;
835
871
  }
836
872
 
837
873
  /**
@@ -1055,6 +1091,8 @@ export interface ResolvedNumberingSnapshot {
1055
1091
  geometry: ResolvedNumberingGeometrySnapshot;
1056
1092
  /** CASCADED marker run formatting: docDefaults → paragraph style chain rPr → paragraph-mark rPr → level rPr. Added in Task 11. The raw level rPr is still available at geometry.markerRunProperties. */
1057
1093
  markerRunProperties?: CanonicalRunFormatting;
1094
+ /** Media-catalog ID for picture-bullet images (CO3.9). Set when the numbering level has `picBulletId` that resolves to a NumPicBullet entry. */
1095
+ picBulletMediaId?: string;
1058
1096
  }
1059
1097
 
1060
1098
  export type SurfaceBlockSnapshot =
@@ -1077,7 +1115,14 @@ export type SurfaceBlockSnapshot =
1077
1115
  spacing?: { before?: number; after?: number; line?: number; lineRule?: string };
1078
1116
  contextualSpacing?: boolean;
1079
1117
  indentation?: { left?: number; right?: number; firstLine?: number; hanging?: number };
1080
- borders?: { top?: unknown; left?: unknown; bottom?: unknown; right?: unknown; bar?: unknown; between?: unknown };
1118
+ borders?: {
1119
+ top?: PublicBorderSpec | null;
1120
+ left?: PublicBorderSpec | null;
1121
+ bottom?: PublicBorderSpec | null;
1122
+ right?: PublicBorderSpec | null;
1123
+ bar?: PublicBorderSpec | null;
1124
+ between?: PublicBorderSpec | null;
1125
+ };
1081
1126
  shading?: { fill?: string; color?: string; val?: string };
1082
1127
  tabStops?: Array<{ pos: number; val?: string; leader?: string }>;
1083
1128
  keepNext?: boolean;
@@ -1096,6 +1141,14 @@ export type SurfaceBlockSnapshot =
1096
1141
  to: number;
1097
1142
  styleId?: string;
1098
1143
  gridColumns: number[];
1144
+ /**
1145
+ * SOW gap G1 — when `tableResolved.widthType === "pct"`, a parallel array
1146
+ * of relative column widths (percent 0–100) derived from `gridColumns`
1147
+ * twips. The node-view prefers these for the `<colgroup>` so the column
1148
+ * proportions track the table's percent width instead of the absolute
1149
+ * `pt` values drifting against a `width: 100%` container.
1150
+ */
1151
+ gridColumnsRelative?: number[] | null;
1099
1152
  alignment?: "left" | "center" | "right";
1100
1153
  tblLook?: {
1101
1154
  /** R2d: raw `w:tblLook/@w:val` hex so vendor-extended bits survive round-trip. */
@@ -1206,7 +1259,8 @@ export type EditorWarningCode =
1206
1259
  | "revision_anchor_detached"
1207
1260
  | "large_document_degraded"
1208
1261
  | "font_substitution"
1209
- | "image_missing";
1262
+ | "image_missing"
1263
+ | "review_target_not_found";
1210
1264
 
1211
1265
  export interface EditorWarning {
1212
1266
  warningId: string;
@@ -1223,6 +1277,13 @@ export interface EditorWarning {
1223
1277
  affectedAnchor?: EditorAnchorProjection;
1224
1278
  featureEntryId?: string;
1225
1279
  details?: Record<string, unknown>;
1280
+ /**
1281
+ * v2.0.0 — dual-error composite carrying a machine-facing `technical`
1282
+ * payload and an LLM-facing `llmMetadata` payload. Populated by the
1283
+ * editor on every warning emitted from v2.0.0 onward; older snapshots
1284
+ * may omit it. See {@link EditorDiagnostic}.
1285
+ */
1286
+ diagnostic?: EditorDiagnostic;
1226
1287
  }
1227
1288
 
1228
1289
  export type EditorErrorCode =
@@ -1240,6 +1301,149 @@ export interface EditorError {
1240
1301
  isFatal: boolean;
1241
1302
  source: "import" | "runtime" | "validation" | "datastore" | "host" | "export";
1242
1303
  details?: Record<string, unknown>;
1304
+ /**
1305
+ * v2.0.0 — dual-error composite. See {@link EditorDiagnostic}. Populated
1306
+ * by the editor from v2.0.0 onward; older snapshots may omit it.
1307
+ */
1308
+ diagnostic?: EditorDiagnostic;
1309
+ }
1310
+
1311
+ // ---------------------------------------------------------------------------
1312
+ // v2.0.0 — dual-error diagnostic composite
1313
+ // ---------------------------------------------------------------------------
1314
+
1315
+ /**
1316
+ * Unified source origin for any diagnostic emitted by the editor.
1317
+ * Superset of {@link EditorWarning.source} and {@link EditorError.source}
1318
+ * to cover API-surface + host-adapter rejections uniformly.
1319
+ */
1320
+ export type EditorDiagnosticSource =
1321
+ | "import"
1322
+ | "export"
1323
+ | "runtime"
1324
+ | "review"
1325
+ | "preservation"
1326
+ | "validation"
1327
+ | "datastore"
1328
+ | "host"
1329
+ | "api";
1330
+
1331
+ /**
1332
+ * Canonical machine-scannable code for every diagnostic surface in the
1333
+ * public API. Prefixed by convention (`import.*`, `export.*`, `runtime.*`,
1334
+ * `host.*`, `api.*`, `review.*`, `preservation.*`, `validation.*`).
1335
+ *
1336
+ * Legacy codes from {@link EditorWarningCode} / {@link EditorErrorCode} are
1337
+ * bridged into this union via the metadata table in
1338
+ * `src/runtime/diagnostics/code-metadata-table.ts`.
1339
+ *
1340
+ * Stability: `advanced-supported`. New codes are additive; existing codes
1341
+ * are permanent. Removal requires a major version bump.
1342
+ */
1343
+ export type EditorDiagnosticCode =
1344
+ | "import.failed"
1345
+ | "import.package_corrupt"
1346
+ | "import.normalized"
1347
+ | "import.unsupported_ooxml_preserved"
1348
+ | "import.unsupported_ooxml_locked"
1349
+ | "export.failed"
1350
+ | "export.roundtrip_risk"
1351
+ | "review.comment_anchor_detached"
1352
+ | "review.revision_anchor_detached"
1353
+ | "runtime.large_document_degraded"
1354
+ | "runtime.font_substitution"
1355
+ | "runtime.image_missing"
1356
+ | "runtime.internal_invariant"
1357
+ | "host.adapter_rejected"
1358
+ | "host.load_rejected"
1359
+ | "host.save_rejected"
1360
+ | "host.chart_preview_rejected"
1361
+ | "datastore.failed"
1362
+ | "datastore.load_rejected"
1363
+ | "datastore.save_rejected"
1364
+ | "validation.failed"
1365
+ | "validation.invariant_violated"
1366
+ | "api.invalid_regex"
1367
+ | "api.invalid_anchor"
1368
+ | "api.invalid_argument"
1369
+ | "api.metadata_resolver_missing"
1370
+ | "api.metadata_resolver_rejected"
1371
+ | "api.scope_not_found"
1372
+ | "api.collab_role_restricted"
1373
+ | "api.workflow_comment_only"
1374
+ | "api.command_blocked"
1375
+ // Lane 8 Track H (v2.x) — agent-helper widening. Metadata registered in
1376
+ // Phase 1; emission sites land with the Phase 2 runtime wiring.
1377
+ | "api.projection_unavailable"
1378
+ | "api.batch_edit_collision"
1379
+ | "api.workflow_patch_invalid"
1380
+ | "api.change_id_unknown"
1381
+ | "api.ai_explanation_anchor_invalid";
1382
+
1383
+ /**
1384
+ * The recovery class an agent / LLM uses to decide whether to retry,
1385
+ * reprompt, fall back, or surface to a human. Stable + enumerated.
1386
+ */
1387
+ export type EditorDiagnosticRecoveryClass =
1388
+ | "retry-safe"
1389
+ | "retry-with-backoff"
1390
+ | "requires-input"
1391
+ | "requires-resolver"
1392
+ | "requires-permission"
1393
+ | "requires-human"
1394
+ | "unrecoverable";
1395
+
1396
+ /**
1397
+ * Structured remediation the LLM can act on.
1398
+ */
1399
+ export type EditorDiagnosticRemediation =
1400
+ | { kind: "none" }
1401
+ | { kind: "retry"; afterMs?: number; maxAttempts?: number }
1402
+ | { kind: "fallback"; suggestion: string; payload?: Record<string, unknown> }
1403
+ | {
1404
+ kind: "escalate";
1405
+ to: "host" | "author" | "reviewer" | "admin";
1406
+ reason: string;
1407
+ };
1408
+
1409
+ /** Developer / machine-facing payload. */
1410
+ export interface EditorDiagnosticTechnical {
1411
+ message: string;
1412
+ source: EditorDiagnosticSource;
1413
+ stack?: string;
1414
+ cause?: {
1415
+ message: string;
1416
+ name?: string;
1417
+ stack?: string;
1418
+ };
1419
+ details?: Record<string, unknown>;
1420
+ affectedAnchor?: EditorAnchorProjection;
1421
+ featureEntryId?: string;
1422
+ }
1423
+
1424
+ /** LLM / agent-facing payload. */
1425
+ export interface EditorDiagnosticLlmMetadata {
1426
+ userSummary: string;
1427
+ remediation: EditorDiagnosticRemediation;
1428
+ recoveryClass: EditorDiagnosticRecoveryClass;
1429
+ echoedInput?: Record<string, unknown>;
1430
+ docsUrl?: string;
1431
+ tags?: string[];
1432
+ }
1433
+
1434
+ /**
1435
+ * v2.0.0 dual-error composite. LLM consumers read `llmMetadata` only;
1436
+ * developer consumers read `technical`. Host UI renders
1437
+ * `llmMetadata.userSummary` to end users. See
1438
+ * `docs/wiki/error-catalog.md` for the full code catalog.
1439
+ */
1440
+ export interface EditorDiagnostic {
1441
+ diagnosticId: string;
1442
+ severity: "fatal" | "error" | "warning" | "info";
1443
+ code: EditorDiagnosticCode;
1444
+ technical: EditorDiagnosticTechnical;
1445
+ llmMetadata: EditorDiagnosticLlmMetadata;
1446
+ emittedAt: string;
1243
1447
  }
1244
1448
 
1245
1449
  export type CompatibilityFeatureClass =
@@ -1924,6 +2128,27 @@ export interface AddScopeResult {
1924
2128
  export interface ExportDocxOptions {
1925
2129
  fileName?: string;
1926
2130
  reason?: string;
2131
+ /**
2132
+ * @experimental Lane 7c Slice 7c.4 (v2.0.0) — opt-in for Strict-flavor
2133
+ * OOXML export (ECMA-376 / ISO 29500-1 Strict, namespaces under
2134
+ * `http://purl.oclc.org/ooxml/...`). Transitional remains the default.
2135
+ *
2136
+ * **Status:** wired — `true` switches `serializeMainDocument` to the
2137
+ * Strict namespace URI set (`w`, `r`, `a`, `pic`, `wp`, `mc`) and
2138
+ * omits Microsoft extension namespace declarations
2139
+ * (`w14`/`w15`/`w16*`/`wp14`/`wps`) from the root element. `false`
2140
+ * or omitted preserves Transitional output byte-equivalent to
2141
+ * pre-7c.4 behavior.
2142
+ *
2143
+ * **Known scope limitations:** relationship `Type` URIs and
2144
+ * Content-Type URIs still use the Transitional form; extension
2145
+ * content wrapping via `mc:AlternateContent` / `mc:Fallback` is
2146
+ * not yet emitted. Full ISO 29500 Strict compliance requires those
2147
+ * follow-ups before this option graduates from `@experimental`.
2148
+ * See `docs/wiki/compatibility-and-validation.md` § Strict-flavor
2149
+ * export for the current capability matrix.
2150
+ */
2151
+ exportStrictOoxml?: boolean;
1927
2152
  }
1928
2153
 
1929
2154
  export interface ExportDelivery {
@@ -1940,6 +2165,35 @@ export interface ExportResult {
1940
2165
 
1941
2166
  export type WorkflowScopeMode = "edit" | "suggest" | "comment" | "view";
1942
2167
 
2168
+ /**
2169
+ * §C7 — Local chrome visibility mode. Never collab-replicated.
2170
+ * - `"all"`: show all scope rail entries + decorations (default).
2171
+ * - `"none"`: suppress all scope chrome; data layer unaffected.
2172
+ * - `"filtered"`: show only scopes matching `filter`.
2173
+ */
2174
+ export type ScopeChromeVisibility = "all" | "none" | "filtered";
2175
+
2176
+ /**
2177
+ * §C7 — Full chrome visibility state including an optional filter (only
2178
+ * relevant when `mode === "filtered"`).
2179
+ */
2180
+ export interface ScopeChromeVisibilityState {
2181
+ mode: ScopeChromeVisibility;
2182
+ filter?: ScopeQueryFilter;
2183
+ }
2184
+
2185
+ /**
2186
+ * §C8 — Per-scope chrome visibility. Default when absent is `"visible"`.
2187
+ * Collab-replicated: all peers see the same value. Distinct from
2188
+ * `setScopeChromeVisibility` (§C7), which is local view-state.
2189
+ *
2190
+ * - `"visible"`: rail entry + card + inline decoration (current behavior).
2191
+ * - `"hidden"`: in the rail but muted; card opens on explicit click; no decoration.
2192
+ * - `"invisible"`: never rendered; only queryable via API. Does NOT contribute
2193
+ * to InteractionGuard unless `mode === "view"` (explicit host opt-in).
2194
+ */
2195
+ export type ScopeVisibility = "visible" | "hidden" | "invisible";
2196
+
1943
2197
  export interface WorkflowCandidateRange {
1944
2198
  candidateId: string;
1945
2199
  storyTarget?: EditorStoryTarget;
@@ -1965,6 +2219,12 @@ export interface WorkflowScope {
1965
2219
  * `"inherit"`.
1966
2220
  */
1967
2221
  metadataPersistence?: ScopeMetadataPersistence;
2222
+ /**
2223
+ * §C8 — Per-scope chrome visibility. Absent / `undefined` is equivalent to
2224
+ * `"visible"`. Collab-replicated via the existing `workflow.set-overlay`
2225
+ * broadcast; old peers ignore the unknown field (read as `undefined` = visible).
2226
+ */
2227
+ visibility?: ScopeVisibility;
1968
2228
  }
1969
2229
 
1970
2230
  export interface WorkflowScopeMetadataField {
@@ -2239,6 +2499,8 @@ export interface ScopeCardModel {
2239
2499
  posture: ScopeRailPosture;
2240
2500
  label: string;
2241
2501
  primaryAnchorRect: RenderFrameRect | null;
2502
+ /** K2 — source anchor for the scope; passed to `onScopeAskAgent` so hosts skip a `getScope()` round-trip. */
2503
+ anchor?: EditorAnchorProjection;
2242
2504
  issue?: IssueMetadataValue;
2243
2505
  /** Id-only lookup; `suggestionGroups` holds the full entries. */
2244
2506
  suggestionGroupIds: readonly string[];
@@ -2303,6 +2565,13 @@ export interface InteractionGuardSnapshot {
2303
2565
  effectiveMode: EffectiveSelectionMode;
2304
2566
  matchedScopeId?: string;
2305
2567
  matchedScopeMode?: WorkflowScopeMode;
2568
+ /** §C6 — all scopes covering the selection, ordered outermost→innermost
2569
+ * (widest span first). Most-restrictive mode wins for effectiveMode. */
2570
+ matchedScopeStack?: Array<{
2571
+ scopeId: string;
2572
+ mode: WorkflowScopeMode;
2573
+ visibility: ScopeVisibility;
2574
+ }>;
2306
2575
  targetAccess?: "direct-edit" | "suggest" | "comment-only" | "view-only" | "blocked";
2307
2576
  commandCapabilities?: Array<{
2308
2577
  family: "text" | "formatting" | "structure";
@@ -2646,8 +2915,25 @@ export type AutosaveState =
2646
2915
  | { status: "saved"; savedAt: string }
2647
2916
  | { status: "error"; error: EditorError };
2648
2917
 
2918
+ /**
2919
+ * Controls the editor's automatic session-state persistence behaviour.
2920
+ * Passed as `autosave` on `WordReviewEditorProps`.
2921
+ *
2922
+ * When omitted entirely, autosave is **enabled** with a 2 000 ms debounce.
2923
+ */
2649
2924
  export interface AutosaveConfig {
2925
+ /**
2926
+ * Set to `false` to disable autosave entirely.
2927
+ * @default true
2928
+ */
2650
2929
  enabled?: boolean;
2930
+ /**
2931
+ * Milliseconds of idle time after the last edit before
2932
+ * `hostAdapter.saveSession` is called. Minimum effective value is
2933
+ * 500 ms (values below are clamped). Has no effect when `enabled` is
2934
+ * `false`.
2935
+ * @default 2000
2936
+ */
2651
2937
  debounceMs?: number;
2652
2938
  }
2653
2939
 
@@ -2710,8 +2996,8 @@ export type WordReviewEditorEvent =
2710
2996
  * the previous and current runtime render snapshot. Includes
2711
2997
  * additions, deletions, body edits, reply appends, and
2712
2998
  * resolution-state transitions. Consumers can call
2713
- * `editorRef.current.getComments()` to obtain the full updated
2714
- * `CommentSidebarSnapshot`.
2999
+ * `editorRef.current.getCommentSidebarSnapshot()` to obtain the full
3000
+ * updated `CommentSidebarSnapshot`.
2715
3001
  *
2716
3002
  * The array is always non-empty when this event fires. When the
2717
3003
  * snapshot's `comments` reference is unchanged between commits,
@@ -2835,6 +3121,13 @@ export type WordReviewEditorEvent =
2835
3121
  documentId: string;
2836
3122
  command: string;
2837
3123
  reasons: WorkflowBlockedCommandReason[];
3124
+ /**
3125
+ * v2.0.0 — per-reason diagnostic composite. When present, carries
3126
+ * one {@link EditorDiagnostic} per entry in `reasons` (matching
3127
+ * indices). Older snapshots may omit this field; LLM consumers
3128
+ * should tolerate absence.
3129
+ */
3130
+ diagnostics?: EditorDiagnostic[];
2838
3131
  }
2839
3132
  | WordReviewEditorPasteEvent
2840
3133
  | {
@@ -3130,8 +3423,25 @@ export interface ChartPreviewResolveParams {
3130
3423
  }
3131
3424
 
3132
3425
  export interface EditorHostAdapter {
3426
+ /**
3427
+ * Called once at load time to retrieve a previously-saved session
3428
+ * blob. Rejections are treated as fatal load failures and surfaced
3429
+ * via the `onError` callback with `code: "host_load_failed"`. The
3430
+ * editor does not retry.
3431
+ */
3133
3432
  load?(params: LoadRequest): Promise<LoadResult>;
3433
+ /**
3434
+ * Called after each debounce window when the in-memory session state
3435
+ * has changed. Rejections are non-fatal: the editor emits
3436
+ * `autosave_state { status: "error" }` and retries on the next dirty
3437
+ * commit. Must be idempotent.
3438
+ */
3134
3439
  saveSession?(params: SaveSessionParams): Promise<SaveSessionResult>;
3440
+ /**
3441
+ * Called when the user triggers an explicit export. Rejections
3442
+ * propagate as a rejected `Promise<ExportResult>` from `exportDocx()`
3443
+ * — the host is responsible for surfacing the error to the user.
3444
+ */
3135
3445
  saveExport?(params: SaveExportParams): Promise<SaveExportResult>;
3136
3446
  logEvent?(event: EditorTelemetryEvent): void;
3137
3447
  /**
@@ -3146,6 +3456,10 @@ export interface EditorHostAdapter {
3146
3456
  * for a PNG magic number, `image/svg+xml` otherwise. Hosts that
3147
3457
  * need a different content type should extend this contract in a
3148
3458
  * follow-up.
3459
+ *
3460
+ * Rejections and thrown exceptions are caught by the editor and
3461
+ * treated identically to a `null` return — the badge fallback path
3462
+ * activates and the error is logged non-fatally.
3149
3463
  */
3150
3464
  renderChartPreview?(params: ChartPreviewResolveParams): Promise<Uint8Array | null>;
3151
3465
  }
@@ -3157,6 +3471,404 @@ export interface EditorDatastoreAdapter {
3157
3471
  logEvent?(event: EditorTelemetryEvent): void;
3158
3472
  }
3159
3473
 
3474
+ // ---------------------------------------------------------------------------
3475
+ // v2.x — Lane 8 Track H agent-helper widening (Phase 1: types only)
3476
+ //
3477
+ // Derived from the CLM workblock (`docs/CLM (10).yaml`) hand-rolled patterns:
3478
+ // `snapshot_to_projection`, back-to-front anchor-sorted field fill,
3479
+ // `change_id → range` walking, and read-merge-write workflow-overlay
3480
+ // annotation. See `docs/wiki/agent-helpers.md` for the narrative and
3481
+ // `docs/plans/lane-8-api-ergonomics.md` § Track H for the phased plan.
3482
+ //
3483
+ // Phase 1 ships type declarations and optional method signatures on
3484
+ // `WordReviewEditorRef`; runtime wiring lands in Phase 2, Python parity
3485
+ // in Phase 3.
3486
+ // ---------------------------------------------------------------------------
3487
+
3488
+ /**
3489
+ * Options controlling the shape of the annotated-text projection returned
3490
+ * by {@link WordReviewEditorRef.getRenderSnapshotAsText} /
3491
+ * {@link EditorSurfaceSnapshotLike.toAnnotatedText}.
3492
+ *
3493
+ * All flags default to `true`; callers who only want the raw text can
3494
+ * opt everything off to skip the post-processing cost.
3495
+ */
3496
+ export interface TextProjectionOptions {
3497
+ /**
3498
+ * When `true` (default), every line in {@link TextProjection.lines}
3499
+ * carries the `[start, end)` runtime offsets the line spans in the
3500
+ * active story. Offsets are the same unit `findAllText` / `replaceText`
3501
+ * / `addScope` accept, so agent code can feed offsets back into
3502
+ * mutation calls without re-projection.
3503
+ */
3504
+ withOffsets?: boolean;
3505
+ /**
3506
+ * When `true` (default), {@link TextProjection.lines} is populated.
3507
+ * When `false`, only {@link TextProjection.text} is computed; useful
3508
+ * for regex search where line boundaries don't matter.
3509
+ */
3510
+ withLineMap?: boolean;
3511
+ /**
3512
+ * When `true` (default), {@link TextProjection.stories} is populated
3513
+ * with one entry per non-main story (header/footer/footnote/endnote)
3514
+ * that carries its own offset space. Set `false` to skip secondary
3515
+ * stories entirely — main body only.
3516
+ */
3517
+ withStoryMap?: boolean;
3518
+ /**
3519
+ * Restrict projection to a specific story. Defaults to main body.
3520
+ * Unknown story targets return an empty projection (no throw).
3521
+ */
3522
+ storyTarget?: EditorStoryTarget;
3523
+ }
3524
+
3525
+ /**
3526
+ * A single line within an annotated text projection. Lines are produced
3527
+ * by the same line-segmentation logic that backs `findAllText`'s
3528
+ * `matchLocation.lineIndex`, so agents can round-trip between
3529
+ * `findAllText` results and line indices deterministically.
3530
+ */
3531
+ export interface TextProjectionLine {
3532
+ /** Zero-based line index within the containing story. */
3533
+ lineIndex: number;
3534
+ /** Line text, without trailing newline. */
3535
+ text: string;
3536
+ /**
3537
+ * `[start, end)` runtime offsets this line spans. End is exclusive
3538
+ * of any trailing newline. Present only when
3539
+ * {@link TextProjectionOptions.withOffsets} is `true`.
3540
+ */
3541
+ start?: number;
3542
+ end?: number;
3543
+ /** Block id the line belongs to, when derivable. */
3544
+ blockId?: string;
3545
+ /** Story the line belongs to; defaults to main body. */
3546
+ storyTarget?: EditorStoryTarget;
3547
+ }
3548
+
3549
+ /**
3550
+ * Per-story section of a text projection. Main body is returned on the
3551
+ * top-level {@link TextProjection} fields; non-main stories each get one
3552
+ * entry here with their own offset space.
3553
+ */
3554
+ export interface TextProjectionStoryEntry {
3555
+ storyTarget: EditorStoryTarget;
3556
+ text: string;
3557
+ lines?: TextProjectionLine[];
3558
+ }
3559
+
3560
+ /**
3561
+ * Annotated linear-text projection of the render snapshot. Replaces the
3562
+ * hand-written `snapshot_to_projection` / `workblock.cdr` wrapper that
3563
+ * CLM workblocks carry today. Text is in the same offset space as
3564
+ * `findAllText`, `replaceText`, and `addScope` ranges, so agent code
3565
+ * can search the flattened text, then feed the matching offsets
3566
+ * directly back into mutation APIs.
3567
+ */
3568
+ export interface TextProjection {
3569
+ /** Main-body text, newline-separated. */
3570
+ text: string;
3571
+ /** Main-body line map (absent when `withLineMap: false`). */
3572
+ lines?: TextProjectionLine[];
3573
+ /** Non-main-body stories (absent when `withStoryMap: false`). */
3574
+ stories?: TextProjectionStoryEntry[];
3575
+ /**
3576
+ * Total line count across main + stories. Stable even when
3577
+ * `withLineMap: false` (counted without emitting the array).
3578
+ */
3579
+ totalLines: number;
3580
+ }
3581
+
3582
+ /**
3583
+ * Typed handle for a tracked change or comment thread as returned by
3584
+ * {@link WordReviewEditorRef.findChangeById} /
3585
+ * {@link WordReviewEditorRef.findAllChanges}. Collapses the current
3586
+ * two-step `getComments() → .threads` + `getTrackedChanges() → .revisions`
3587
+ * walk that CLM's `_get_range_from_diff_items` / `_get_range_from_doc`
3588
+ * open-codes today.
3589
+ */
3590
+ export interface ChangeAnchor {
3591
+ kind: "comment" | "revision";
3592
+ /** `commentId` (when `kind === "comment"`) or `revisionId`. */
3593
+ id: string;
3594
+ /**
3595
+ * Best-known live anchor. For comments: the thread anchor. For
3596
+ * revisions: `anchor.range` (fresh) or `anchor.lastKnownRange`
3597
+ * (detached). Consumers should treat detached anchors as advisory.
3598
+ */
3599
+ anchor: EditorAnchorProjection;
3600
+ storyTarget?: EditorStoryTarget;
3601
+ /** `false` when the underlying thread/revision is detached. */
3602
+ isLive: boolean;
3603
+ }
3604
+
3605
+ /**
3606
+ * Filter for {@link WordReviewEditorRef.findAllChanges}. AND-combined;
3607
+ * omitted fields do not constrain the result.
3608
+ */
3609
+ export interface ChangeFilter {
3610
+ kind?: "comment" | "revision";
3611
+ storyTarget?: EditorStoryTarget;
3612
+ authorId?: string;
3613
+ /** Only return changes authored at/after this revision token. */
3614
+ sinceRevisionToken?: string;
3615
+ /** Only return live (non-detached) changes. Defaults to `false`. */
3616
+ liveOnly?: boolean;
3617
+ }
3618
+
3619
+ /**
3620
+ * One edit in a {@link WordReviewEditorRef.applyBatchedEdits} batch.
3621
+ * Discriminated by `kind`. Each shape mirrors an existing ref method
3622
+ * (`replaceText`, `insertFragment`, `setFontFamily`-style mark ops).
3623
+ */
3624
+ export type BatchEditOperation =
3625
+ | {
3626
+ kind: "replace-text";
3627
+ target: EditorAnchorProjection;
3628
+ text: string;
3629
+ formatting?: TextFormattingDirective;
3630
+ }
3631
+ | {
3632
+ kind: "insert-fragment";
3633
+ target: EditorAnchorProjection;
3634
+ fragment: CanonicalDocumentFragment;
3635
+ }
3636
+ | {
3637
+ kind: "set-mark";
3638
+ target: EditorAnchorProjection;
3639
+ mark: TextMark;
3640
+ }
3641
+ | {
3642
+ kind: "clear-mark";
3643
+ target: EditorAnchorProjection;
3644
+ mark: TextMark["type"];
3645
+ };
3646
+
3647
+ /**
3648
+ * Sequencing contract for {@link WordReviewEditorRef.applyBatchedEdits}.
3649
+ *
3650
+ * - `"back-to-front"`: edits are sorted by descending `target.range.to`
3651
+ * before apply, so earlier offsets are not shifted by later edits.
3652
+ * Use for field-fill / find-and-replace workflows. Default.
3653
+ * - `"atomic"`: edits are applied in array order inside a single
3654
+ * `startAction("batch")` bracket; any failure rolls back the
3655
+ * whole batch via a single `undo()`.
3656
+ */
3657
+ export interface BatchEditOptions {
3658
+ mode?: "back-to-front" | "atomic";
3659
+ /** Optional label for the action bracket; surfaces in undo UX. */
3660
+ actionLabel?: string;
3661
+ }
3662
+
3663
+ export interface BatchEditEntryResult {
3664
+ ok: boolean;
3665
+ /** Diagnostic (recoverable skip) when `ok === false`. */
3666
+ diagnostic?: EditorDiagnostic;
3667
+ }
3668
+
3669
+ export interface BatchEditResult {
3670
+ appliedCount: number;
3671
+ skippedCount: number;
3672
+ entries: BatchEditEntryResult[];
3673
+ }
3674
+
3675
+ /**
3676
+ * Differential patch for {@link WorkflowOverlay}. Replaces the
3677
+ * read-merge-write pattern documented in `public-api.md` under
3678
+ * `getWorkflowOverlay()`. Runtime-authored fields (`scopes` from
3679
+ * `addScope`, `workItems`) are never clobbered; only the fields
3680
+ * named in the patch are touched.
3681
+ */
3682
+ export interface WorkflowOverlayPatch {
3683
+ addScopes?: WorkflowScope[];
3684
+ removeScopeIds?: string[];
3685
+ addCandidates?: WorkflowCandidateRange[];
3686
+ removeCandidateIds?: string[];
3687
+ /** Shallow-merge into existing work items by `workItemId`. */
3688
+ mergeWorkItems?: WorkflowWorkItem[];
3689
+ /**
3690
+ * When set, overlay-level `metadataPersistence` is replaced. Omit to
3691
+ * leave the current value alone.
3692
+ */
3693
+ metadataPersistence?: MetadataPersistenceMode;
3694
+ }
3695
+
3696
+ /**
3697
+ * Input shape for {@link WordReviewEditorRef.attachAiExplanationScope}.
3698
+ * Collapses the "find change → build scope → patch overlay" sequence
3699
+ * CLM workblocks hand-roll in `annotate_document_with_explanations`.
3700
+ */
3701
+ export interface AiExplanationScopeInput {
3702
+ /** `commentId` or `revisionId` to anchor the explanation against. */
3703
+ changeId: string;
3704
+ explanation: {
3705
+ summary: string;
3706
+ detail?: string;
3707
+ riskLevel?: "low" | "medium" | "high" | "unknown";
3708
+ recommendedAction?: "accept" | "reject" | "review" | "escalate";
3709
+ actionRationale?: string;
3710
+ /** Free-form location label (e.g., "§4.2 payment terms"). */
3711
+ location?: string;
3712
+ };
3713
+ /** Scope mode. Defaults to `"view"` — advisory-only. */
3714
+ mode?: WorkflowScopeMode;
3715
+ /** Optional caller-supplied scope id; runtime mints one when absent. */
3716
+ scopeId?: string;
3717
+ /** Domain tag. Defaults to `"ai-suggestion"`. */
3718
+ domain?: string;
3719
+ }
3720
+
3721
+ export interface AiExplanationScopeResult {
3722
+ scopeId: string;
3723
+ candidateId: string;
3724
+ anchor: EditorAnchorProjection;
3725
+ }
3726
+
3727
+ // ---------------------------------------------------------------------------
3728
+ // v2.0.0 — Track D purpose-grouped ref projections
3729
+ // ---------------------------------------------------------------------------
3730
+
3731
+ /**
3732
+ * Ergonomic projection of comment-related methods. Pure dispatch over
3733
+ * {@link WordReviewEditorRef} — flat methods keep working. LLM workblocks
3734
+ * and wrapper layers should prefer the projection to narrow the surface
3735
+ * they import.
3736
+ */
3737
+ export interface WordReviewEditorCommentsFacet {
3738
+ add(params: AddCommentParams): AddCommentResult;
3739
+ addReply(commentId: string, body: string): AddCommentReplyResult | null;
3740
+ resolve(commentId: string): void;
3741
+ reopen(commentId: string): void;
3742
+ edit(commentId: string, body: string): void;
3743
+ delete(commentId: string): void;
3744
+ open(commentId: string): void;
3745
+ scrollTo(commentId: string): void;
3746
+ get(): CommentSidebarSnapshot;
3747
+ /**
3748
+ * Track H (v2.x Phase 1 — types only; runtime wired in Phase 2). Typed
3749
+ * id lookup over `get().threads`. Returns `null` when the id is unknown.
3750
+ */
3751
+ getById?(commentId: string): CommentSidebarThreadSnapshot | null;
3752
+ }
3753
+
3754
+ /** Ergonomic projection of tracked-change methods. */
3755
+ export interface WordReviewEditorChangesFacet {
3756
+ accept(changeId: string): void;
3757
+ reject(changeId: string): void;
3758
+ acceptAll(): void;
3759
+ rejectAll(): void;
3760
+ acceptGroup(groupId: string): void;
3761
+ rejectGroup(groupId: string): void;
3762
+ scrollTo(revisionId: string): void;
3763
+ get(): TrackedChangesSnapshot;
3764
+ getSuggestions(): SuggestionsSnapshot;
3765
+ /**
3766
+ * Track H (v2.x Phase 1 — types only; runtime wired in Phase 2). Typed
3767
+ * id lookup over `get().revisions`. Returns `null` when unknown.
3768
+ */
3769
+ getById?(revisionId: string): TrackedChangeEntrySnapshot | null;
3770
+ /**
3771
+ * Track H — unified change-lookup across comments + revisions. Replaces
3772
+ * the hand-rolled `_get_range_from_diff_items` walk.
3773
+ */
3774
+ findById?(changeId: string): ChangeAnchor | null;
3775
+ /** Track H — filter over all comments + revisions. */
3776
+ findAll?(filter?: ChangeFilter): ChangeAnchor[];
3777
+ }
3778
+
3779
+ /** Ergonomic projection of field / TOC operations. */
3780
+ export interface WordReviewEditorFieldsFacet {
3781
+ getSnapshot(): FieldSnapshot;
3782
+ update(options?: UpdateFieldsOptions): UpdateFieldsResult;
3783
+ updateToc(options?: TocRefreshOptions): TocRefreshResult;
3784
+ }
3785
+
3786
+ /** Ergonomic projection of document-level operations. */
3787
+ export interface WordReviewEditorDocumentFacet {
3788
+ export(options?: ExportDocxOptions): Promise<ExportResult>;
3789
+ getSessionState(): EditorSessionState;
3790
+ getSnapshot(): PersistedEditorSnapshot;
3791
+ getRenderSnapshot(): RuntimeRenderSnapshot;
3792
+ isDirty(): boolean;
3793
+ getCompatibilityReport(): CompatibilityReport;
3794
+ getStats(): DocumentStats;
3795
+ /**
3796
+ * Track H (v2.x Phase 1 — types only; runtime wired in Phase 2).
3797
+ * Annotated linear-text projection with stable runtime offsets.
3798
+ * Replaces the hand-written `snapshot_to_projection` helper.
3799
+ */
3800
+ getAsText?(options?: TextProjectionOptions): TextProjection;
3801
+ /**
3802
+ * Track H — sequenced replace/insert/mark batch with offset-shift
3803
+ * protection. Collapses the back-to-front sort + bytes-chain pattern
3804
+ * from CLM's `generate_filled_document`.
3805
+ */
3806
+ applyBatchedEdits?(
3807
+ edits: BatchEditOperation[],
3808
+ options?: BatchEditOptions,
3809
+ ): Promise<BatchEditResult>;
3810
+ /**
3811
+ * Track H — one-shot `patchWorkflowOverlay` + `exportDocx`. Use for
3812
+ * AI-annotation pipelines that would otherwise run two stateless
3813
+ * round-trips through the same document.
3814
+ */
3815
+ exportWithOverlayPatch?(
3816
+ patch: WorkflowOverlayPatch,
3817
+ exportOptions?: ExportDocxOptions,
3818
+ ): Promise<ExportResult>;
3819
+ }
3820
+
3821
+ /**
3822
+ * Ergonomic projection of workflow-scope query methods. Phase C+ LLM
3823
+ * helpers (`adjust`, `resize`, `alignToBoundary`, `addForText`,
3824
+ * `applyPlaybook`, `getRenderProjection`) will be added additively as
3825
+ * the underlying ref methods merge from the Phase C+ lane.
3826
+ */
3827
+ export interface WordReviewEditorScopesFacet {
3828
+ add(params: AddScopeParams): AddScopeResult;
3829
+ get(scopeId: string): WorkflowScope | null;
3830
+ remove(scopeId: string): void;
3831
+ query(filter?: ScopeQueryFilter): ScopeQueryResult[];
3832
+ findAt(
3833
+ position: EditorAnchorProjection,
3834
+ options?: { includeHidden?: boolean; includeInvisible?: boolean },
3835
+ ): ScopeQueryResult[];
3836
+ findIntersecting(
3837
+ range: EditorAnchorProjection,
3838
+ options?: {
3839
+ includeHidden?: boolean;
3840
+ includeInvisible?: boolean;
3841
+ mode?: "overlap" | "contain";
3842
+ },
3843
+ ): ScopeQueryResult[];
3844
+ /**
3845
+ * Track H (v2.x Phase 1 — types only; runtime wired in Phase 2).
3846
+ * Differential overlay patch. Never clobbers engine-authored scopes
3847
+ * or work items — only the fields named in the patch are touched.
3848
+ */
3849
+ patch?(patch: WorkflowOverlayPatch): void;
3850
+ /**
3851
+ * Track H — one-shot convenience: resolve `changeId` via
3852
+ * `findChangeById`, build an AI-explanation scope + candidate, and
3853
+ * patch the overlay. Collapses ~60 lines of CLM workblock glue.
3854
+ */
3855
+ attachAiExplanation?(input: AiExplanationScopeInput): AiExplanationScopeResult;
3856
+ }
3857
+
3858
+ /**
3859
+ * Ergonomic projection of diagnostic surfaces. Exposes the legacy warning
3860
+ * array plus the v2.0.0 code catalog for LLM consumers that want to
3861
+ * discover remediation strategies up front (before an error fires).
3862
+ */
3863
+ export interface WordReviewEditorDiagnosticsFacet {
3864
+ getWarnings(): EditorWarning[];
3865
+ getCatalog(): ReadonlyArray<{
3866
+ code: EditorDiagnosticCode;
3867
+ severity: "fatal" | "error" | "warning" | "info";
3868
+ llmMetadata: EditorDiagnosticLlmMetadata;
3869
+ }>;
3870
+ }
3871
+
3160
3872
  export interface WordReviewEditorRef {
3161
3873
  focus(): void;
3162
3874
  blur(): void;
@@ -3166,7 +3878,17 @@ export interface WordReviewEditorRef {
3166
3878
  openComment(commentId: string): void;
3167
3879
  resolveComment(commentId: string): void;
3168
3880
  reopenComment(commentId: string): void;
3169
- addCommentReply(commentId: string, body: string): AddCommentReplyResult;
3881
+ /**
3882
+ * Append a reply entry to an existing thread. Returns `{ commentId,
3883
+ * entryId }` on success and `null` when the thread is unknown, resolved,
3884
+ * or detached — in that case a `review_target_not_found` warning fires
3885
+ * on `onWarning` / `warning_added` with `details.op = "addCommentReply"`
3886
+ * and `details.reason` ∈ `{ "comment_unknown", "comment_status" }`.
3887
+ */
3888
+ addCommentReply(
3889
+ commentId: string,
3890
+ body: string,
3891
+ ): AddCommentReplyResult | null;
3170
3892
  editCommentBody(commentId: string, body: string): void;
3171
3893
  deleteComment(commentId: string): void;
3172
3894
  /**
@@ -3187,6 +3909,34 @@ export interface WordReviewEditorRef {
3187
3909
  * metadata record. No-op when the scopeId is unknown.
3188
3910
  */
3189
3911
  removeScope(scopeId: string): void;
3912
+ /**
3913
+ * §C8 — Convenience: adds a scope with `visibility: "invisible"` atomically.
3914
+ * Mode defaults to `"comment"` — invisible scopes carry no InteractionGuard
3915
+ * constraint unless `mode: "view"` is passed explicitly.
3916
+ */
3917
+ addInvisibleScope(
3918
+ params: Omit<AddScopeParams, "mode"> & { mode?: WorkflowScopeMode },
3919
+ ): AddScopeResult;
3920
+ /**
3921
+ * §C8 — Set a scope's visibility. Collab-replicated; all peers see the same
3922
+ * chrome state after the next overlay-replay cycle.
3923
+ */
3924
+ setScopeVisibility(scopeId: string, visibility: ScopeVisibility): void;
3925
+ /**
3926
+ * §C8 — Get a scope's current visibility. Returns `"visible"` for unknown
3927
+ * scopes or when the `visibility` field has never been set.
3928
+ */
3929
+ getScopeVisibility(scopeId: string): ScopeVisibility;
3930
+ /**
3931
+ * §C7 — Set the local chrome-visibility state. Local view-state only —
3932
+ * never collab-replicated. Controls whether the scope rail / decorations
3933
+ * render in the current session.
3934
+ */
3935
+ setScopeChromeVisibility(state: ScopeChromeVisibilityState): void;
3936
+ /**
3937
+ * §C7 — Get the local chrome-visibility state. Default is `{ mode: "all" }`.
3938
+ */
3939
+ getScopeChromeVisibility(): ScopeChromeVisibilityState;
3190
3940
  acceptChange(changeId: string): void;
3191
3941
  rejectChange(changeId: string): void;
3192
3942
  acceptAllChanges(): void;
@@ -3219,7 +3969,9 @@ export interface WordReviewEditorRef {
3219
3969
  getCommentSidebarSnapshot(): CommentSidebarSnapshot;
3220
3970
  getTrackedChangesSnapshot(): TrackedChangesSnapshot;
3221
3971
  getSuggestionsSnapshot(): SuggestionsSnapshot;
3972
+ /** @deprecated Use {@link getCommentSidebarSnapshot} instead. */
3222
3973
  getComments(): CommentSidebarSnapshot;
3974
+ /** @deprecated Use {@link getTrackedChangesSnapshot} instead. */
3223
3975
  getTrackedChanges(): TrackedChangesSnapshot;
3224
3976
  isDirty(): boolean;
3225
3977
  getFormattingState(): FormattingStateSnapshot;
@@ -3326,7 +4078,7 @@ export interface WordReviewEditorRef {
3326
4078
  setCellBackground(color: string): void;
3327
4079
  search(query: string, options?: SearchOptions): SearchResultSnapshot[];
3328
4080
  clearSearch(): void;
3329
- setSelection(selection: SelectionSnapshot | null): void;
4081
+ setSelection(selection: SelectionSnapshot | null, options?: SetSelectionOptions): void;
3330
4082
  scrollToRevision(revisionId: string): void;
3331
4083
  scrollToComment(commentId: string): void;
3332
4084
  openStory(target: EditorStoryTarget): void;
@@ -3414,6 +4166,18 @@ export interface WordReviewEditorRef {
3414
4166
  * Returns `[]` when no workflow overlay has been set.
3415
4167
  */
3416
4168
  queryScopes(filter?: ScopeQueryFilter): ScopeQueryResult[];
4169
+ /**
4170
+ * Phase C §C1 — live subscription to `queryScopes(filter)` results.
4171
+ * Fires the callback immediately, then once per settled commit after any
4172
+ * overlay change that passes the filter. Multiple changes in one
4173
+ * synchronous burst are coalesced into a single callback via `setTimeout(0)`.
4174
+ * Shallow-equality dedup: callback skips if results are unchanged.
4175
+ * Returns an unsubscribe function.
4176
+ */
4177
+ subscribeToScopeQuery(
4178
+ filter: ScopeQueryFilter,
4179
+ callback: (results: ScopeQueryResult[]) => void,
4180
+ ): () => void;
3417
4181
  /**
3418
4182
  * Phase C §C2 — every scope whose marker range contains `position.from`
3419
4183
  * (end-inclusive), ordered outermost → innermost. Pass a zero-length
@@ -3470,7 +4234,7 @@ export interface WordReviewEditorRef {
3470
4234
  */
3471
4235
  selectFirstText(
3472
4236
  query: string,
3473
- options?: SearchOptions,
4237
+ options?: SearchOptions & SetSelectionOptions,
3474
4238
  ): boolean;
3475
4239
  /**
3476
4240
  * Phase C §C3 — select first text match and return the total match count.
@@ -3479,7 +4243,33 @@ export interface WordReviewEditorRef {
3479
4243
  */
3480
4244
  selectAllText(
3481
4245
  query: string,
4246
+ options?: SearchOptions & SetSelectionOptions,
4247
+ ): number;
4248
+ /**
4249
+ * Phase C §C4 — find all text matches that also satisfy the given style
4250
+ * filter. Combines `findAllText` text search with paragraph-level and
4251
+ * run-level formatting predicates:
4252
+ * - `inHeading`: paragraph must be a heading (outlineLevel set or styleId
4253
+ * matches /^Heading\d/i).
4254
+ * - `hasFormatting`: ALL segments in the match must carry ALL specified
4255
+ * formatting marks (AND semantics per property, AND across segments).
4256
+ * - `anyFormatting`: ALL segments in the match must carry AT LEAST ONE of
4257
+ * the specified marks (OR semantics per property, AND across segments).
4258
+ * An empty filter is a no-op — returns all text matches.
4259
+ */
4260
+ findTextWithStyle(
4261
+ query: string,
4262
+ filter: TextStyleFilter,
3482
4263
  options?: SearchOptions,
4264
+ ): EditorAnchorProjection[];
4265
+ /**
4266
+ * Phase C §C4 — convenience wrapper: `findTextWithStyle` + select the first
4267
+ * result. Returns the total match count (0 when no matches).
4268
+ */
4269
+ selectTextWithStyle(
4270
+ query: string,
4271
+ filter: TextStyleFilter,
4272
+ options?: SearchOptions & SetSelectionOptions,
3483
4273
  ): number;
3484
4274
  /**
3485
4275
  * Schema 1.1 — set the overlay default for metadata persistence.
@@ -3525,7 +4315,9 @@ export interface WordReviewEditorRef {
3525
4315
  * `"external"`, call `resolver.resolve(ref)`, inline the returned
3526
4316
  * value, clear `storageRef`, preserve `metadataVersion` as a hint.
3527
4317
  * Call this before exporting a docx outside the resolver's reach
3528
- * (e.g., sending to an external supplier).
4318
+ * (e.g., sending to an external supplier). Rejects if
4319
+ * `resolver.resolve` throws for any entry; partial conversions are
4320
+ * rolled back.
3529
4321
  */
3530
4322
  convertScopesToInternal(scopeIds: string[]): Promise<void>;
3531
4323
  /**
@@ -3564,6 +4356,8 @@ export interface WordReviewEditorRef {
3564
4356
  /**
3565
4357
  * Re-attempt any persists that failed since the last successful
3566
4358
  * write. Pass a namespace to scope the retry; omit to retry all.
4359
+ * Rejects if the persister throws on retry; the failed namespace
4360
+ * remains in the pending queue.
3567
4361
  */
3568
4362
  retryPendingPersist(namespace?: EditorStateNamespace): Promise<void>;
3569
4363
  setHostAnnotationOverlay(overlay: HostAnnotationOverlay): void;
@@ -3580,6 +4374,92 @@ export interface WordReviewEditorRef {
3580
4374
  query?: RuntimeContextAnalyticsQuery,
3581
4375
  ): RuntimeContextAnalyticsSnapshot | null;
3582
4376
 
4377
+ // -------------------------------------------------------------------------
4378
+ // Track H — agent-helper widening (v2.x Phase 1: optional; wired Phase 2)
4379
+ // -------------------------------------------------------------------------
4380
+
4381
+ /**
4382
+ * Track H T1 — annotated linear-text projection with stable runtime
4383
+ * offsets. Replaces the hand-written `snapshot_to_projection` helper
4384
+ * that CLM workblocks carry in `workblock.cdr`.
4385
+ *
4386
+ * **Status:** @experimental (v2.x). Types land in Phase 1; runtime
4387
+ * wiring in Phase 2.
4388
+ */
4389
+ getRenderSnapshotAsText?(options?: TextProjectionOptions): TextProjection;
4390
+ /**
4391
+ * Track H T2 — typed lookup by `commentId` or `revisionId` across
4392
+ * comments + tracked changes. Returns `null` when the id is unknown.
4393
+ * Collapses the two-step walk over `getComments().threads` +
4394
+ * `getTrackedChanges().revisions` that agents currently open-code.
4395
+ *
4396
+ * **Status:** @experimental (v2.x Phase 1).
4397
+ */
4398
+ findChangeById?(changeId: string): ChangeAnchor | null;
4399
+ /**
4400
+ * Track H T2 — filtered enumeration over comments + revisions.
4401
+ *
4402
+ * **Status:** @experimental (v2.x Phase 1).
4403
+ */
4404
+ findAllChanges?(filter?: ChangeFilter): ChangeAnchor[];
4405
+ /**
4406
+ * Track H T10 — typed id lookup over the comment sidebar snapshot.
4407
+ *
4408
+ * **Status:** @experimental (v2.x Phase 1).
4409
+ */
4410
+ getCommentSnapshotById?(commentId: string): CommentSidebarThreadSnapshot | null;
4411
+ /**
4412
+ * Track H T10 — typed id lookup over the tracked-changes snapshot.
4413
+ *
4414
+ * **Status:** @experimental (v2.x Phase 1).
4415
+ */
4416
+ getRevisionSnapshotById?(revisionId: string): TrackedChangeEntrySnapshot | null;
4417
+ /**
4418
+ * Track H T3 — sequenced batch of replace/insert/mark operations with
4419
+ * offset-shift protection. In `"back-to-front"` mode (default), edits
4420
+ * are sorted by descending `target.range.to` before apply so earlier
4421
+ * offsets are not shifted by later edits. In `"atomic"` mode the batch
4422
+ * runs inside a single `startAction` bracket and rolls back on failure.
4423
+ * Replaces the manual bytes-chain + sort pattern from CLM's
4424
+ * `generate_filled_document`.
4425
+ *
4426
+ * **Status:** @experimental (v2.x Phase 1).
4427
+ */
4428
+ applyBatchedEdits?(
4429
+ edits: BatchEditOperation[],
4430
+ options?: BatchEditOptions,
4431
+ ): Promise<BatchEditResult>;
4432
+ /**
4433
+ * Track H T4 — differential `WorkflowOverlay` patch. Never clobbers
4434
+ * engine-authored `scopes` or `workItems`; only the fields named in
4435
+ * the patch are touched. Replaces the documented read-merge-write
4436
+ * pattern around `getWorkflowOverlay()` + `setWorkflowOverlay()`.
4437
+ *
4438
+ * **Status:** @experimental (v2.x Phase 1).
4439
+ */
4440
+ patchWorkflowOverlay?(patch: WorkflowOverlayPatch): void;
4441
+ /**
4442
+ * Track H T5 — resolve `changeId` via `findChangeById`, build an
4443
+ * AI-explanation scope + candidate, and patch the overlay. One call
4444
+ * replaces ~60 lines of `annotate_document_with_explanations` glue.
4445
+ *
4446
+ * **Status:** @experimental (v2.x Phase 1).
4447
+ */
4448
+ attachAiExplanationScope?(
4449
+ input: AiExplanationScopeInput,
4450
+ ): AiExplanationScopeResult;
4451
+ /**
4452
+ * Track H T6 — one-shot `patchWorkflowOverlay` + `exportDocx`. Use
4453
+ * for AI-annotation pipelines that would otherwise run two stateless
4454
+ * round-trips through the same document.
4455
+ *
4456
+ * **Status:** @experimental (v2.x Phase 1).
4457
+ */
4458
+ exportDocxFromOverlayedSession?(
4459
+ patch: WorkflowOverlayPatch,
4460
+ exportOptions?: ExportDocxOptions,
4461
+ ): Promise<ExportResult>;
4462
+
3583
4463
  /**
3584
4464
  * Runtime-owned layout facet.
3585
4465
  *
@@ -3599,6 +4479,26 @@ export interface WordReviewEditorRef {
3599
4479
  * `ref.tables.apply(op)` with a typed discriminated union.
3600
4480
  */
3601
4481
  readonly tables: WordReviewEditorTablesFacet;
4482
+ /**
4483
+ * v2.0.0 — purpose-grouped projection of comment methods. Flat methods
4484
+ * (`addComment`, `resolveComment`, …) keep working. LLM workblocks should
4485
+ * prefer `editor.comments.*` to narrow their imports.
4486
+ */
4487
+ readonly comments: WordReviewEditorCommentsFacet;
4488
+ /** v2.0.0 — purpose-grouped projection of tracked-change methods. */
4489
+ readonly changes: WordReviewEditorChangesFacet;
4490
+ /** v2.0.0 — purpose-grouped projection of field / TOC operations. */
4491
+ readonly fields: WordReviewEditorFieldsFacet;
4492
+ /** v2.0.0 — purpose-grouped projection of document-level operations. */
4493
+ readonly document: WordReviewEditorDocumentFacet;
4494
+ /** v2.0.0 — purpose-grouped projection of workflow-scope + LLM helpers. */
4495
+ readonly scopes: WordReviewEditorScopesFacet;
4496
+ /**
4497
+ * v2.0.0 — diagnostic surface including the LLM error-catalog. Prefer
4498
+ * `editor.diagnostics.getCatalog()` at session-start to learn the
4499
+ * retry/fallback strategy for every code the editor can emit.
4500
+ */
4501
+ readonly diagnostics: WordReviewEditorDiagnosticsFacet;
3602
4502
  }
3603
4503
 
3604
4504
  /**
@@ -3663,6 +4563,13 @@ export interface WordReviewEditorChromeOptions {
3663
4563
  export interface WordReviewEditorProps {
3664
4564
  documentId: string;
3665
4565
  currentUser: EditorUser;
4566
+ /**
4567
+ * Optional host-provided shell content mounted above the editor's own
4568
+ * toolbar region. Harnesses and host apps use this to install a
4569
+ * `TwShellHeader` without rendering a parallel chrome outside the
4570
+ * editor workspace.
4571
+ */
4572
+ shellHeader?: ReactNode;
3666
4573
  ydoc?: import('yjs').Doc;
3667
4574
  awareness?: import("y-protocols/awareness").Awareness;
3668
4575
  /**
@@ -3789,8 +4696,23 @@ export interface WordReviewEditorProps {
3789
4696
  hostAdapter?: EditorHostAdapter;
3790
4697
  datastore?: EditorDatastoreAdapter;
3791
4698
  autosave?: AutosaveConfig;
4699
+ /**
4700
+ * Receives every `WordReviewEditorEvent` as it fires. Exceptions
4701
+ * thrown inside this callback are caught and logged non-fatally —
4702
+ * they do not propagate into the editor. Returning a Promise is
4703
+ * allowed but ignored.
4704
+ */
3792
4705
  onEvent?: (event: WordReviewEditorEvent) => void;
4706
+ /**
4707
+ * Receives non-fatal `EditorWarning` objects (e.g., compatibility
4708
+ * issues, detached anchors). Exceptions thrown here are swallowed.
4709
+ */
3793
4710
  onWarning?: (warning: EditorWarning) => void;
4711
+ /**
4712
+ * Receives fatal `EditorError` objects. Called once per error; the
4713
+ * editor enters a degraded state afterward. Exceptions thrown inside
4714
+ * this callback are swallowed to avoid double-fault loops.
4715
+ */
3794
4716
  onError?: (error: EditorError) => void;
3795
4717
  /**
3796
4718
  * Optional: opens the host's sidebar to the tracked-changes panel. When
@@ -3905,6 +4827,38 @@ export interface WordReviewEditorProps {
3905
4827
  * Capability id: `shortcut.last-edit`.
3906
4828
  */
3907
4829
  onLastEditRequested?: (context: ShortcutDelegationContext) => void;
4830
+ /**
4831
+ * design-close-chrome Phase 2 — density contract (designsystem §4.2).
4832
+ *
4833
+ * Controls the global `data-density` attribute that drives the
4834
+ * `--space-density-multiplier` cascade in `tokens.css`. When set,
4835
+ * the editor calls `useDensity().setDensity(value)` inside an effect;
4836
+ * when omitted, the hook reads the user's persisted preference from
4837
+ * `localStorage["wre.density"]` (defaulting to `"standard"`).
4838
+ *
4839
+ * @experimental The set of values (`"compact" | "standard" | "comfortable"`)
4840
+ * is stable; the effect-driven attribute write may move into a
4841
+ * theme-provider context in a future major.
4842
+ */
4843
+ density?: "compact" | "standard" | "comfortable";
4844
+ /**
4845
+ * design-close-chrome Phase 4 / R9 — host-supplied selection-tool
4846
+ * registry entries. Each entry is merged with the default
4847
+ * `SELECTION_TOOL_REGISTRY` via `resolveSelectionToolRegistry` (host
4848
+ * wins on id collision, merged list is precedence-sorted). Low-
4849
+ * precedence host entries (precedence < 10) can shadow the default
4850
+ * `suggestion-review` slot — useful for integrating a bespoke review
4851
+ * surface while keeping the remaining defaults.
4852
+ *
4853
+ * The entry's `id` must be a known `SelectionToolKind`; widening the
4854
+ * kind union to accept host render functions is coordinated with
4855
+ * Lane 8 (API ergonomics) and not part of this slice.
4856
+ *
4857
+ * @experimental
4858
+ */
4859
+ customSelectionTools?: ReadonlyArray<
4860
+ import("../ui/headless/chrome-registry").SelectionToolRegistryEntry
4861
+ >;
3908
4862
  }
3909
4863
 
3910
4864
  /**
@@ -4029,10 +4983,21 @@ export interface ResolveMetadataConflictInput {
4029
4983
  */
4030
4984
  export class EditorApiError extends Error {
4031
4985
  readonly code: string;
4032
- constructor(params: { code: string; message?: string }) {
4986
+ /**
4987
+ * v2.0.0 dual-error composite. Always populated when the editor itself
4988
+ * throws. Downstream code that re-throws `EditorApiError` (e.g. test
4989
+ * harnesses) may set this to `undefined`.
4990
+ */
4991
+ readonly diagnostic?: EditorDiagnostic;
4992
+ constructor(params: {
4993
+ code: string;
4994
+ message?: string;
4995
+ diagnostic?: EditorDiagnostic;
4996
+ }) {
4033
4997
  super(params.message ?? `EditorApiError: ${params.code}`);
4034
4998
  this.name = "EditorApiError";
4035
4999
  this.code = params.code;
5000
+ this.diagnostic = params.diagnostic;
4036
5001
  }
4037
5002
  }
4038
5003
 
@@ -4045,11 +5010,14 @@ export class EditorApiError extends Error {
4045
5010
  * Follows the fail-closed policy in collab-master-plan §1.6.
4046
5011
  */
4047
5012
  export class MetadataResolverMissingError extends Error {
4048
- constructor() {
5013
+ /** v2.0.0 dual-error composite (code `api.metadata_resolver_missing`). */
5014
+ readonly diagnostic?: EditorDiagnostic;
5015
+ constructor(diagnostic?: EditorDiagnostic) {
4049
5016
  super(
4050
5017
  "setMetadataPersistenceMode('external') requires a resolver — call " +
4051
5018
  "setScopeMetadataResolver(...) first.",
4052
5019
  );
4053
5020
  this.name = "MetadataResolverMissingError";
5021
+ this.diagnostic = diagnostic;
4054
5022
  }
4055
5023
  }