Datasets:
Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/ip-bbb-aaa-t1-b/environment/app/contract.docx +3 -0
- tasks/ip-bbb-aaa-t1-b/environment/app/grounding/Side B Commercial Context - Digital License Agreement.pdf +3 -0
- tasks/ip-bbb-aaa-t1-b/environment/app/grounding/Side B Playbook - Digital Content License (BBB Interactive) (3) (2).docx +3 -0
- tasks/ip-bbb-aaa-t1-b/tests/baseline/contract.docx +3 -0
- tasks/ip-bbb-aaa-t1-e/environment/app/contract.docx +3 -0
- tasks/ip-bbb-aaa-t1-e/environment/app/grounding/Side B Commercial Context - Digital License Agreement.pdf +3 -0
- tasks/ip-bbb-aaa-t1-e/environment/app/grounding/Side B Playbook - Digital Content License (BBB Interactive) (3) (2).docx +3 -0
- tasks/ip-bbb-aaa-t1-e/tests/baseline/contract.docx +3 -0
- tasks/ip-bbb-aaa-t2-c/environment/app/contract.docx +3 -0
- tasks/ip-bbb-aaa-t2-c/environment/app/grounding/Side A Commercial Context - Digital License Agreement.pdf +3 -0
- tasks/ip-bbb-aaa-t2-c/environment/app/grounding/Side A Playbook - Digital Content IP License (1) (1).docx +3 -0
- tasks/ip-bbb-aaa-t2-c/tests/baseline/contract.docx +3 -0
- tasks/ip-bbb-aaa-t2-d/environment/app/contract.docx +3 -0
- tasks/ip-bbb-aaa-t2-d/environment/app/grounding/Side A Commercial Context - Digital License Agreement.pdf +3 -0
- tasks/ip-bbb-aaa-t2-d/environment/app/grounding/Side A Playbook - Digital Content IP License (1) (1).docx +3 -0
- tasks/ip-bbb-aaa-t2-d/tests/baseline/contract.docx +3 -0
- tasks/ip-darkside-imperial-t1-a/environment/app/contract.docx +3 -0
- tasks/ip-darkside-imperial-t1-a/environment/app/grounding/Commercial_Context_Side_A.docx.pdf +3 -0
- tasks/ip-darkside-imperial-t1-a/environment/app/grounding/Darkside PLAYBOOK.docx +3 -0
- tasks/ip-darkside-imperial-t1-a/tests/baseline/contract.docx +3 -0
- tasks/ip-inventor-boardgame-t1-a/environment/app/contract.docx +3 -0
- tasks/ip-inventor-boardgame-t1-a/environment/app/grounding/Invention Option Agreement - Side B Commercial Context.v2.pdf +3 -0
- tasks/ip-inventor-boardgame-t1-a/tests/baseline/contract.docx +3 -0
- tasks/ip-sentry-calloway-t1-a/environment/app/contract.docx +3 -0
- tasks/ip-sentry-calloway-t1-a/environment/app/grounding/Commercial Context - Side A - Sentry Aerial Systems.docx.pdf +3 -0
- tasks/ip-sentry-calloway-t1-a/environment/app/grounding/Sentry Aerial Systems Multi-Use Contract Playbook.docx +3 -0
- tasks/ip-sentry-calloway-t1-a/tests/baseline/contract.docx +3 -0
- tasks/ip-whithill-hartsong-t1-a/environment/Dockerfile +23 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/SKILL.md +244 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/references/anchors.md +103 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/add_comment.py +167 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions-0.1.5.dist-info/INSTALLER +1 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions-0.1.5.dist-info/METADATA +91 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions-0.1.5.dist-info/RECORD +13 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions-0.1.5.dist-info/REQUESTED +0 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions-0.1.5.dist-info/WHEEL +4 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions-0.1.5.dist-info/licenses/LICENSE +21 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/VENDORED.md +27 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/__init__.py +30 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/_helpers.py +98 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/document.py +229 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/oxml.py +154 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/paragraph.py +654 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/revision.py +254 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/run.py +129 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/mark_reserved.py +82 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/propose_edits.py +164 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/read_document.py +51 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/redline_engine/__init__.py +0 -0
- tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/redline_engine/anchoring.py +271 -0
tasks/ip-bbb-aaa-t1-b/environment/app/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:048eda3d993fffa4cb846d5f898aaffcc1d4f3cdd9aac29f638ae6d75eabfa64
|
| 3 |
+
size 25373
|
tasks/ip-bbb-aaa-t1-b/environment/app/grounding/Side B Commercial Context - Digital License Agreement.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b2ac630d2ae5963035e7f6d81d9b77da36c7353422b5e61e1f0a6dbfa75638ba
|
| 3 |
+
size 19026
|
tasks/ip-bbb-aaa-t1-b/environment/app/grounding/Side B Playbook - Digital Content License (BBB Interactive) (3) (2).docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9cad620c9b1b048e39a9e0bab44df583a0ea181c64d9b480dd41e3216aa6188e
|
| 3 |
+
size 30917
|
tasks/ip-bbb-aaa-t1-b/tests/baseline/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:048eda3d993fffa4cb846d5f898aaffcc1d4f3cdd9aac29f638ae6d75eabfa64
|
| 3 |
+
size 25373
|
tasks/ip-bbb-aaa-t1-e/environment/app/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:048eda3d993fffa4cb846d5f898aaffcc1d4f3cdd9aac29f638ae6d75eabfa64
|
| 3 |
+
size 25373
|
tasks/ip-bbb-aaa-t1-e/environment/app/grounding/Side B Commercial Context - Digital License Agreement.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b2ac630d2ae5963035e7f6d81d9b77da36c7353422b5e61e1f0a6dbfa75638ba
|
| 3 |
+
size 19026
|
tasks/ip-bbb-aaa-t1-e/environment/app/grounding/Side B Playbook - Digital Content License (BBB Interactive) (3) (2).docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9cad620c9b1b048e39a9e0bab44df583a0ea181c64d9b480dd41e3216aa6188e
|
| 3 |
+
size 30917
|
tasks/ip-bbb-aaa-t1-e/tests/baseline/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:048eda3d993fffa4cb846d5f898aaffcc1d4f3cdd9aac29f638ae6d75eabfa64
|
| 3 |
+
size 25373
|
tasks/ip-bbb-aaa-t2-c/environment/app/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8a509851d62997312e5a30944a0d346efa6832129011a4c40ad02641ddc88c54
|
| 3 |
+
size 33223
|
tasks/ip-bbb-aaa-t2-c/environment/app/grounding/Side A Commercial Context - Digital License Agreement.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f64bdc4fb6f8fdcd9087299937d7e14c56b8b867556e01a3fe0e7cec4bfb13cc
|
| 3 |
+
size 18660
|
tasks/ip-bbb-aaa-t2-c/environment/app/grounding/Side A Playbook - Digital Content IP License (1) (1).docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:adc11b9b4c0cb42a522959f3e057569bc85a534156bcd57882c2af9a40ea2a70
|
| 3 |
+
size 45732
|
tasks/ip-bbb-aaa-t2-c/tests/baseline/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8a509851d62997312e5a30944a0d346efa6832129011a4c40ad02641ddc88c54
|
| 3 |
+
size 33223
|
tasks/ip-bbb-aaa-t2-d/environment/app/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dae14f7e046a004cb7df8e32b4636a3c00fcc25e2ab1f1cc2d9d7ac7d7341495
|
| 3 |
+
size 37959
|
tasks/ip-bbb-aaa-t2-d/environment/app/grounding/Side A Commercial Context - Digital License Agreement.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f64bdc4fb6f8fdcd9087299937d7e14c56b8b867556e01a3fe0e7cec4bfb13cc
|
| 3 |
+
size 18660
|
tasks/ip-bbb-aaa-t2-d/environment/app/grounding/Side A Playbook - Digital Content IP License (1) (1).docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:adc11b9b4c0cb42a522959f3e057569bc85a534156bcd57882c2af9a40ea2a70
|
| 3 |
+
size 45732
|
tasks/ip-bbb-aaa-t2-d/tests/baseline/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dae14f7e046a004cb7df8e32b4636a3c00fcc25e2ab1f1cc2d9d7ac7d7341495
|
| 3 |
+
size 37959
|
tasks/ip-darkside-imperial-t1-a/environment/app/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2cbe1e8783f15ba84b2e8767d315ca07b693238ffc4da42e979921eb6cdb72ed
|
| 3 |
+
size 22600
|
tasks/ip-darkside-imperial-t1-a/environment/app/grounding/Commercial_Context_Side_A.docx.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bb998c2912df2a8c13aac9cf55f5ea42817c4ebf50098ec095c72f1d5a096e33
|
| 3 |
+
size 92533
|
tasks/ip-darkside-imperial-t1-a/environment/app/grounding/Darkside PLAYBOOK.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cb363d868049a3f07fa345e7c700eb6107aa5f48af4d140608e95041e5fc9c5c
|
| 3 |
+
size 39578
|
tasks/ip-darkside-imperial-t1-a/tests/baseline/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2cbe1e8783f15ba84b2e8767d315ca07b693238ffc4da42e979921eb6cdb72ed
|
| 3 |
+
size 22600
|
tasks/ip-inventor-boardgame-t1-a/environment/app/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5181aa56f8d3fc3c541f4a9178252c980a9a460e09374a23995eb868a84e31c0
|
| 3 |
+
size 11828
|
tasks/ip-inventor-boardgame-t1-a/environment/app/grounding/Invention Option Agreement - Side B Commercial Context.v2.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a6a94628a57d92afaeb04515da4784bff6c97456bf8c60fb5d29e1ec806d8828
|
| 3 |
+
size 18648
|
tasks/ip-inventor-boardgame-t1-a/tests/baseline/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5181aa56f8d3fc3c541f4a9178252c980a9a460e09374a23995eb868a84e31c0
|
| 3 |
+
size 11828
|
tasks/ip-sentry-calloway-t1-a/environment/app/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:30ddc65de7e7140d2b5827cb13e628a5d526bd6134923356bee8c8a9ab204c9d
|
| 3 |
+
size 26527
|
tasks/ip-sentry-calloway-t1-a/environment/app/grounding/Commercial Context - Side A - Sentry Aerial Systems.docx.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:03cac4199735797454e7029c4dff38402bdc3ed1acbfa720bc209f67b6bf6c0f
|
| 3 |
+
size 69700
|
tasks/ip-sentry-calloway-t1-a/environment/app/grounding/Sentry Aerial Systems Multi-Use Contract Playbook.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eb58ef595d16d5dcc1d17365b2a8dd6c46f90815ab43fccef19f696c0be5a0ab
|
| 3 |
+
size 100863
|
tasks/ip-sentry-calloway-t1-a/tests/baseline/contract.docx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:30ddc65de7e7140d2b5827cb13e628a5d526bd6134923356bee8c8a9ab204c9d
|
| 3 |
+
size 26527
|
tasks/ip-whithill-hartsong-t1-a/environment/Dockerfile
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
|
| 3 |
+
# Basic utilities agent installers commonly need (claude-code, codex, opencode).
|
| 4 |
+
# poppler-utils provides pdftotext: the grounding documents (playbook, commercial context) are
|
| 5 |
+
# shipped in their original PDF / Word form, and the agent has to read them itself.
|
| 6 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 7 |
+
ca-certificates curl git unzip poppler-utils \
|
| 8 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 9 |
+
|
| 10 |
+
# Skill + verifier dependencies. litellm is for the verifier's judge call;
|
| 11 |
+
# the docx stack is shared by the skill scripts and the verifier; pypdf is a
|
| 12 |
+
# pure-Python fallback reader for the PDF grounding documents.
|
| 13 |
+
RUN pip install --no-cache-dir \
|
| 14 |
+
"python-docx==1.2.0" "docx-revisions>=0.1.5" "lxml>=5.0" "litellm>=1.83" "pypdf>=5.0"
|
| 15 |
+
|
| 16 |
+
# The contract-redliner skill (SKILL.md + scripts + vendored engine).
|
| 17 |
+
COPY skills/ /skills/
|
| 18 |
+
|
| 19 |
+
# Task documents: the contract to redline + grounding materials.
|
| 20 |
+
COPY app/ /app/
|
| 21 |
+
RUN python -c "import zipfile; zipfile.ZipFile('/app/contract.docx').testzip()" # fails on an LFS pointer file
|
| 22 |
+
|
| 23 |
+
WORKDIR /app
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/SKILL.md
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: contract-redliner
|
| 3 |
+
description: Redline Word (.docx) contracts with native tracked changes and margin comments, the way an attorney works in Word's Review pane. Use when asked to redline, mark up, revise, or respond to a contract or other .docx legal document — every edit must be a real tracked change (insertion/deletion) with a rationale comment, applied via the bundled scripts, never by rewriting the file.
|
| 4 |
+
compatibility: Requires Python 3.10+ with python-docx==1.2.0, docx-revisions, and lxml installed.
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
# Contract Redliner
|
| 8 |
+
|
| 9 |
+
Redline a `.docx` contract with real Word tracked changes (`<w:ins>`/`<w:del>`)
|
| 10 |
+
and threaded margin comments. The deliverable is the same file, edited in
|
| 11 |
+
place, that opens cleanly in Microsoft Word's Review pane.
|
| 12 |
+
|
| 13 |
+
Never edit the `.docx` by other means (unzipping it, rewriting XML, or
|
| 14 |
+
regenerating the file) — that destroys tracked-change attribution. All edits
|
| 15 |
+
go through the scripts below. Always pass the same `--author` string on every
|
| 16 |
+
call in a session — it is the name that appears in Word's Review pane and how
|
| 17 |
+
your work is attributed.
|
| 18 |
+
|
| 19 |
+
## Scripts
|
| 20 |
+
|
| 21 |
+
1. **Read the document:**
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
python scripts/read_document.py CONTRACT.docx
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
Prints the contract as Markdown. Every paragraph has an ID like `[p-027]`,
|
| 28 |
+
assigned in reading order for the current view and stable while you apply a
|
| 29 |
+
batch of edits from one read. The IDs are **positional**, though: adding a new
|
| 30 |
+
paragraph with `insert_paragraph_after` shifts the ID of every paragraph after
|
| 31 |
+
it on the *next* `read_document.py`. So if a later command targets a paragraph
|
| 32 |
+
by id after you've inserted one, re-run `read_document.py` first and use the
|
| 33 |
+
fresh id. Existing tracked changes are shown **inline** in the body —
|
| 34 |
+
`++inserted++` for insertions, `~~struck~~` for deletions — so you read the
|
| 35 |
+
document exactly as the reviewer will; paragraphs carrying changes/comments
|
| 36 |
+
are also flagged `{REVS,CMTS}`, and an appendix lists each existing comment
|
| 37 |
+
(`cmt-N`, with author and thread parent) and tracked change (`rev-N`, with
|
| 38 |
+
author and text). On a response turn you can anchor to text the counterparty
|
| 39 |
+
inserted — copy it without the `++…++` markers (see `references/anchors.md`).
|
| 40 |
+
|
| 41 |
+
The same script reads any other `.docx` you are given (a playbook, a deal
|
| 42 |
+
memo): the paragraph IDs it prints for those are for your reading only. For
|
| 43 |
+
a `.pdf`, use `pdftotext -layout FILE -` (or `pypdf`); both are installed.
|
| 44 |
+
|
| 45 |
+
2. **Apply a batch of tracked changes:**
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
python scripts/propose_edits.py CONTRACT.docx edits.json --author "Jane (AgentCo Legal)"
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
`edits.json` is an array of edit objects (full schema and anchor rules:
|
| 52 |
+
[references/anchors.md](references/anchors.md)):
|
| 53 |
+
|
| 54 |
+
```json
|
| 55 |
+
[
|
| 56 |
+
{
|
| 57 |
+
"op": "replace",
|
| 58 |
+
"anchor": {"paragraph_id": "p-032", "text": "thirty (30) days’ written notice"},
|
| 59 |
+
"new_text": "ten (10) business days’ written notice",
|
| 60 |
+
"comment": "We shortened the notice window because our subprocessors ship on faster cycles than 30 days."
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"op": "delete",
|
| 64 |
+
"anchor": {"paragraph_id": "p-033", "text": "(i) will render accurate and reliable results,"},
|
| 65 |
+
"comment": "We can't warrant that AI outputs are accurate in every case — a breach claim would attach to any imperfect output."
|
| 66 |
+
}
|
| 67 |
+
]
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
Ops: `replace`, `delete`, `insert_after`, `insert_paragraph_after`
|
| 71 |
+
(`new_text` required for all but `delete`). `comment` is required on every
|
| 72 |
+
edit. Results print as JSON per edit; exit code 1 means at least one edit
|
| 73 |
+
failed.
|
| 74 |
+
|
| 75 |
+
- `insert_after` inserts `new_text` **inline**, within the anchor paragraph.
|
| 76 |
+
- `insert_paragraph_after` adds a **new standalone paragraph** (a real new,
|
| 77 |
+
fully-tracked `<w:p>`) immediately after the anchor paragraph. Use it — not
|
| 78 |
+
`insert_after` — whenever a redline must add a **new numbered section or
|
| 79 |
+
clause**; `insert_after` cannot create a new paragraph and would leave the
|
| 80 |
+
clause as a run-on inside the anchor paragraph. Fill the placeholders below
|
| 81 |
+
with the actual section number, title, and clause text your task calls for:
|
| 82 |
+
|
| 83 |
+
```json
|
| 84 |
+
{
|
| 85 |
+
"op": "insert_paragraph_after",
|
| 86 |
+
"anchor": {"paragraph_id": "p-018", "text": "<a unique phrase ending the section this should follow>"},
|
| 87 |
+
"new_text": "<N.N> <New Section Title>. <The full text of the clause you are adding.>",
|
| 88 |
+
"comment": "<your rationale for adding this section>"
|
| 89 |
+
}
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
3. **If an edit fails, fix only that edit and resubmit it.** A failed anchor
|
| 93 |
+
returns `status: "anchor_failed"` with the reason — `text_not_found` (your
|
| 94 |
+
text isn't a verbatim substring of that paragraph) or `ambiguous` (it
|
| 95 |
+
matches more than once; candidates are listed). Re-read the paragraph in
|
| 96 |
+
the `read_document.py` output, tighten the anchor (add `paragraph_id`,
|
| 97 |
+
`context_before`/`context_after`, or `occurrence`), and resubmit a batch
|
| 98 |
+
containing only the failed edits — successful ones are already saved in
|
| 99 |
+
the file.
|
| 100 |
+
|
| 101 |
+
> **`propose_edits.py` applies and saves the batch the moment it runs — it is
|
| 102 |
+
> not idempotent.** Never re-run a batch that already succeeded (even if its
|
| 103 |
+
> output scrolled off or a pipe broke): re-running double-applies edits — an
|
| 104 |
+
> `insert_after`/`replace` whose new text contains its own anchor will
|
| 105 |
+
> duplicate the text and its comment — and edits that already changed a
|
| 106 |
+
> paragraph now return `text_not_found`, a misleading "everything failed"
|
| 107 |
+
> signal. After any run, re-run `read_document.py` and submit **only** the
|
| 108 |
+
> still-needed edits, anchored on the current text.
|
| 109 |
+
|
| 110 |
+
4. **Standalone comments and thread replies:**
|
| 111 |
+
|
| 112 |
+
```bash
|
| 113 |
+
# New thread on a paragraph
|
| 114 |
+
python scripts/add_comment.py CONTRACT.docx --paragraph-id p-035 \
|
| 115 |
+
--comment "Can you confirm whether any Agents are offshore?" --author "Jane (AgentCo Legal)"
|
| 116 |
+
|
| 117 |
+
# Reply to existing comment cmt-24 (use the paragraph the thread sits on)
|
| 118 |
+
python scripts/add_comment.py CONTRACT.docx --paragraph-id p-035 --reply-to 24 \
|
| 119 |
+
--comment "Agreed — we accepted this change." --author "Jane (AgentCo Legal)"
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
**Comments with a `$`, quotes, or newlines: use `--comment-file`, not
|
| 123 |
+
`--comment`.** A double-quoted `--comment "…$44,000…"` is mangled by the
|
| 124 |
+
shell (bash expands `$2`), corrupting the saved comment. Write the text to a
|
| 125 |
+
file (or pipe via `-`) so it's read verbatim:
|
| 126 |
+
|
| 127 |
+
```bash
|
| 128 |
+
printf '%s' 'The fee cap is $44,000; anything above needs written consent.' > /tmp/c.txt
|
| 129 |
+
python scripts/add_comment.py CONTRACT.docx --paragraph-id p-035 \
|
| 130 |
+
--comment-file /tmp/c.txt --author "Jane (AgentCo Legal)"
|
| 131 |
+
```
|
| 132 |
+
(Per-edit `comment` fields inside the `propose_edits.py` JSON are already safe
|
| 133 |
+
— they never transit the shell.)
|
| 134 |
+
|
| 135 |
+
4b. **Internal escalations** — flag an issue for your own side's approval instead
|
| 136 |
+
of redlining it:
|
| 137 |
+
|
| 138 |
+
```bash
|
| 139 |
+
printf '%s' "We can't take a position on the marketplace exclusivity without sign-off." > /tmp/esc.txt
|
| 140 |
+
python scripts/add_comment.py CONTRACT.docx --paragraph-id p-041 --escalation \
|
| 141 |
+
--approvers "Talent Agent, Legal Counsel" \
|
| 142 |
+
--comment-file /tmp/esc.txt --author "Jane (AgentCo Legal)"
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
`--escalation` marks the comment as an **internal** note rather than a
|
| 146 |
+
counterparty-facing one: the saved text begins `ESCALATE:` and, with
|
| 147 |
+
`--approvers`, ends `Approval required from: <roles>.` Use it when a position
|
| 148 |
+
needs sign-off before it goes to the other side — and leave the clause itself
|
| 149 |
+
unredlined unless your instructions say otherwise. Name the issue, the clause,
|
| 150 |
+
and the approver(s) in the text.
|
| 151 |
+
|
| 152 |
+
`--escalation` cannot be combined with `--reply-to`: a reply sits on a thread
|
| 153 |
+
the counterparty reads, so it isn't an internal note. Never type `ESCALATE:`
|
| 154 |
+
into the contract body or into an edit's rationale comment — the first is
|
| 155 |
+
contract text, the second is counterparty-facing.
|
| 156 |
+
|
| 157 |
+
5. **Whole-section removal** (preserves downstream numbering):
|
| 158 |
+
|
| 159 |
+
```bash
|
| 160 |
+
python scripts/mark_reserved.py CONTRACT.docx --start p-036 --end p-037 \
|
| 161 |
+
--comment "We removed this section because ..." --author "Jane (AgentCo Legal)"
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
This tracked-deletes the body text of every paragraph in the range — including
|
| 165 |
+
an inline-typed section number/title if the number is part of the paragraph's
|
| 166 |
+
own text — and tracked-inserts "Reserved." into the first one. Auto-numbered
|
| 167 |
+
(list) numbering is preserved, so downstream sections don't renumber. It leaves
|
| 168 |
+
any tracked changes the counterparty already made inside the range **in place**;
|
| 169 |
+
reject or accept those separately with `propose_edits.py`.
|
| 170 |
+
|
| 171 |
+
6. **Verify before finishing.** Re-run `read_document.py` and confirm the
|
| 172 |
+
appendix shows your tracked changes under your author name and your
|
| 173 |
+
comments where you expect them. The saved file is the deliverable.
|
| 174 |
+
|
| 175 |
+
## Known limitation
|
| 176 |
+
|
| 177 |
+
`insert_after` shows the anchor text in both the deletion and insertion halves
|
| 178 |
+
of the tracked change (it is implemented as replace anchor → anchor+new text).
|
| 179 |
+
This is cosmetically noisy but legally equivalent; prefer `replace` with the
|
| 180 |
+
full revised phrase when inserting mid-sentence. `insert_after` also inserts
|
| 181 |
+
**inline** and cannot add a new paragraph — to add a new numbered section or
|
| 182 |
+
clause, use `insert_paragraph_after`.
|
| 183 |
+
|
| 184 |
+
## Editing text the other side has already tracked-changed (response turns)
|
| 185 |
+
|
| 186 |
+
On a response turn the document already carries the counterparty's tracked
|
| 187 |
+
changes. In the read view these appear inline as `~~their deletion~~` /
|
| 188 |
+
`++their insertion++`. A word or number can be **part base text and part their
|
| 189 |
+
pending edit** — e.g. (illustrative figures) the read view shows `$++4++4,000`,
|
| 190 |
+
meaning the base is `$4,000` and the other side inserted a `4` to propose
|
| 191 |
+
`$44,000`.
|
| 192 |
+
|
| 193 |
+
A single `replace`/`delete` op **cannot span across — or fully contain — one of
|
| 194 |
+
their tracked-change markers**, whether an insertion (`++…++`) or a deletion
|
| 195 |
+
(`~~…~~`): the anchored text mixes settled base with their unaccepted edit, which
|
| 196 |
+
are different revision layers. Attempting it returns
|
| 197 |
+
`runtime_error: ... across a revision boundary`; nothing is applied. This is
|
| 198 |
+
expected — decide, per revision layer, and apply one op each:
|
| 199 |
+
|
| 200 |
+
1. **Accept or reject their pending edit EXPLICITLY — do not just leave it.**
|
| 201 |
+
Leaving a counterparty tracked change untouched reads as "not reviewed," NOT as
|
| 202 |
+
acceptance. Each counterparty change has a stable `rev-N` id (shown in the
|
| 203 |
+
"Existing tracked changes" appendix of the read view). Resolve the ones you've
|
| 204 |
+
decided on with an `accept` / `reject` op, passing the `rev-N`:
|
| 205 |
+
|
| 206 |
+
```bash
|
| 207 |
+
python scripts/propose_edits.py CONTRACT.docx - --author "Jane (AgentCo Legal)" <<'JSON'
|
| 208 |
+
[{"op": "accept", "revision_ids": [12], "comment": "Agreed — acceptable as drafted."}]
|
| 209 |
+
JSON
|
| 210 |
+
```
|
| 211 |
+
|
| 212 |
+
- **accept** an insertion keeps their text as settled text; **accept** a deletion
|
| 213 |
+
finalizes it. Use `accept` when you AGREE with their change.
|
| 214 |
+
- **To REJECT or counter their change, leave a VISIBLE tracked change of your own** —
|
| 215 |
+
strike their inserted text with a `delete` op anchored exactly on it (renders
|
| 216 |
+
`~~their text~~`), or `replace` it with your own language. A bare `reject` op
|
| 217 |
+
removes their change with NO visible tracked mark of your own; prefer a visible
|
| 218 |
+
strike so your rejection is recorded as your own tracked change. (`reject` on a
|
| 219 |
+
counterparty deletion simply restores the struck text.)
|
| 220 |
+
- A counterparty **replace** is a paired strike + insertion — TWO `rev-N`; `accept`
|
| 221 |
+
BOTH together to adopt it, or strike / `replace` their inserted text visibly to reject it.
|
| 222 |
+
- `comment` is optional here. `accept`/`reject` target only the OTHER side's
|
| 223 |
+
`rev-N`; use `replace`/`delete`/`insert_after` to make YOUR OWN edits.
|
| 224 |
+
2. **To COUNTER** (reject theirs and propose your own), strike their inserted text with
|
| 225 |
+
a `delete` op anchored exactly on it (a VISIBLE `~~…~~`) — or `replace` it with your
|
| 226 |
+
language — then `replace`/`insert_after` on the surrounding base text as needed.
|
| 227 |
+
Prefer striking their text visibly over a bare `reject` op, so your counter is a
|
| 228 |
+
recorded tracked change of your own.
|
| 229 |
+
3. **Edit surrounding base text in its own op.** A single `replace`/`delete` op
|
| 230 |
+
**cannot span across — or fully contain — one of their tracked-change markers**
|
| 231 |
+
(`++…++` / `~~…~~`): the anchored text would mix settled base with their
|
| 232 |
+
unaccepted edit (different revision layers) → `runtime_error: ... across a
|
| 233 |
+
revision boundary`, and nothing is applied. Anchor only the base portion.
|
| 234 |
+
|
| 235 |
+
Example (illustrative figures) — they proposed `$4,000` → `$44,000` (read view
|
| 236 |
+
`$++4++4,000`) and you want `$8,000`: (1) `reject` the `rev-N` for their inserted
|
| 237 |
+
`4`, then (2) `replace` `4,000` → `8,000`. Accepting all revisions then yields
|
| 238 |
+
`$8,000`, and the redline reads cleanly as your rejection plus your counter.
|
| 239 |
+
|
| 240 |
+
> Do **not** leave a counterparty change unresolved when your task is to accept,
|
| 241 |
+
> reject, or counter it. Accepting-by-inaction is NOT acceptance — an unresolved
|
| 242 |
+
> change reads as "not reviewed," and leaving a leftover inserted fragment next to
|
| 243 |
+
> your own edit can fuse into nonsense on accept-all. Resolve every counterparty
|
| 244 |
+
> change you act on.
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/references/anchors.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Edit schema and anchor reference
|
| 2 |
+
|
| 3 |
+
## Edit object schema (`propose_edits.py`)
|
| 4 |
+
|
| 5 |
+
```json
|
| 6 |
+
{
|
| 7 |
+
"op": "replace" | "delete" | "insert_after" | "insert_paragraph_after",
|
| 8 |
+
"anchor": {
|
| 9 |
+
"paragraph_id": "p-027",
|
| 10 |
+
"text": "verbatim substring of the paragraph",
|
| 11 |
+
"context_before": "optional text immediately before the anchor",
|
| 12 |
+
"context_after": "optional text immediately after the anchor",
|
| 13 |
+
"occurrence": 1
|
| 14 |
+
},
|
| 15 |
+
"new_text": "required for replace / insert_after / insert_paragraph_after",
|
| 16 |
+
"comment": "required — the rationale margin comment"
|
| 17 |
+
}
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
| op | effect | new_text |
|
| 21 |
+
|---|---|---|
|
| 22 |
+
| `replace` | tracked-delete `anchor.text`, tracked-insert `new_text` in its place | required |
|
| 23 |
+
| `delete` | tracked-delete `anchor.text` | ignored |
|
| 24 |
+
| `insert_after` | tracked-insert `new_text` **inline**, immediately after `anchor.text` (same paragraph) | required |
|
| 25 |
+
| `insert_paragraph_after` | add a **new standalone paragraph** (a real, fully-tracked `<w:p>`) right after the anchor paragraph — for a new numbered section/clause | required |
|
| 26 |
+
|
| 27 |
+
> The `comment` (and `new_text`) here are read from the edits **JSON file**, so
|
| 28 |
+
> dollar amounts / quotes / newlines are safe. Standalone comments via
|
| 29 |
+
> `add_comment.py` must use **`--comment-file`** for such text — a shell
|
| 30 |
+
> `--comment "…$44,000…"` is mangled by bash before the script sees it.
|
| 31 |
+
|
| 32 |
+
## Anchor resolution rules
|
| 33 |
+
|
| 34 |
+
- **`text` is required** and must be a verbatim substring of the target
|
| 35 |
+
paragraph's current text. Copy it from the `read_document.py` output, not
|
| 36 |
+
from memory.
|
| 37 |
+
- **Always supply `paragraph_id`** (the `p-NNN` from the document view). It
|
| 38 |
+
restricts the search to one paragraph, which avoids nearly all ambiguity.
|
| 39 |
+
- Matching is **normalized on both sides**, so these differences never cause a
|
| 40 |
+
mismatch: curly vs straight quotes (`’` ≡ `'`, `“”` ≡ `"`), en/em dashes vs
|
| 41 |
+
hyphens, non-breaking spaces, and runs of whitespace (any amount of
|
| 42 |
+
whitespace matches a single space).
|
| 43 |
+
- Anything else must match exactly — case, punctuation, spelling.
|
| 44 |
+
- **Anchor to the text as it currently reads, with prior insertions kept and
|
| 45 |
+
prior deletions removed.** On a response turn the document already contains the
|
| 46 |
+
counterparty's tracked changes; `read_document.py` shows them inline as
|
| 47 |
+
`++inserted++` and `~~struck~~`. You *can* anchor to text the counterparty
|
| 48 |
+
inserted — copy it **without** the `++…++` markers (they are not part of the
|
| 49 |
+
text). Ignore `~~struck~~` text entirely; it is already deleted and cannot be
|
| 50 |
+
anchored. Refining or striking counterparty-inserted wording (a nested edit) is
|
| 51 |
+
fully supported and shows up correctly in the reviewer's view.
|
| 52 |
+
- If a `replace`/`delete` reports `runtime_error … across a revision boundary`,
|
| 53 |
+
your span straddles **or fully contains** a prior tracked change (an insertion
|
| 54 |
+
or a deletion) — narrow the anchor so it sits entirely inside (or entirely
|
| 55 |
+
outside) that inserted/deleted run. To
|
| 56 |
+
change a value the counterparty has partially edited (e.g. read view
|
| 57 |
+
`$++4++4,000`, illustrative), split into two ops: one on their pending edit (a `delete`
|
| 58 |
+
anchored on their `++inserted++` text to reject it, or leave it to accept) and
|
| 59 |
+
one on the surrounding base text. See SKILL.md → "Editing text the other side
|
| 60 |
+
has already tracked-changed."
|
| 61 |
+
- If `text` appears more than once in the paragraph, disambiguate with either:
|
| 62 |
+
- `occurrence`: 1-indexed position among the matches (1 = first), or
|
| 63 |
+
- `context_before` / `context_after`: short verbatim snippets adjacent to
|
| 64 |
+
the intended match (whitespace at the boundary is forgiven).
|
| 65 |
+
|
| 66 |
+
## Failure modes and fixes
|
| 67 |
+
|
| 68 |
+
Every edit returns a JSON result. Statuses:
|
| 69 |
+
|
| 70 |
+
| status | meaning | fix |
|
| 71 |
+
|---|---|---|
|
| 72 |
+
| `ok` | applied; `comment_id` is the margin comment's id | — |
|
| 73 |
+
| `anchor_failed` / `text_not_found` | `text` is not a substring of that paragraph | Re-read the paragraph; copy the exact current text (it may already contain your earlier edits) |
|
| 74 |
+
| `anchor_failed` / `ambiguous` | matched multiple places; `candidates` lists paragraph ids | Add `paragraph_id`, then `occurrence` or context fields |
|
| 75 |
+
| `anchor_failed` / `paragraph_not_found` | bad `paragraph_id` | Use an id that appears in the current document view |
|
| 76 |
+
| `runtime_error` | the engine could not apply the edit | Read `error`; usually re-anchoring on a smaller span fixes it |
|
| 77 |
+
|
| 78 |
+
Two rules of thumb:
|
| 79 |
+
|
| 80 |
+
1. **After any successful batch, the paragraph text has changed.** If you need
|
| 81 |
+
a second edit in the same paragraph, re-run `read_document.py` first and
|
| 82 |
+
anchor on the *current* text.
|
| 83 |
+
2. **Resubmit only the failed edits.** `propose_edits.py` saves the batch the
|
| 84 |
+
moment it runs (it is **not idempotent**), so re-running a batch that already
|
| 85 |
+
succeeded double-applies each edit — and an `insert_after`/`replace` whose new
|
| 86 |
+
text contains its anchor duplicates the text. If a run's output was lost or
|
| 87 |
+
interrupted, re-read with `read_document.py` before resubmitting anything.
|
| 88 |
+
|
| 89 |
+
## Choosing good anchors
|
| 90 |
+
|
| 91 |
+
- Anchor on the **shortest span that is unique** within the paragraph —
|
| 92 |
+
usually 4–10 words. Whole-sentence anchors break when any word in the
|
| 93 |
+
sentence was already edited.
|
| 94 |
+
- For `replace`, anchor exactly the words being changed, not the surrounding
|
| 95 |
+
sentence. The tracked change then reads as a surgical word-level edit, which
|
| 96 |
+
is what reviewers expect.
|
| 97 |
+
- For `insert_after`, anchor the few words you want the insertion to follow
|
| 98 |
+
(commonly the end of a sentence including its period). It stays **inline** in
|
| 99 |
+
the anchor paragraph.
|
| 100 |
+
- For `insert_paragraph_after`, anchor any text in the paragraph the new section
|
| 101 |
+
should follow (e.g. the number of the preceding section). The new clause lands
|
| 102 |
+
as its own new paragraph — use this for a new numbered section, never
|
| 103 |
+
`insert_after` (which cannot create a paragraph).
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/add_comment.py
ADDED
|
@@ -0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 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Add a margin comment to a .docx contract, in place.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
# New standalone comment thread on a paragraph:
|
| 6 |
+
python add_comment.py CONTRACT.docx --paragraph-id p-014 \
|
| 7 |
+
--comment "Can you confirm the data residency requirement applies here?" \
|
| 8 |
+
--author "Jane (AgentCo Legal)"
|
| 9 |
+
|
| 10 |
+
# Threaded reply to an existing comment (cmt-N from read_document.py).
|
| 11 |
+
# --paragraph-id is the paragraph the parent comment sits on:
|
| 12 |
+
python add_comment.py CONTRACT.docx --paragraph-id p-014 --reply-to 3 \
|
| 13 |
+
--comment "Agreed — we accepted this change." \
|
| 14 |
+
--author "Jane (AgentCo Legal)"
|
| 15 |
+
|
| 16 |
+
Comment text: pass EITHER --comment "..." OR --comment-file PATH (use '-' for
|
| 17 |
+
stdin). Prefer --comment-file whenever the text contains a `$`, quotes, or
|
| 18 |
+
newlines — dollar amounts like "$250,000" get silently mangled by the shell
|
| 19 |
+
when passed as a double-quoted --comment argument (bash reads `$2` as a
|
| 20 |
+
positional parameter). --comment-file reads the text verbatim, never touching
|
| 21 |
+
the shell (the same reason propose_edits.py takes its edits from a JSON file).
|
| 22 |
+
|
| 23 |
+
# Internal escalation — an issue that needs your own side's approval before
|
| 24 |
+
# any position goes to the counterparty. Writes "ESCALATION: ..." for you:
|
| 25 |
+
python add_comment.py CONTRACT.docx --paragraph-id p-041 --escalation \
|
| 26 |
+
--approvers "Talent Agent, Legal Counsel" \
|
| 27 |
+
--comment-file /tmp/esc.txt --author "Jane (AgentCo Legal)"
|
| 28 |
+
|
| 29 |
+
Use standalone comments only to flag an issue for discussion without making an
|
| 30 |
+
edit (edits made via propose_edits.py already carry their own comment).
|
| 31 |
+
Prints a JSON result with the assigned comment id.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
from __future__ import annotations
|
| 35 |
+
|
| 36 |
+
import argparse
|
| 37 |
+
import json
|
| 38 |
+
import os
|
| 39 |
+
import sys
|
| 40 |
+
from dataclasses import asdict
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
|
| 43 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 44 |
+
|
| 45 |
+
from redline_engine.document import DocumentView # noqa: E402
|
| 46 |
+
from redline_engine.ops import add_standalone_comment # noqa: E402
|
| 47 |
+
|
| 48 |
+
DEFAULT_AUTHOR = "Counsel"
|
| 49 |
+
# esc2 — the task sets this via [environment.env] so the literal token matches the instructions the
|
| 50 |
+
# model was given ("ESCALATION:" for the comment-only design, "ESCALATE:" for redline-plus-comment).
|
| 51 |
+
ESCALATION_PREFIX = (os.environ.get("ESCALATION_PREFIX") or "ESCALATION:").strip()
|
| 52 |
+
# Either token is accepted as already-prefixed, so a model that types the other one is not
|
| 53 |
+
# double-prefixed and the grader still detects it.
|
| 54 |
+
_KNOWN_PREFIXES = ("ESCALATION:", "ESCALATE:")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _lock_docx(docx_path):
|
| 59 |
+
"""Exclusive cross-process lock for a .docx read-modify-write. opencode can fire parallel bash
|
| 60 |
+
calls, so two of these scripts may run at once on the same file; without serialization they collide
|
| 61 |
+
(duplicate comment ids, silently clobbered edits, or a corrupted zip). Hold an flock on a sidecar
|
| 62 |
+
lock file for the whole load->save; the returned handle keeps the lock until this process exits.
|
| 63 |
+
Returns None on platforms without fcntl (e.g. Windows) rather than failing."""
|
| 64 |
+
try:
|
| 65 |
+
import fcntl
|
| 66 |
+
except ImportError:
|
| 67 |
+
return None
|
| 68 |
+
from pathlib import Path as _P
|
| 69 |
+
f = open(str(_P(str(docx_path) + ".lock")), "w")
|
| 70 |
+
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
|
| 71 |
+
return f
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def main() -> int:
|
| 75 |
+
parser = argparse.ArgumentParser(
|
| 76 |
+
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
| 77 |
+
)
|
| 78 |
+
parser.add_argument("docx", help="path to the .docx file (edited in place)")
|
| 79 |
+
parser.add_argument("--paragraph-id", required=True, help="target paragraph, e.g. p-014")
|
| 80 |
+
parser.add_argument("--comment", default=None, help="comment text (inline)")
|
| 81 |
+
parser.add_argument(
|
| 82 |
+
"--comment-file",
|
| 83 |
+
default=None,
|
| 84 |
+
help="path to a file with the comment text, or '-' for stdin. Prefer this "
|
| 85 |
+
"for text with $, quotes, or newlines (avoids shell mangling).",
|
| 86 |
+
)
|
| 87 |
+
parser.add_argument(
|
| 88 |
+
"--reply-to",
|
| 89 |
+
type=int,
|
| 90 |
+
default=None,
|
| 91 |
+
help="existing comment id N (from cmt-N) to reply to instead of starting a new thread",
|
| 92 |
+
)
|
| 93 |
+
parser.add_argument(
|
| 94 |
+
"--escalation",
|
| 95 |
+
action="store_true",
|
| 96 |
+
help="mark this comment as an INTERNAL escalation to your own side: the saved text is prefixed "
|
| 97 |
+
"'ESCALATION:'. Use it for an issue that needs your side's approval before any position goes "
|
| 98 |
+
"to the counterparty, and leave the clause itself unredlined. Cannot be combined with "
|
| 99 |
+
"--reply-to.",
|
| 100 |
+
)
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"--approvers",
|
| 103 |
+
default=None,
|
| 104 |
+
help="comma-separated approver ROLES this escalation needs (e.g. \"Talent Agent, Legal "
|
| 105 |
+
"Counsel\"), appended as 'Approval required from: ...'. Only valid with --escalation.",
|
| 106 |
+
)
|
| 107 |
+
parser.add_argument("--author", default=DEFAULT_AUTHOR, help="comment author name")
|
| 108 |
+
args = parser.parse_args()
|
| 109 |
+
|
| 110 |
+
# Exactly one of --comment / --comment-file. --comment-file (or stdin) reads
|
| 111 |
+
# the text verbatim so dollar amounts / quotes / newlines never hit the shell.
|
| 112 |
+
if (args.comment is None) == (args.comment_file is None):
|
| 113 |
+
print("error: pass exactly one of --comment or --comment-file", file=sys.stderr)
|
| 114 |
+
return 2
|
| 115 |
+
if args.comment_file is not None:
|
| 116 |
+
comment_text = sys.stdin.read() if args.comment_file == "-" else Path(args.comment_file).read_text()
|
| 117 |
+
else:
|
| 118 |
+
comment_text = args.comment
|
| 119 |
+
|
| 120 |
+
if args.approvers and not args.escalation:
|
| 121 |
+
print("error: --approvers is only valid with --escalation", file=sys.stderr)
|
| 122 |
+
return 2
|
| 123 |
+
if args.escalation and args.reply_to is not None:
|
| 124 |
+
print(
|
| 125 |
+
"error: --escalation cannot be combined with --reply-to — an escalation is a standalone "
|
| 126 |
+
"INTERNAL note, and a reply sits on a thread the counterparty reads. Post the escalation "
|
| 127 |
+
"as its own comment on the paragraph the issue lives in.",
|
| 128 |
+
file=sys.stderr,
|
| 129 |
+
)
|
| 130 |
+
return 2
|
| 131 |
+
if args.escalation:
|
| 132 |
+
# The tool owns the prefix so the grader's detection is exact on the sanctioned path.
|
| 133 |
+
# Idempotent: an author who already typed the prefix doesn't get it twice.
|
| 134 |
+
body = " ".join(comment_text.split())
|
| 135 |
+
if not any(body.upper().startswith(t) for t in _KNOWN_PREFIXES):
|
| 136 |
+
body = f"{ESCALATION_PREFIX} {body}"
|
| 137 |
+
if args.approvers:
|
| 138 |
+
roles = ", ".join(x.strip() for x in args.approvers.split(",") if x.strip())
|
| 139 |
+
if roles and roles.lower() not in body.lower():
|
| 140 |
+
body = f"{body.rstrip('.')}. Approval required from: {roles}."
|
| 141 |
+
comment_text = body
|
| 142 |
+
|
| 143 |
+
path = Path(args.docx)
|
| 144 |
+
if not path.exists():
|
| 145 |
+
print(f"error: file not found: {path}", file=sys.stderr)
|
| 146 |
+
return 1
|
| 147 |
+
|
| 148 |
+
_docx_lock = _lock_docx(path) # noqa: F841 (held until process exit; serializes concurrent writers)
|
| 149 |
+
view = DocumentView.load(path)
|
| 150 |
+
res = add_standalone_comment(
|
| 151 |
+
view,
|
| 152 |
+
paragraph_id=args.paragraph_id,
|
| 153 |
+
comment=comment_text,
|
| 154 |
+
author=args.author,
|
| 155 |
+
reply_to_comment_id=args.reply_to,
|
| 156 |
+
)
|
| 157 |
+
view._docx.save(str(path)) # noqa: SLF001
|
| 158 |
+
|
| 159 |
+
out = {k: v for k, v in asdict(res).items() if v not in (None, [], "")}
|
| 160 |
+
if args.escalation:
|
| 161 |
+
out["escalation"] = True # echo it back so the caller can verify the prefix landed
|
| 162 |
+
print(json.dumps(out, indent=2))
|
| 163 |
+
return 0 if out.get("status") == "ok" else 1
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
if __name__ == "__main__":
|
| 167 |
+
sys.exit(main())
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions-0.1.5.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
uv
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions-0.1.5.dist-info/METADATA
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: docx-revisions
|
| 3 |
+
Version: 0.1.5
|
| 4 |
+
Summary: Track changes (revisions) support for python-docx: read, write and manipulate <w:ins> and <w:del> elements
|
| 5 |
+
Project-URL: Homepage, https://github.com/balalofernandez/docx-revisions
|
| 6 |
+
Project-URL: Documentation, https://balalofernandez.github.io/docx-revisions
|
| 7 |
+
Project-URL: Repository, https://github.com/balalofernandez/docx-revisions
|
| 8 |
+
License: MIT
|
| 9 |
+
License-File: LICENSE
|
| 10 |
+
Requires-Python: >=3.10
|
| 11 |
+
Requires-Dist: lxml>=4.9.0
|
| 12 |
+
Requires-Dist: python-docx>=1.1.0
|
| 13 |
+
Provides-Extra: dev
|
| 14 |
+
Requires-Dist: mkdocs-material>=9.0; extra == 'dev'
|
| 15 |
+
Requires-Dist: mkdocstrings[python]>=0.24; extra == 'dev'
|
| 16 |
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
| 17 |
+
Requires-Dist: ruff>=0.1; extra == 'dev'
|
| 18 |
+
Provides-Extra: examples
|
| 19 |
+
Requires-Dist: pydantic-ai>=1.51.0; extra == 'examples'
|
| 20 |
+
Description-Content-Type: text/markdown
|
| 21 |
+
|
| 22 |
+
# Python Tracked Changes Library - docx-revisions
|
| 23 |
+
|
| 24 |
+
<p align="center">
|
| 25 |
+
<a href="https://balalofernandez.github.io/docx-revisions" target="_blank"><img src="https://img.shields.io/badge/Docs-0066FF" alt="Documentation"></a>
|
| 26 |
+
<a href="https://github.com/balalofernandez/docx-revisions/actions/workflows/tests.yml"><img src="https://github.com/balalofernandez/docx-revisions/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>
|
| 27 |
+
<a href="https://github.com/balalofernandez/docx-revisions/actions/workflows/docs.yml"><img src="https://github.com/balalofernandez/docx-revisions/actions/workflows/docs.yml/badge.svg" alt="Docs"></a>
|
| 28 |
+
<a href="https://pypi.org/project/docx-revisions" target="_blank"><img src="https://img.shields.io/pypi/v/docx-revisions" alt="PyPI"></a>
|
| 29 |
+
<!-- <a href="https://pepy.tech/projects/docx-revisions"><img src="https://static.pepy.tech/badge/docx-revisions" alt="PyPI Downloads"></a> -->
|
| 30 |
+
</p>
|
| 31 |
+
|
| 32 |
+
**Read and write track changes in Word documents (.docx) with Python.** docx-revisions extends [python-docx](https://python-docx.readthedocs.io/) to support **document revision tracking**, **change tracking**, and **OOXML** revision markup (insertions `<w:ins>` and deletions `<w:del>`) so you can programmatically accept text, list revisions with author and date, and apply insertions, deletions, or replacements with full revision metadata.
|
| 33 |
+
|
| 34 |
+
Use it for **Microsoft Word**-compatible revision tracking: parse DOCX files with track changes on, get accepted (clean) text, enumerate revisions per paragraph, or write new revisions (insert/delete/replace) that show up as track changes in Word.
|
| 35 |
+
|
| 36 |
+
## Installation
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
pip install docx-revisions
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
## Quick Start
|
| 43 |
+
|
| 44 |
+
### Check out our examples!
|
| 45 |
+
|
| 46 |
+
Navigate to the [examples directory](https://github.com/balalofernandez/docx-revisions/tree/main/examples) to see code samples.
|
| 47 |
+
|
| 48 |
+
### Read tracked changes
|
| 49 |
+
|
| 50 |
+
```python
|
| 51 |
+
from docx_revisions import RevisionDocument
|
| 52 |
+
|
| 53 |
+
rdoc = RevisionDocument("tracked_changes.docx")
|
| 54 |
+
for para in rdoc.paragraphs:
|
| 55 |
+
if para.has_track_changes:
|
| 56 |
+
for change in para.track_changes:
|
| 57 |
+
print(f"{type(change).__name__}: '{change.text}' by {change.author}")
|
| 58 |
+
print(f"Accepted: {para.accepted_text}")
|
| 59 |
+
print(f"Original: {para.original_text}")
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
### Accept or reject all changes
|
| 63 |
+
|
| 64 |
+
```python
|
| 65 |
+
from docx_revisions import RevisionDocument
|
| 66 |
+
|
| 67 |
+
rdoc = RevisionDocument("tracked_changes.docx")
|
| 68 |
+
rdoc.accept_all() # or rdoc.reject_all()
|
| 69 |
+
rdoc.save("clean.docx")
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
### Find and replace with tracking
|
| 73 |
+
|
| 74 |
+
```python
|
| 75 |
+
from docx_revisions import RevisionDocument
|
| 76 |
+
|
| 77 |
+
rdoc = RevisionDocument("contract.docx")
|
| 78 |
+
count = rdoc.find_and_replace_tracked("Acme Corp", "NewCo Inc", author="Legal")
|
| 79 |
+
print(f"Replaced {count} occurrences")
|
| 80 |
+
rdoc.save("contract_revised.docx")
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
### Add tracked insertions and deletions
|
| 84 |
+
|
| 85 |
+
```python
|
| 86 |
+
from docx_revisions import RevisionParagraph
|
| 87 |
+
|
| 88 |
+
rp = RevisionParagraph.from_paragraph(paragraph)
|
| 89 |
+
rp.add_tracked_insertion("new text", author="Editor")
|
| 90 |
+
rp.add_tracked_deletion(start=5, end=10, author="Editor")
|
| 91 |
+
```
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions-0.1.5.dist-info/RECORD
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
docx_revisions-0.1.5.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
|
| 2 |
+
docx_revisions-0.1.5.dist-info/METADATA,sha256=qBV0lPAWaw6EFfaOrMklkJLtw5Twi8TMqC0u8r2TcZc,3883
|
| 3 |
+
docx_revisions-0.1.5.dist-info/RECORD,,
|
| 4 |
+
docx_revisions-0.1.5.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
docx_revisions-0.1.5.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
| 6 |
+
docx_revisions-0.1.5.dist-info/licenses/LICENSE,sha256=zErhD-66QHXGynsQ5HN0AzCOC9ONeSKE9A06H03e9G0,1072
|
| 7 |
+
docx_revisions/__init__.py,sha256=jA7SGOrJ4abzHPaJkNKPE_nsyBb4PyOgSt_mVHbJAaE,719
|
| 8 |
+
docx_revisions/_helpers.py,sha256=pua1RXAbQtrHhU2syOc_JUSc2BnLc6TrMXlSmw9fzvw,3148
|
| 9 |
+
docx_revisions/document.py,sha256=qySX5AIUgWsBz2lhhCJB2N6B-WMu8nMWmeF3ju-fKIM,8451
|
| 10 |
+
docx_revisions/oxml.py,sha256=2zniaSSzzFZG6JGpWOWiW0neBWcvKlRRFG_A2uRbwmc,5465
|
| 11 |
+
docx_revisions/paragraph.py,sha256=jg5J91rhS2J3KPMvwupEEGf79-3V9H8d_0Igkt9WSBo,23137
|
| 12 |
+
docx_revisions/revision.py,sha256=EQydJTLToPFztE2R_yF-tduv1FRD3xuT0fyOuZXWIYQ,7997
|
| 13 |
+
docx_revisions/run.py,sha256=Mt0yzROai3U_rCLGzFOuHvc455CCzT6r6yJVtSjo6fY,4629
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions-0.1.5.dist-info/REQUESTED
ADDED
|
File without changes
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions-0.1.5.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.29.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions-0.1.5.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 balalofernandez
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/VENDORED.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Vendored dependency
|
| 2 |
+
|
| 3 |
+
`docx_revisions/` (+ the sibling `docx_revisions-0.1.5.dist-info/`) is vendored
|
| 4 |
+
from PyPI **docx-revisions==0.1.5** (MIT, https://github.com/balalofernandez/docx-revisions),
|
| 5 |
+
with **one local fix** (see below).
|
| 6 |
+
|
| 7 |
+
## Local fix — end-inclusive end-offset resolution (`paragraph.py`)
|
| 8 |
+
|
| 9 |
+
`replace_tracked_at` and `add_tracked_deletion` resolved the *exclusive* `end`
|
| 10 |
+
offset with `_find_unit_at_offset`, which is inclusive semantics. When a span
|
| 11 |
+
ended exactly on a run/revision boundary (e.g. an edit that sits entirely inside
|
| 12 |
+
one prior `w:ins` but ends at that insertion's boundary), `end` resolved to the
|
| 13 |
+
*next* unit and the call raised a false **"Cannot apply tracked … across a
|
| 14 |
+
revision boundary"** — blocking in-place edits of counterparty-inserted text.
|
| 15 |
+
Both call sites now resolve `end` end-inclusively (`_find_unit_at_offset(end-1)`
|
| 16 |
+
then `+1`). Search the file for `[vendored local fix` to find the two spots.
|
| 17 |
+
This copy is model-facing only; the grader never imports `docx_revisions`.
|
| 18 |
+
|
| 19 |
+
Why: the contract-redliner scripts (`propose_edits.py`, `mark_reserved.py`,
|
| 20 |
+
`add_comment.py` reply path) import `RevisionParagraph` from `docx_revisions`,
|
| 21 |
+
but the image's PyPI copy lacks the local fix above and nothing can be installed at
|
| 22 |
+
runtime (no network egress). It is vendored
|
| 23 |
+
here (a sibling of `redline_engine/`, resolved via `sys.path[0]`) so the tools
|
| 24 |
+
work with zero code change. The `.dist-info` is included so `importlib.metadata.
|
| 25 |
+
version("docx-revisions")` in `__init__.py` resolves; `__init__.py` also guards
|
| 26 |
+
that call as belt-and-suspenders. Runtime deps (`python-docx`, `lxml`) are
|
| 27 |
+
already installed in the image.
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""docx-revisions: Track changes support for python-docx."""
|
| 2 |
+
|
| 3 |
+
from importlib.metadata import version
|
| 4 |
+
|
| 5 |
+
from docx_revisions.document import RevisionDocument
|
| 6 |
+
from docx_revisions.oxml import register_revision_elements
|
| 7 |
+
from docx_revisions.paragraph import RevisionParagraph
|
| 8 |
+
from docx_revisions.revision import TrackedChange, TrackedDeletion, TrackedInsertion
|
| 9 |
+
from docx_revisions.run import RevisionRun
|
| 10 |
+
|
| 11 |
+
# Register OXML element classes so lxml produces typed instances
|
| 12 |
+
# for w:ins, w:del, w:delText, etc.
|
| 13 |
+
register_revision_elements()
|
| 14 |
+
|
| 15 |
+
# Vendored into this skill (see VENDORED.md). The .dist-info is shipped alongside
|
| 16 |
+
# so this resolves, but guard it so a missing-metadata edge never crashes import
|
| 17 |
+
# of the model's redlining tools (that ModuleNotFoundError-style crash is exactly
|
| 18 |
+
# the env defect this vendoring fixes).
|
| 19 |
+
try:
|
| 20 |
+
__version__ = version("docx-revisions")
|
| 21 |
+
except Exception:
|
| 22 |
+
__version__ = "0.1.5"
|
| 23 |
+
__all__ = [
|
| 24 |
+
"RevisionDocument",
|
| 25 |
+
"RevisionParagraph",
|
| 26 |
+
"RevisionRun",
|
| 27 |
+
"TrackedChange",
|
| 28 |
+
"TrackedDeletion",
|
| 29 |
+
"TrackedInsertion",
|
| 30 |
+
]
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/_helpers.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared XML element builders for revision tracking.
|
| 2 |
+
|
| 3 |
+
Centralises the repeated patterns for creating ``w:r``, ``w:del``, ``w:ins``
|
| 4 |
+
elements and the ``before / del / ins / after`` splice used by both
|
| 5 |
+
``RevisionParagraph`` and ``RevisionRun``.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import contextlib
|
| 11 |
+
from typing import Callable
|
| 12 |
+
|
| 13 |
+
from docx.oxml.ns import qn
|
| 14 |
+
from docx.oxml.parser import OxmlElement
|
| 15 |
+
from lxml import etree
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def revision_attrs(rev_id: int, author: str, now: str) -> dict[str, str]:
|
| 19 |
+
"""Build the standard ``{w:id, w:author, w:date}`` attribute dict."""
|
| 20 |
+
return {qn("w:id"): str(rev_id), qn("w:author"): author, qn("w:date"): now}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def make_text_run(text: str) -> OxmlElement:
|
| 24 |
+
"""Create a ``<w:r><w:t>text</w:t></w:r>`` element with space preservation."""
|
| 25 |
+
r = OxmlElement("w:r")
|
| 26 |
+
t = OxmlElement("w:t")
|
| 27 |
+
t.text = text
|
| 28 |
+
if text.startswith(" ") or text.endswith(" "):
|
| 29 |
+
t.set(qn("xml:space"), "preserve")
|
| 30 |
+
r.append(t)
|
| 31 |
+
return r
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def make_del_element(deleted_text: str, author: str, rev_id: int, now: str) -> OxmlElement:
|
| 35 |
+
"""Create a ``<w:del><w:r><w:delText>text</w:delText></w:r></w:del>`` element."""
|
| 36 |
+
del_elem = OxmlElement("w:del", attrs=revision_attrs(rev_id, author, now))
|
| 37 |
+
del_r = OxmlElement("w:r")
|
| 38 |
+
del_text_elem = OxmlElement("w:delText")
|
| 39 |
+
del_text_elem.text = deleted_text
|
| 40 |
+
del_r.append(del_text_elem)
|
| 41 |
+
del_elem.append(del_r)
|
| 42 |
+
return del_elem
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def make_ins_element(insert_text: str, author: str, rev_id: int, now: str) -> OxmlElement:
|
| 46 |
+
"""Create a ``<w:ins><w:r><w:t>text</w:t></w:r></w:ins>`` element."""
|
| 47 |
+
ins_elem = OxmlElement("w:ins", attrs=revision_attrs(rev_id, author, now))
|
| 48 |
+
ins_r = OxmlElement("w:r")
|
| 49 |
+
ins_t = OxmlElement("w:t")
|
| 50 |
+
ins_t.text = insert_text
|
| 51 |
+
ins_r.append(ins_t)
|
| 52 |
+
ins_elem.append(ins_r)
|
| 53 |
+
return ins_elem
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def splice_tracked_replace(
|
| 57 |
+
parent: etree._Element,
|
| 58 |
+
index: int,
|
| 59 |
+
before_text: str | None,
|
| 60 |
+
deleted_text: str,
|
| 61 |
+
insert_text: str,
|
| 62 |
+
after_text: str | None,
|
| 63 |
+
author: str,
|
| 64 |
+
next_id_fn: Callable[[], int],
|
| 65 |
+
now: str,
|
| 66 |
+
) -> int:
|
| 67 |
+
"""Insert the before-run / w:del / w:ins / after-run sequence into *parent* at *index*.
|
| 68 |
+
|
| 69 |
+
Returns:
|
| 70 |
+
The number of elements inserted.
|
| 71 |
+
"""
|
| 72 |
+
insert_idx = index
|
| 73 |
+
if before_text:
|
| 74 |
+
parent.insert(insert_idx, make_text_run(before_text))
|
| 75 |
+
insert_idx += 1
|
| 76 |
+
|
| 77 |
+
parent.insert(insert_idx, make_del_element(deleted_text, author, next_id_fn(), now))
|
| 78 |
+
insert_idx += 1
|
| 79 |
+
|
| 80 |
+
parent.insert(insert_idx, make_ins_element(insert_text, author, next_id_fn(), now))
|
| 81 |
+
insert_idx += 1
|
| 82 |
+
|
| 83 |
+
if after_text:
|
| 84 |
+
parent.insert(insert_idx, make_text_run(after_text))
|
| 85 |
+
insert_idx += 1
|
| 86 |
+
|
| 87 |
+
return insert_idx - index
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def next_revision_id(element: etree._Element) -> int:
|
| 91 |
+
"""Generate the next unique revision ID by scanning the document tree from *element*."""
|
| 92 |
+
max_id = 0
|
| 93 |
+
for ins_or_del in element.xpath("//w:ins | //w:del"):
|
| 94 |
+
id_val = ins_or_del.get(qn("w:id"))
|
| 95 |
+
if id_val is not None:
|
| 96 |
+
with contextlib.suppress(ValueError):
|
| 97 |
+
max_id = max(max_id, int(id_val))
|
| 98 |
+
return max_id + 1
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/document.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RevisionDocument — the main entry point for working with tracked changes.
|
| 2 |
+
|
| 3 |
+
Opens a ``.docx`` file (or wraps an existing ``Document``) and exposes
|
| 4 |
+
paragraphs as ``RevisionParagraph`` objects, plus document-level operations
|
| 5 |
+
for accepting, rejecting, and performing find-and-replace with tracking.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import IO, Iterator, List
|
| 12 |
+
|
| 13 |
+
from docx import Document as _new_document
|
| 14 |
+
from docx.document import Document as _DocumentClass
|
| 15 |
+
from docx.table import Table as _Table
|
| 16 |
+
|
| 17 |
+
from docx_revisions.paragraph import IndexMode, RevisionParagraph
|
| 18 |
+
from docx_revisions.revision import TrackedChange
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class RevisionDocument:
|
| 22 |
+
"""Entry point for reading and writing tracked changes in a docx file.
|
| 23 |
+
|
| 24 |
+
Example:
|
| 25 |
+
```python
|
| 26 |
+
from docx_revisions import RevisionDocument
|
| 27 |
+
|
| 28 |
+
rdoc = RevisionDocument("contract.docx")
|
| 29 |
+
for para in rdoc.paragraphs:
|
| 30 |
+
if para.has_track_changes:
|
| 31 |
+
print(para.accepted_text)
|
| 32 |
+
|
| 33 |
+
rdoc.accept_all()
|
| 34 |
+
rdoc.save("contract_clean.docx")
|
| 35 |
+
```
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def __init__(self, path_or_doc: str | Path | IO[bytes] | _DocumentClass | None = None):
|
| 39 |
+
"""Open a docx file or wrap an existing ``Document``.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
path_or_doc: A file path, file-like object, or an existing
|
| 43 |
+
``Document`` instance. Pass ``None`` to create a new
|
| 44 |
+
blank document.
|
| 45 |
+
"""
|
| 46 |
+
if isinstance(path_or_doc, _DocumentClass):
|
| 47 |
+
self._document = path_or_doc
|
| 48 |
+
else:
|
| 49 |
+
self._document = _new_document(path_or_doc)
|
| 50 |
+
|
| 51 |
+
@property
|
| 52 |
+
def document(self) -> _DocumentClass:
|
| 53 |
+
"""The underlying python-docx ``Document`` object."""
|
| 54 |
+
return self._document
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def paragraphs(self) -> List[RevisionParagraph]:
|
| 58 |
+
"""All body paragraphs as ``RevisionParagraph`` objects.
|
| 59 |
+
|
| 60 |
+
Only paragraphs in the document body are returned. Paragraphs inside
|
| 61 |
+
tables are excluded. Use :attr:`all_paragraphs` to iterate over every
|
| 62 |
+
paragraph including those nested in tables.
|
| 63 |
+
"""
|
| 64 |
+
return [RevisionParagraph.from_paragraph(p) for p in self._document.paragraphs]
|
| 65 |
+
|
| 66 |
+
@property
|
| 67 |
+
def all_paragraphs(self) -> List[RevisionParagraph]:
|
| 68 |
+
"""Every paragraph in the document, including those inside tables.
|
| 69 |
+
|
| 70 |
+
Walks the document body and recurses into all tables (including
|
| 71 |
+
nested tables within cells).
|
| 72 |
+
|
| 73 |
+
Example:
|
| 74 |
+
```python
|
| 75 |
+
rdoc = RevisionDocument("contract.docx")
|
| 76 |
+
for para in rdoc.all_paragraphs:
|
| 77 |
+
if para.has_track_changes:
|
| 78 |
+
print(para.accepted_text)
|
| 79 |
+
```
|
| 80 |
+
"""
|
| 81 |
+
return list(self._iter_all_paragraphs())
|
| 82 |
+
|
| 83 |
+
def _iter_all_paragraphs(self) -> Iterator[RevisionParagraph]:
|
| 84 |
+
"""Yield every ``RevisionParagraph`` in the body and all tables.
|
| 85 |
+
|
| 86 |
+
Recurses into nested tables via ``cell.tables``.
|
| 87 |
+
"""
|
| 88 |
+
for p in self._document.paragraphs:
|
| 89 |
+
yield RevisionParagraph.from_paragraph(p)
|
| 90 |
+
for table in self._document.tables:
|
| 91 |
+
yield from self._iter_table_paragraphs(table)
|
| 92 |
+
|
| 93 |
+
def _iter_table_paragraphs(self, table: _Table) -> Iterator[RevisionParagraph]:
|
| 94 |
+
"""Yield every ``RevisionParagraph`` inside *table* recursively."""
|
| 95 |
+
for row in table.rows:
|
| 96 |
+
for cell in row.cells:
|
| 97 |
+
for p in cell.paragraphs:
|
| 98 |
+
yield RevisionParagraph.from_paragraph(p)
|
| 99 |
+
for nested in cell.tables:
|
| 100 |
+
yield from self._iter_table_paragraphs(nested)
|
| 101 |
+
|
| 102 |
+
@property
|
| 103 |
+
def track_changes(self) -> List[TrackedChange]:
|
| 104 |
+
"""All tracked changes across the document body and tables."""
|
| 105 |
+
changes: List[TrackedChange] = []
|
| 106 |
+
for para in self._iter_all_paragraphs():
|
| 107 |
+
changes.extend(para.track_changes)
|
| 108 |
+
return changes
|
| 109 |
+
|
| 110 |
+
def accept_all(self) -> None:
|
| 111 |
+
"""Accept every tracked change in the document.
|
| 112 |
+
|
| 113 |
+
Insertions are kept (wrapper removed), deletions are removed entirely.
|
| 114 |
+
Tracked changes inside tables (including nested tables) are processed.
|
| 115 |
+
Loops until no tracked changes remain so that nested revisions (which
|
| 116 |
+
can arise from ``replace_tracked(index_mode="accepted")``) are fully
|
| 117 |
+
resolved.
|
| 118 |
+
"""
|
| 119 |
+
for para in self._iter_all_paragraphs():
|
| 120 |
+
while para.track_changes:
|
| 121 |
+
for change in list(para.track_changes):
|
| 122 |
+
change.accept()
|
| 123 |
+
|
| 124 |
+
def reject_all(self) -> None:
|
| 125 |
+
"""Reject every tracked change in the document.
|
| 126 |
+
|
| 127 |
+
Insertions are removed entirely, deletions are kept (wrapper removed,
|
| 128 |
+
``w:delText`` converted back to ``w:t``). Tracked changes inside
|
| 129 |
+
tables (including nested tables) are processed. Loops until no tracked
|
| 130 |
+
changes remain.
|
| 131 |
+
"""
|
| 132 |
+
for para in self._iter_all_paragraphs():
|
| 133 |
+
while para.track_changes:
|
| 134 |
+
for change in list(para.track_changes):
|
| 135 |
+
change.reject()
|
| 136 |
+
|
| 137 |
+
def find_and_replace_tracked(
|
| 138 |
+
self,
|
| 139 |
+
search_text: str,
|
| 140 |
+
replace_text: str,
|
| 141 |
+
author: str = "",
|
| 142 |
+
comment: str | None = None,
|
| 143 |
+
index_mode: IndexMode = "text",
|
| 144 |
+
) -> int:
|
| 145 |
+
"""Find and replace across the whole document with track changes.
|
| 146 |
+
|
| 147 |
+
Searches all paragraphs in the document body and tables (including
|
| 148 |
+
nested tables).
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
search_text: Text to find.
|
| 152 |
+
replace_text: Replacement text.
|
| 153 |
+
author: Author name for the revisions.
|
| 154 |
+
comment: Optional comment text (requires python-docx comment
|
| 155 |
+
support).
|
| 156 |
+
index_mode: Which text view to search against per paragraph. See
|
| 157 |
+
:meth:`RevisionParagraph.replace_tracked` — ``"text"`` (default),
|
| 158 |
+
``"accepted"``, or ``"original"``.
|
| 159 |
+
|
| 160 |
+
Returns:
|
| 161 |
+
Total number of replacements made.
|
| 162 |
+
|
| 163 |
+
Example:
|
| 164 |
+
```python
|
| 165 |
+
rdoc = RevisionDocument("doc.docx")
|
| 166 |
+
# Replace against the accepted view so matches inside prior
|
| 167 |
+
# tracked insertions are also found.
|
| 168 |
+
count = rdoc.find_and_replace_tracked(
|
| 169 |
+
"Acme Corp", "NewCo Inc", author="Legal", index_mode="accepted"
|
| 170 |
+
)
|
| 171 |
+
rdoc.save("doc_revised.docx")
|
| 172 |
+
```
|
| 173 |
+
"""
|
| 174 |
+
total_count = 0
|
| 175 |
+
for para in self._iter_all_paragraphs():
|
| 176 |
+
total_count += para.replace_tracked(
|
| 177 |
+
search_text, replace_text, author=author, comment=comment, index_mode=index_mode
|
| 178 |
+
)
|
| 179 |
+
return total_count
|
| 180 |
+
|
| 181 |
+
def save(self, path_or_stream: str | Path | IO[bytes]) -> None:
|
| 182 |
+
"""Save the document to a path or file-like object.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
path_or_stream: Destination file path (``str`` or ``Path``) or a
|
| 186 |
+
writable binary file-like object (anything with a ``write``
|
| 187 |
+
method, such as ``io.BytesIO``).
|
| 188 |
+
|
| 189 |
+
Raises:
|
| 190 |
+
TypeError: If *path_or_stream* is neither a path nor a writable
|
| 191 |
+
binary stream.
|
| 192 |
+
ValueError: If *path_or_stream* is an empty string, or is a text-
|
| 193 |
+
mode file object.
|
| 194 |
+
|
| 195 |
+
Example:
|
| 196 |
+
```python
|
| 197 |
+
import io
|
| 198 |
+
from docx_revisions import RevisionDocument
|
| 199 |
+
|
| 200 |
+
rdoc = RevisionDocument("contract.docx")
|
| 201 |
+
rdoc.accept_all()
|
| 202 |
+
|
| 203 |
+
buffer = io.BytesIO()
|
| 204 |
+
rdoc.save(buffer)
|
| 205 |
+
buffer.seek(0)
|
| 206 |
+
data = buffer.read()
|
| 207 |
+
```
|
| 208 |
+
"""
|
| 209 |
+
if isinstance(path_or_stream, str | Path):
|
| 210 |
+
path_str = str(path_or_stream)
|
| 211 |
+
if not path_str:
|
| 212 |
+
raise ValueError("save() path must not be empty")
|
| 213 |
+
self._document.save(path_str)
|
| 214 |
+
return
|
| 215 |
+
|
| 216 |
+
write = getattr(path_or_stream, "write", None)
|
| 217 |
+
if not callable(write):
|
| 218 |
+
raise TypeError(
|
| 219 |
+
f"save() expects a str, Path, or writable binary file-like object; got {type(path_or_stream).__name__}"
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
mode = getattr(path_or_stream, "mode", None)
|
| 223 |
+
if isinstance(mode, str) and "b" not in mode:
|
| 224 |
+
raise ValueError(
|
| 225 |
+
f"save() requires a binary-mode stream; got mode={mode!r}. "
|
| 226 |
+
"Open the file with mode='wb' or use io.BytesIO()."
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
self._document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
+
"""Custom element classes for revision tracking (tracked changes).
|
| 2 |
+
|
| 3 |
+
Registers OXML element classes so that lxml produces typed elements
|
| 4 |
+
(e.g. ``CT_RunTrackChange``) instead of generic ``BaseOxmlElement``
|
| 5 |
+
when parsing ``w:ins``, ``w:del``, and related revision elements.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import datetime as dt
|
| 11 |
+
from typing import TYPE_CHECKING, List
|
| 12 |
+
|
| 13 |
+
from docx.oxml.ns import qn
|
| 14 |
+
from docx.oxml.simpletypes import ST_String, XsdInt
|
| 15 |
+
from docx.oxml.text.run import CT_Text
|
| 16 |
+
from docx.oxml.xmlchemy import BaseOxmlElement, OptionalAttribute, RequiredAttribute, ZeroOrMore, ZeroOrOne
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from docx.oxml.table import CT_Tbl
|
| 20 |
+
from docx.oxml.text.paragraph import CT_P
|
| 21 |
+
from docx.oxml.text.run import CT_R
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class CT_TrackChange(BaseOxmlElement):
|
| 25 |
+
"""Base class for tracked change elements.
|
| 26 |
+
|
| 27 |
+
This serves as the base for ``w:ins``, ``w:del``, and other revision
|
| 28 |
+
tracking elements. Provides common attributes: ``w:id``, ``w:author``,
|
| 29 |
+
and ``w:date``.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
id: int = RequiredAttribute("w:id", XsdInt) # pyright: ignore[reportAssignmentType]
|
| 33 |
+
author: str = RequiredAttribute("w:author", ST_String) # pyright: ignore[reportAssignmentType]
|
| 34 |
+
date: str | None = OptionalAttribute("w:date", ST_String) # pyright: ignore[reportAssignmentType]
|
| 35 |
+
|
| 36 |
+
@property
|
| 37 |
+
def date_value(self) -> dt.datetime | None:
|
| 38 |
+
"""The ``w:date`` attribute as a datetime object, or None if not set."""
|
| 39 |
+
date_str = self.date
|
| 40 |
+
if date_str is None:
|
| 41 |
+
return None
|
| 42 |
+
try:
|
| 43 |
+
return dt.datetime.fromisoformat(date_str.replace("Z", "+00:00"))
|
| 44 |
+
except ValueError:
|
| 45 |
+
return None
|
| 46 |
+
|
| 47 |
+
@date_value.setter
|
| 48 |
+
def date_value(self, value: dt.datetime | None):
|
| 49 |
+
"""Set the ``w:date`` attribute from a datetime object."""
|
| 50 |
+
if value is None:
|
| 51 |
+
date_qn = qn("w:date")
|
| 52 |
+
if date_qn in self.attrib: # pyright: ignore[reportUnknownMemberType]
|
| 53 |
+
del self.attrib[date_qn] # pyright: ignore[reportUnknownMemberType]
|
| 54 |
+
else:
|
| 55 |
+
self.date = value.strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class CT_RunTrackChange(CT_TrackChange):
|
| 59 |
+
"""``w:ins`` or ``w:del`` element containing run-level content.
|
| 60 |
+
|
| 61 |
+
Used for tracking insertions and deletions at the run level within a
|
| 62 |
+
paragraph, or at the block level containing paragraphs and tables.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
p_lst: List[CT_P]
|
| 66 |
+
tbl_lst: List[CT_Tbl]
|
| 67 |
+
r_lst: List[CT_R]
|
| 68 |
+
|
| 69 |
+
p = ZeroOrMore("w:p")
|
| 70 |
+
tbl = ZeroOrMore("w:tbl")
|
| 71 |
+
r = ZeroOrMore("w:r")
|
| 72 |
+
|
| 73 |
+
@property
|
| 74 |
+
def inner_content_elements(self) -> List[CT_P | CT_Tbl]:
|
| 75 |
+
"""All ``w:p`` and ``w:tbl`` elements in this tracked change, in document order."""
|
| 76 |
+
return self.xpath("./w:p | ./w:tbl")
|
| 77 |
+
|
| 78 |
+
@property
|
| 79 |
+
def run_content_elements(self) -> List[CT_R]:
|
| 80 |
+
"""All ``w:r`` elements in this tracked change, in document order."""
|
| 81 |
+
return self.xpath("./w:r")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class CT_RPrChange(CT_TrackChange):
|
| 85 |
+
"""``w:rPrChange`` element, tracking changes to run properties.
|
| 86 |
+
|
| 87 |
+
Contains the previous run properties before the change was made.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
rPr: BaseOxmlElement | None = ZeroOrOne("w:rPr") # pyright: ignore[reportAssignmentType]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class CT_PPrChange(CT_TrackChange):
|
| 94 |
+
"""``w:pPrChange`` element, tracking changes to paragraph properties.
|
| 95 |
+
|
| 96 |
+
Contains the previous paragraph properties before the change was made.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
pPr: BaseOxmlElement | None = ZeroOrOne("w:pPr") # pyright: ignore[reportAssignmentType]
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class CT_SectPrChange(CT_TrackChange):
|
| 103 |
+
"""``w:sectPrChange`` element, tracking changes to section properties.
|
| 104 |
+
|
| 105 |
+
Contains the previous section properties before the change was made.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
sectPr: BaseOxmlElement | None = ZeroOrOne("w:sectPr") # pyright: ignore[reportAssignmentType]
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class CT_TblPrChange(CT_TrackChange):
|
| 112 |
+
"""``w:tblPrChange`` element, tracking changes to table properties.
|
| 113 |
+
|
| 114 |
+
Contains the previous table properties before the change was made.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
tblPr: BaseOxmlElement | None = ZeroOrOne("w:tblPr") # pyright: ignore[reportAssignmentType]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class CT_TcPrChange(CT_TrackChange):
|
| 121 |
+
"""``w:tcPrChange`` element, tracking changes to table cell properties.
|
| 122 |
+
|
| 123 |
+
Contains the previous cell properties before the change was made.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
tcPr: BaseOxmlElement | None = ZeroOrOne("w:tcPr") # pyright: ignore[reportAssignmentType]
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class CT_TrPrChange(CT_TrackChange):
|
| 130 |
+
"""``w:trPrChange`` element, tracking changes to table row properties.
|
| 131 |
+
|
| 132 |
+
Contains the previous row properties before the change was made.
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
trPr: BaseOxmlElement | None = ZeroOrOne("w:trPr") # pyright: ignore[reportAssignmentType]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def register_revision_elements() -> None:
|
| 139 |
+
"""Register all revision-related OXML element classes.
|
| 140 |
+
|
| 141 |
+
Must be called once (typically at package import time) so that lxml
|
| 142 |
+
produces typed element instances when parsing revision markup.
|
| 143 |
+
"""
|
| 144 |
+
from docx.oxml.parser import register_element_cls
|
| 145 |
+
|
| 146 |
+
register_element_cls("w:ins", CT_RunTrackChange)
|
| 147 |
+
register_element_cls("w:del", CT_RunTrackChange)
|
| 148 |
+
register_element_cls("w:delText", CT_Text)
|
| 149 |
+
register_element_cls("w:rPrChange", CT_RPrChange)
|
| 150 |
+
register_element_cls("w:pPrChange", CT_PPrChange)
|
| 151 |
+
register_element_cls("w:sectPrChange", CT_SectPrChange)
|
| 152 |
+
register_element_cls("w:tblPrChange", CT_TblPrChange)
|
| 153 |
+
register_element_cls("w:tcPrChange", CT_TcPrChange)
|
| 154 |
+
register_element_cls("w:trPrChange", CT_TrPrChange)
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/paragraph.py
ADDED
|
@@ -0,0 +1,654 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RevisionParagraph — a ``Paragraph`` subclass with track-change support.
|
| 2 |
+
|
| 3 |
+
Wraps an existing ``Paragraph`` (sharing the same XML element) and adds
|
| 4 |
+
methods for reading, creating, accepting, and rejecting tracked insertions
|
| 5 |
+
and deletions.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import datetime as dt
|
| 11 |
+
from typing import TYPE_CHECKING, Iterator, List, Literal
|
| 12 |
+
|
| 13 |
+
from docx.oxml.ns import qn
|
| 14 |
+
from docx.oxml.parser import OxmlElement
|
| 15 |
+
from docx.text.hyperlink import Hyperlink
|
| 16 |
+
from docx.text.paragraph import Paragraph
|
| 17 |
+
from docx.text.run import Run
|
| 18 |
+
from lxml import etree
|
| 19 |
+
|
| 20 |
+
from docx_revisions._helpers import (
|
| 21 |
+
make_del_element,
|
| 22 |
+
make_text_run,
|
| 23 |
+
next_revision_id,
|
| 24 |
+
revision_attrs,
|
| 25 |
+
splice_tracked_replace,
|
| 26 |
+
)
|
| 27 |
+
from docx_revisions.revision import TrackedChange, TrackedDeletion, TrackedInsertion
|
| 28 |
+
|
| 29 |
+
if TYPE_CHECKING:
|
| 30 |
+
from docx.styles.style import CharacterStyle
|
| 31 |
+
|
| 32 |
+
IndexMode = Literal["text", "accepted", "original"]
|
| 33 |
+
|
| 34 |
+
_REVISION_TAGS = (qn("w:ins"), qn("w:del"), qn("w:moveFrom"), qn("w:moveTo"))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _assert_no_interleaved_revision(parent, first_el, last_el, what: str) -> None:
|
| 38 |
+
"""[vendored local fix — see VENDORED.md] Raise if a revision wrapper sits
|
| 39 |
+
physically between the first and last spanned unit in *parent*.
|
| 40 |
+
|
| 41 |
+
The unit-parent guard alone misses this: ``_get_editable_units`` skips ``w:del``
|
| 42 |
+
(and, in ``text`` mode, any run nested inside a ``w:ins``/``w:del``), so a span
|
| 43 |
+
``base…<w:del>…base`` enumerates two top-level runs that share the ``w:p`` parent
|
| 44 |
+
and passes the guard — but the removal loop then leaves the interleaved ``w:del``,
|
| 45 |
+
which the splice relocates, silently reordering the reject-all base text (a
|
| 46 |
+
script-only run then trips the grader's content-fidelity gate and scores 0).
|
| 47 |
+
Rejecting here converts that into the actionable revision-boundary error the
|
| 48 |
+
caller already recovers from by narrowing. A span entirely inside one ``w:ins``
|
| 49 |
+
has that ``w:ins`` as its parent, whose children are plain runs, so this never
|
| 50 |
+
false-fires on the supported in-insertion edit.
|
| 51 |
+
"""
|
| 52 |
+
sibs = list(parent)
|
| 53 |
+
try:
|
| 54 |
+
i0 = sibs.index(first_el)
|
| 55 |
+
i1 = sibs.index(last_el)
|
| 56 |
+
except ValueError:
|
| 57 |
+
return
|
| 58 |
+
if i1 < i0:
|
| 59 |
+
i0, i1 = i1, i0
|
| 60 |
+
for k in range(i0, i1 + 1):
|
| 61 |
+
if sibs[k].tag in _REVISION_TAGS:
|
| 62 |
+
raise ValueError(
|
| 63 |
+
f"Cannot apply tracked {what} across a revision boundary; "
|
| 64 |
+
"operate on a narrower span entirely inside or outside a prior revision."
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class RevisionParagraph(Paragraph):
|
| 69 |
+
"""A ``Paragraph`` subclass that adds track-change support.
|
| 70 |
+
|
| 71 |
+
Create from an existing ``Paragraph`` with ``from_paragraph()`` — the
|
| 72 |
+
two objects share the same underlying XML element so mutations via either
|
| 73 |
+
reference are visible to both.
|
| 74 |
+
|
| 75 |
+
Example:
|
| 76 |
+
```python
|
| 77 |
+
from docx import Document
|
| 78 |
+
from docx_revisions import RevisionParagraph
|
| 79 |
+
|
| 80 |
+
doc = Document("example.docx")
|
| 81 |
+
for para in doc.paragraphs:
|
| 82 |
+
rp = RevisionParagraph.from_paragraph(para)
|
| 83 |
+
if rp.has_track_changes:
|
| 84 |
+
print(f"Insertions: {len(rp.insertions)}")
|
| 85 |
+
print(f"Deletions: {len(rp.deletions)}")
|
| 86 |
+
```
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
@classmethod
|
| 90 |
+
def from_paragraph(cls, para: Paragraph) -> RevisionParagraph:
|
| 91 |
+
"""Create a ``RevisionParagraph`` that shares *para*'s XML element.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
para: An existing ``Paragraph`` object.
|
| 95 |
+
|
| 96 |
+
Returns:
|
| 97 |
+
A ``RevisionParagraph`` wrapping the same ``<w:p>`` element.
|
| 98 |
+
"""
|
| 99 |
+
return cls(para._p, para._parent)
|
| 100 |
+
|
| 101 |
+
# ------------------------------------------------------------------
|
| 102 |
+
# Read-only properties
|
| 103 |
+
# ------------------------------------------------------------------
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def has_track_changes(self) -> bool:
|
| 107 |
+
"""True if this paragraph contains any ``w:ins`` or ``w:del`` children."""
|
| 108 |
+
return bool(self._p.xpath("./w:ins | ./w:del"))
|
| 109 |
+
|
| 110 |
+
@property
|
| 111 |
+
def insertions(self) -> List[TrackedInsertion]:
|
| 112 |
+
"""All tracked insertions in this paragraph, in document order."""
|
| 113 |
+
return [
|
| 114 |
+
TrackedInsertion(e, self) # pyright: ignore[reportArgumentType]
|
| 115 |
+
for e in self._p.xpath("./w:ins")
|
| 116 |
+
]
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def deletions(self) -> List[TrackedDeletion]:
|
| 120 |
+
"""All tracked deletions in this paragraph, in document order."""
|
| 121 |
+
return [
|
| 122 |
+
TrackedDeletion(e, self) # pyright: ignore[reportArgumentType]
|
| 123 |
+
for e in self._p.xpath("./w:del")
|
| 124 |
+
]
|
| 125 |
+
|
| 126 |
+
@property
|
| 127 |
+
def track_changes(self) -> List[TrackedChange]:
|
| 128 |
+
"""All tracked changes (insertions and deletions) in document order."""
|
| 129 |
+
changes: List[TrackedChange] = []
|
| 130 |
+
for e in self._p.xpath("./w:ins | ./w:del"):
|
| 131 |
+
tag = e.tag # pyright: ignore[reportUnknownMemberType]
|
| 132 |
+
if tag == qn("w:ins"):
|
| 133 |
+
changes.append(TrackedInsertion(e, self)) # pyright: ignore[reportArgumentType]
|
| 134 |
+
elif tag == qn("w:del"):
|
| 135 |
+
changes.append(TrackedDeletion(e, self)) # pyright: ignore[reportArgumentType]
|
| 136 |
+
return changes
|
| 137 |
+
|
| 138 |
+
def _text_view(self, *, accept_changes: bool) -> str:
|
| 139 |
+
"""Return paragraph text with changes either accepted or rejected.
|
| 140 |
+
|
| 141 |
+
Args:
|
| 142 |
+
accept_changes: If True, include insertions and skip deletions
|
| 143 |
+
(accepted view). If False, include deletions and skip
|
| 144 |
+
insertions (original/rejected view).
|
| 145 |
+
"""
|
| 146 |
+
include_tag = qn("w:ins") if accept_changes else qn("w:del")
|
| 147 |
+
skip_tag = qn("w:del") if accept_changes else qn("w:ins")
|
| 148 |
+
|
| 149 |
+
def walk(element: etree._Element) -> str:
|
| 150 |
+
parts: List[str] = []
|
| 151 |
+
for child in element.xpath("./w:r | ./w:ins | ./w:del"):
|
| 152 |
+
tag = child.tag
|
| 153 |
+
if tag == qn("w:r"):
|
| 154 |
+
for t in child.xpath("./w:t | ./w:delText"):
|
| 155 |
+
parts.append(t.text or "")
|
| 156 |
+
elif tag == include_tag:
|
| 157 |
+
parts.append(walk(child))
|
| 158 |
+
elif tag == skip_tag:
|
| 159 |
+
continue
|
| 160 |
+
return "".join(parts)
|
| 161 |
+
|
| 162 |
+
return walk(self._p)
|
| 163 |
+
|
| 164 |
+
@property
|
| 165 |
+
def accepted_text(self) -> str:
|
| 166 |
+
"""Text of this paragraph with all changes accepted.
|
| 167 |
+
|
| 168 |
+
Insertions are kept, deletions are removed.
|
| 169 |
+
"""
|
| 170 |
+
return self._text_view(accept_changes=True)
|
| 171 |
+
|
| 172 |
+
@property
|
| 173 |
+
def original_text(self) -> str:
|
| 174 |
+
"""Text of this paragraph with all changes rejected.
|
| 175 |
+
|
| 176 |
+
Deletions are kept, insertions are removed.
|
| 177 |
+
"""
|
| 178 |
+
return self._text_view(accept_changes=False)
|
| 179 |
+
|
| 180 |
+
# ------------------------------------------------------------------
|
| 181 |
+
# Iteration
|
| 182 |
+
# ------------------------------------------------------------------
|
| 183 |
+
|
| 184 |
+
def iter_inner_content( # type: ignore[override]
|
| 185 |
+
self, include_revisions: bool = False
|
| 186 |
+
) -> Iterator[Run | Hyperlink | TrackedInsertion | TrackedDeletion]:
|
| 187 |
+
"""Generate runs, hyperlinks, and optionally revisions in document order.
|
| 188 |
+
|
| 189 |
+
Args:
|
| 190 |
+
include_revisions: If True, also yields ``TrackedInsertion`` and
|
| 191 |
+
``TrackedDeletion`` objects for run-level tracked changes.
|
| 192 |
+
Defaults to False for backward compatibility.
|
| 193 |
+
|
| 194 |
+
Yields:
|
| 195 |
+
``Run``, ``Hyperlink``, ``TrackedInsertion``, or ``TrackedDeletion``
|
| 196 |
+
objects in document order.
|
| 197 |
+
"""
|
| 198 |
+
if include_revisions:
|
| 199 |
+
elements = self._p.xpath("./w:r | ./w:hyperlink | ./w:ins | ./w:del")
|
| 200 |
+
else:
|
| 201 |
+
elements = self._p.xpath("./w:r | ./w:hyperlink")
|
| 202 |
+
|
| 203 |
+
for element in elements:
|
| 204 |
+
tag = element.tag # pyright: ignore[reportUnknownMemberType]
|
| 205 |
+
if tag == qn("w:r"):
|
| 206 |
+
yield Run(element, self)
|
| 207 |
+
elif tag == qn("w:hyperlink"):
|
| 208 |
+
yield Hyperlink(element, self) # pyright: ignore[reportArgumentType]
|
| 209 |
+
elif tag == qn("w:ins"):
|
| 210 |
+
yield TrackedInsertion(element, self) # pyright: ignore[reportArgumentType]
|
| 211 |
+
elif tag == qn("w:del"):
|
| 212 |
+
yield TrackedDeletion(element, self) # pyright: ignore[reportArgumentType]
|
| 213 |
+
|
| 214 |
+
# ------------------------------------------------------------------
|
| 215 |
+
# Write operations
|
| 216 |
+
# ------------------------------------------------------------------
|
| 217 |
+
|
| 218 |
+
def add_tracked_insertion(
|
| 219 |
+
self,
|
| 220 |
+
text: str | None = None,
|
| 221 |
+
style: str | CharacterStyle | None = None,
|
| 222 |
+
author: str = "",
|
| 223 |
+
revision_id: int | None = None,
|
| 224 |
+
) -> TrackedInsertion:
|
| 225 |
+
"""Append a tracked insertion containing a run with the specified text.
|
| 226 |
+
|
| 227 |
+
The run is wrapped in a ``w:ins`` element, marking it as inserted
|
| 228 |
+
content when track changes is enabled.
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
text: Text to add to the run.
|
| 232 |
+
style: Character style to apply to the run.
|
| 233 |
+
author: Author name for the revision. Defaults to empty string.
|
| 234 |
+
revision_id: Unique ID for this revision. Auto-generated if not
|
| 235 |
+
provided.
|
| 236 |
+
|
| 237 |
+
Returns:
|
| 238 |
+
A ``TrackedInsertion`` wrapping the new ``w:ins`` element.
|
| 239 |
+
|
| 240 |
+
Example:
|
| 241 |
+
```python
|
| 242 |
+
rp = RevisionParagraph.from_paragraph(paragraph)
|
| 243 |
+
tracked = rp.add_tracked_insertion("new text", author="Editor")
|
| 244 |
+
print(tracked.text)
|
| 245 |
+
```
|
| 246 |
+
"""
|
| 247 |
+
if revision_id is None:
|
| 248 |
+
revision_id = self._next_revision_id()
|
| 249 |
+
|
| 250 |
+
ins = OxmlElement(
|
| 251 |
+
"w:ins",
|
| 252 |
+
attrs=revision_attrs(revision_id, author, dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")),
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
r = OxmlElement("w:r")
|
| 256 |
+
ins.append(r)
|
| 257 |
+
self._p.append(ins) # pyright: ignore[reportUnknownMemberType]
|
| 258 |
+
|
| 259 |
+
tracked_insertion = TrackedInsertion(ins, self) # pyright: ignore[reportArgumentType]
|
| 260 |
+
if text:
|
| 261 |
+
for run in tracked_insertion.runs:
|
| 262 |
+
run.text = text
|
| 263 |
+
if style:
|
| 264 |
+
for run in tracked_insertion.runs:
|
| 265 |
+
run.style = style
|
| 266 |
+
|
| 267 |
+
return tracked_insertion
|
| 268 |
+
|
| 269 |
+
def add_tracked_deletion(
|
| 270 |
+
self, start: int, end: int, author: str = "", revision_id: int | None = None, index_mode: IndexMode = "text"
|
| 271 |
+
) -> TrackedDeletion:
|
| 272 |
+
"""Wrap existing text at *[start, end)* in a ``w:del`` element.
|
| 273 |
+
|
| 274 |
+
The text remains in the document but is marked as deleted. The
|
| 275 |
+
corresponding ``w:t`` elements are converted to ``w:delText``.
|
| 276 |
+
|
| 277 |
+
Args:
|
| 278 |
+
start: Starting character offset (0-based, inclusive).
|
| 279 |
+
end: Ending character offset (0-based, exclusive).
|
| 280 |
+
author: Author name for the revision.
|
| 281 |
+
revision_id: Unique ID for this revision. Auto-generated if not
|
| 282 |
+
provided.
|
| 283 |
+
index_mode: Which text view the offsets index into:
|
| 284 |
+
``"text"`` (default, raw ``paragraph.text`` ignoring prior
|
| 285 |
+
revisions), ``"accepted"`` (``paragraph.accepted_text``, with
|
| 286 |
+
prior insertions kept and deletions skipped), or
|
| 287 |
+
``"original"`` (``paragraph.original_text``, with prior
|
| 288 |
+
deletions kept and insertions skipped).
|
| 289 |
+
|
| 290 |
+
Returns:
|
| 291 |
+
A ``TrackedDeletion`` wrapping the new ``w:del`` element.
|
| 292 |
+
|
| 293 |
+
Raises:
|
| 294 |
+
ValueError: If offsets are invalid.
|
| 295 |
+
|
| 296 |
+
Example:
|
| 297 |
+
```python
|
| 298 |
+
# Delete characters from the accepted (post-revision) view
|
| 299 |
+
rp.add_tracked_deletion(0, 5, author="Editor", index_mode="accepted")
|
| 300 |
+
```
|
| 301 |
+
"""
|
| 302 |
+
view_text = self._view_text(index_mode)
|
| 303 |
+
if start < 0 or end > len(view_text) or start >= end:
|
| 304 |
+
raise ValueError(f"Invalid offsets: start={start}, end={end} for text of length {len(view_text)}")
|
| 305 |
+
|
| 306 |
+
if revision_id is None:
|
| 307 |
+
revision_id = self._next_revision_id()
|
| 308 |
+
|
| 309 |
+
units = self._get_editable_units(index_mode)
|
| 310 |
+
if not units:
|
| 311 |
+
raise ValueError("Paragraph has no runs")
|
| 312 |
+
boundaries = self._unit_boundaries(units)
|
| 313 |
+
|
| 314 |
+
start_unit_idx, start_offset = self._find_unit_at_offset(boundaries, start)
|
| 315 |
+
end_unit_idx, end_offset = self._find_unit_at_offset(boundaries, end)
|
| 316 |
+
# [vendored local fix — see VENDORED.md] Resolve the EXCLUSIVE end offset
|
| 317 |
+
# end-inclusively so a span ending exactly on a unit boundary stays in the
|
| 318 |
+
# preceding unit instead of falsely crossing into the next revision.
|
| 319 |
+
if end > start:
|
| 320 |
+
_eu, _eo = self._find_unit_at_offset(boundaries, end - 1)
|
| 321 |
+
end_unit_idx, end_offset = _eu, _eo + 1
|
| 322 |
+
|
| 323 |
+
# ALL units in the [start, end] span must share the same parent for a
|
| 324 |
+
# clean single-parent splice. This holds when the span is entirely in
|
| 325 |
+
# top-level w:r runs, or entirely inside one w:ins / w:del wrapper.
|
| 326 |
+
# [vendored local fix — see VENDORED.md] Checking only the FIRST and LAST
|
| 327 |
+
# unit's parent let a span that *contains* a revision in the middle pass
|
| 328 |
+
# the guard: the removal loop then skips the middle unit (different parent)
|
| 329 |
+
# while deleted_text still included its chars → silent OOXML corruption
|
| 330 |
+
# (counterparty-inserted digits duplicated into the base text). Require
|
| 331 |
+
# every spanned unit to share the parent so the boundary case raises
|
| 332 |
+
# cleanly (the caller narrows the anchor) instead of corrupting the doc.
|
| 333 |
+
start_parent = units[start_unit_idx].getparent()
|
| 334 |
+
if start_parent is None or any(
|
| 335 |
+
units[i].getparent() is not start_parent
|
| 336 |
+
for i in range(start_unit_idx, end_unit_idx + 1)
|
| 337 |
+
):
|
| 338 |
+
raise ValueError(
|
| 339 |
+
"Cannot apply tracked deletion across a revision boundary; "
|
| 340 |
+
"operate on a narrower span entirely inside or outside a prior revision."
|
| 341 |
+
)
|
| 342 |
+
parent = start_parent
|
| 343 |
+
_assert_no_interleaved_revision(parent, units[start_unit_idx], units[end_unit_idx], "deletion")
|
| 344 |
+
|
| 345 |
+
now = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 346 |
+
|
| 347 |
+
def _r_text(r: etree._Element) -> str:
|
| 348 |
+
parts = []
|
| 349 |
+
for child in r.xpath("./w:t | ./w:delText"):
|
| 350 |
+
parts.append(child.text or "")
|
| 351 |
+
return "".join(parts)
|
| 352 |
+
|
| 353 |
+
# Collect the deleted text
|
| 354 |
+
deleted_text_parts: List[str] = []
|
| 355 |
+
if start_unit_idx == end_unit_idx:
|
| 356 |
+
deleted_text_parts.append(_r_text(units[start_unit_idx])[start_offset:end_offset])
|
| 357 |
+
else:
|
| 358 |
+
deleted_text_parts.append(_r_text(units[start_unit_idx])[start_offset:])
|
| 359 |
+
for i in range(start_unit_idx + 1, end_unit_idx):
|
| 360 |
+
deleted_text_parts.append(_r_text(units[i]))
|
| 361 |
+
deleted_text_parts.append(_r_text(units[end_unit_idx])[:end_offset])
|
| 362 |
+
deleted_text = "".join(deleted_text_parts)
|
| 363 |
+
|
| 364 |
+
start_r = units[start_unit_idx]
|
| 365 |
+
before_text = _r_text(start_r)[:start_offset]
|
| 366 |
+
after_text = _r_text(units[end_unit_idx])[end_offset:]
|
| 367 |
+
|
| 368 |
+
index = list(parent).index(start_r)
|
| 369 |
+
for i in range(start_unit_idx, end_unit_idx + 1):
|
| 370 |
+
run_elem = units[i]
|
| 371 |
+
if run_elem.getparent() is parent:
|
| 372 |
+
parent.remove(run_elem)
|
| 373 |
+
|
| 374 |
+
insert_idx = index
|
| 375 |
+
|
| 376 |
+
if before_text:
|
| 377 |
+
parent.insert(insert_idx, make_text_run(before_text))
|
| 378 |
+
insert_idx += 1
|
| 379 |
+
|
| 380 |
+
del_elem = make_del_element(deleted_text, author, revision_id, now)
|
| 381 |
+
parent.insert(insert_idx, del_elem)
|
| 382 |
+
insert_idx += 1
|
| 383 |
+
|
| 384 |
+
if after_text:
|
| 385 |
+
parent.insert(insert_idx, make_text_run(after_text))
|
| 386 |
+
|
| 387 |
+
return TrackedDeletion(del_elem, self) # pyright: ignore[reportArgumentType]
|
| 388 |
+
|
| 389 |
+
def replace_tracked(
|
| 390 |
+
self,
|
| 391 |
+
search_text: str,
|
| 392 |
+
replace_text: str,
|
| 393 |
+
author: str = "",
|
| 394 |
+
comment: str | None = None,
|
| 395 |
+
index_mode: IndexMode = "text",
|
| 396 |
+
) -> int:
|
| 397 |
+
"""Replace all occurrences of *search_text* with *replace_text* using track changes.
|
| 398 |
+
|
| 399 |
+
Each replacement creates a tracked deletion of *search_text* and a
|
| 400 |
+
tracked insertion of *replace_text*. Matches text across run
|
| 401 |
+
boundaries (handles OOXML run splitting).
|
| 402 |
+
|
| 403 |
+
Args:
|
| 404 |
+
search_text: Text to find and replace.
|
| 405 |
+
replace_text: Text to insert in place of *search_text*.
|
| 406 |
+
author: Author name for the revision.
|
| 407 |
+
comment: Optional comment text (requires python-docx comment
|
| 408 |
+
support).
|
| 409 |
+
index_mode: Which text view to search against:
|
| 410 |
+
``"text"`` (default, raw ``paragraph.text``),
|
| 411 |
+
``"accepted"`` (``paragraph.accepted_text``, includes prior
|
| 412 |
+
insertions, skips prior deletions), or ``"original"``
|
| 413 |
+
(``paragraph.original_text``, includes prior deletions, skips
|
| 414 |
+
prior insertions).
|
| 415 |
+
|
| 416 |
+
Returns:
|
| 417 |
+
The number of replacements made.
|
| 418 |
+
|
| 419 |
+
Example:
|
| 420 |
+
```python
|
| 421 |
+
# Default: search raw run text
|
| 422 |
+
rp.replace_tracked("old", "new", author="Editor")
|
| 423 |
+
|
| 424 |
+
# Search the accepted view — matches land inside prior w:ins blocks
|
| 425 |
+
rp.replace_tracked(
|
| 426 |
+
"old", "new", author="Editor", index_mode="accepted"
|
| 427 |
+
)
|
| 428 |
+
```
|
| 429 |
+
"""
|
| 430 |
+
count = 0
|
| 431 |
+
full_text = self._view_text(index_mode)
|
| 432 |
+
search_len = len(search_text)
|
| 433 |
+
|
| 434 |
+
# Find all match positions in the concatenated text.
|
| 435 |
+
# Process right-to-left so earlier offsets stay valid after each splice.
|
| 436 |
+
positions: list[int] = []
|
| 437 |
+
start = 0
|
| 438 |
+
while True:
|
| 439 |
+
idx = full_text.find(search_text, start)
|
| 440 |
+
if idx == -1:
|
| 441 |
+
break
|
| 442 |
+
positions.append(idx)
|
| 443 |
+
start = idx + search_len
|
| 444 |
+
|
| 445 |
+
# Apply replacements right-to-left to preserve offsets.
|
| 446 |
+
for pos in reversed(positions):
|
| 447 |
+
self.replace_tracked_at(
|
| 448 |
+
pos, pos + search_len, replace_text, author=author, comment=comment, index_mode=index_mode
|
| 449 |
+
)
|
| 450 |
+
count += 1
|
| 451 |
+
|
| 452 |
+
return count
|
| 453 |
+
|
| 454 |
+
def replace_tracked_at(
|
| 455 |
+
self,
|
| 456 |
+
start: int,
|
| 457 |
+
end: int,
|
| 458 |
+
replace_text: str,
|
| 459 |
+
author: str = "",
|
| 460 |
+
comment: str | None = None,
|
| 461 |
+
index_mode: IndexMode = "text",
|
| 462 |
+
) -> None:
|
| 463 |
+
"""Replace text at character offsets *[start, end)* using track changes.
|
| 464 |
+
|
| 465 |
+
Creates a tracked deletion of the text at positions ``[start, end)``
|
| 466 |
+
and a tracked insertion of *replace_text* at that position.
|
| 467 |
+
|
| 468 |
+
Args:
|
| 469 |
+
start: Starting character offset (0-based, inclusive).
|
| 470 |
+
end: Ending character offset (0-based, exclusive).
|
| 471 |
+
replace_text: Text to insert in place of the deleted text.
|
| 472 |
+
author: Author name for the revision.
|
| 473 |
+
comment: Optional comment text (requires python-docx comment
|
| 474 |
+
support).
|
| 475 |
+
index_mode: Which text view the offsets index into. See
|
| 476 |
+
:meth:`replace_tracked`.
|
| 477 |
+
|
| 478 |
+
Raises:
|
| 479 |
+
ValueError: If *start* or *end* are out of bounds or *start* >= *end*.
|
| 480 |
+
|
| 481 |
+
Example:
|
| 482 |
+
```python
|
| 483 |
+
# Offsets are interpreted against accepted_text
|
| 484 |
+
rp.replace_tracked_at(
|
| 485 |
+
0, 5, "Hi", author="Editor", index_mode="accepted"
|
| 486 |
+
)
|
| 487 |
+
```
|
| 488 |
+
"""
|
| 489 |
+
view_text = self._view_text(index_mode)
|
| 490 |
+
if start < 0 or end > len(view_text) or start >= end:
|
| 491 |
+
raise ValueError(f"Invalid offsets: start={start}, end={end} for text of length {len(view_text)}")
|
| 492 |
+
|
| 493 |
+
units = self._get_editable_units(index_mode)
|
| 494 |
+
if not units:
|
| 495 |
+
raise ValueError("Paragraph has no runs")
|
| 496 |
+
boundaries = self._unit_boundaries(units)
|
| 497 |
+
|
| 498 |
+
start_unit_idx, start_offset_in_unit = self._find_unit_at_offset(boundaries, start)
|
| 499 |
+
end_unit_idx, end_offset_in_unit = self._find_unit_at_offset(boundaries, end)
|
| 500 |
+
# [vendored local fix — see VENDORED.md] Resolve the EXCLUSIVE end offset
|
| 501 |
+
# end-inclusively: an end that lands exactly on a unit boundary belongs to
|
| 502 |
+
# the preceding unit (its last char), not the next unit's start. Without
|
| 503 |
+
# this, a [start, end) span sitting entirely inside one prior revision but
|
| 504 |
+
# ending on that revision's boundary is falsely reported as crossing a
|
| 505 |
+
# revision boundary (blocking in-place edits of counterparty-inserted text).
|
| 506 |
+
if end > start:
|
| 507 |
+
_eu, _eo = self._find_unit_at_offset(boundaries, end - 1)
|
| 508 |
+
end_unit_idx, end_offset_in_unit = _eu, _eo + 1
|
| 509 |
+
|
| 510 |
+
# [vendored local fix — see VENDORED.md] Require EVERY unit in the span to
|
| 511 |
+
# share one parent, not just the first & last: a span that fully contains a
|
| 512 |
+
# counterparty revision (base…w:ins…base) has matching first/last parents
|
| 513 |
+
# but a middle unit under the w:ins, which the removal loop below skips
|
| 514 |
+
# while deleted_text still copies its chars → silent base-text corruption.
|
| 515 |
+
# Raising here converts that into the actionable revision-boundary error
|
| 516 |
+
# (the caller narrows the anchor) instead of a corrupted deliverable.
|
| 517 |
+
start_parent = units[start_unit_idx].getparent()
|
| 518 |
+
if start_parent is None or any(
|
| 519 |
+
units[i].getparent() is not start_parent
|
| 520 |
+
for i in range(start_unit_idx, end_unit_idx + 1)
|
| 521 |
+
):
|
| 522 |
+
raise ValueError(
|
| 523 |
+
"Cannot apply tracked replacement across a revision boundary; "
|
| 524 |
+
"operate on a narrower span entirely inside or outside a prior revision."
|
| 525 |
+
)
|
| 526 |
+
parent = start_parent
|
| 527 |
+
_assert_no_interleaved_revision(parent, units[start_unit_idx], units[end_unit_idx], "replacement")
|
| 528 |
+
|
| 529 |
+
now = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 530 |
+
|
| 531 |
+
def _r_text(r: etree._Element) -> str:
|
| 532 |
+
parts = []
|
| 533 |
+
for child in r.xpath("./w:t | ./w:delText"):
|
| 534 |
+
parts.append(child.text or "")
|
| 535 |
+
return "".join(parts)
|
| 536 |
+
|
| 537 |
+
if start_unit_idx == end_unit_idx:
|
| 538 |
+
r = units[start_unit_idx]
|
| 539 |
+
text = _r_text(r)
|
| 540 |
+
before_text = text[:start_offset_in_unit] or None
|
| 541 |
+
deleted_text = text[start_offset_in_unit:end_offset_in_unit]
|
| 542 |
+
after_text = text[end_offset_in_unit:] or None
|
| 543 |
+
first_r = r
|
| 544 |
+
else:
|
| 545 |
+
first_r = units[start_unit_idx]
|
| 546 |
+
start_text = _r_text(first_r)
|
| 547 |
+
before_text = start_text[:start_offset_in_unit] or None
|
| 548 |
+
deleted_from_start = start_text[start_offset_in_unit:]
|
| 549 |
+
|
| 550 |
+
end_r = units[end_unit_idx]
|
| 551 |
+
end_text = _r_text(end_r)
|
| 552 |
+
deleted_from_end = end_text[:end_offset_in_unit]
|
| 553 |
+
after_text = end_text[end_offset_in_unit:] or None
|
| 554 |
+
|
| 555 |
+
middle_deleted = "".join(_r_text(units[i]) for i in range(start_unit_idx + 1, end_unit_idx))
|
| 556 |
+
deleted_text = deleted_from_start + middle_deleted + deleted_from_end
|
| 557 |
+
|
| 558 |
+
index = list(parent).index(first_r)
|
| 559 |
+
|
| 560 |
+
# Remove spanned runs (only if they share the parent, which the check above guarantees)
|
| 561 |
+
for i in range(start_unit_idx, end_unit_idx + 1):
|
| 562 |
+
run_elem = units[i]
|
| 563 |
+
if run_elem.getparent() is parent:
|
| 564 |
+
parent.remove(run_elem)
|
| 565 |
+
|
| 566 |
+
splice_tracked_replace(
|
| 567 |
+
parent, index, before_text, deleted_text, replace_text, after_text, author, self._next_revision_id, now
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
# ------------------------------------------------------------------
|
| 571 |
+
# Private helpers
|
| 572 |
+
# ------------------------------------------------------------------
|
| 573 |
+
|
| 574 |
+
def _next_revision_id(self) -> int:
|
| 575 |
+
"""Generate the next unique revision ID for this document."""
|
| 576 |
+
return next_revision_id(self._p)
|
| 577 |
+
|
| 578 |
+
def _view_text(self, index_mode: IndexMode) -> str:
|
| 579 |
+
"""Return the paragraph text for the chosen index mode."""
|
| 580 |
+
if index_mode == "text":
|
| 581 |
+
return self.text
|
| 582 |
+
if index_mode == "accepted":
|
| 583 |
+
return self.accepted_text
|
| 584 |
+
if index_mode == "original":
|
| 585 |
+
return self.original_text
|
| 586 |
+
raise ValueError(f"Unknown index_mode: {index_mode!r}")
|
| 587 |
+
|
| 588 |
+
def _get_editable_units(self, index_mode: IndexMode) -> List[etree._Element]:
|
| 589 |
+
"""Return the ordered list of ``w:r`` elements that make up *index_mode*'s view.
|
| 590 |
+
|
| 591 |
+
- ``"text"``: only top-level ``w:r`` children.
|
| 592 |
+
- ``"accepted"``: walk ``w:r`` children, recurse into ``w:ins``
|
| 593 |
+
(prior insertions visible), skip ``w:del``.
|
| 594 |
+
- ``"original"``: walk ``w:r`` children, recurse into ``w:del``
|
| 595 |
+
(prior deletions visible), skip ``w:ins``.
|
| 596 |
+
"""
|
| 597 |
+
if index_mode == "text":
|
| 598 |
+
return list(self._p.xpath("./w:r"))
|
| 599 |
+
|
| 600 |
+
if index_mode == "accepted":
|
| 601 |
+
recurse_tag = qn("w:ins")
|
| 602 |
+
skip_tag = qn("w:del")
|
| 603 |
+
elif index_mode == "original":
|
| 604 |
+
recurse_tag = qn("w:del")
|
| 605 |
+
skip_tag = qn("w:ins")
|
| 606 |
+
else:
|
| 607 |
+
raise ValueError(f"Unknown index_mode: {index_mode!r}")
|
| 608 |
+
|
| 609 |
+
units: List[etree._Element] = []
|
| 610 |
+
|
| 611 |
+
def walk(element: etree._Element) -> None:
|
| 612 |
+
for child in element.xpath("./w:r | ./w:ins | ./w:del"):
|
| 613 |
+
tag = child.tag
|
| 614 |
+
if tag == qn("w:r"):
|
| 615 |
+
units.append(child)
|
| 616 |
+
elif tag == recurse_tag:
|
| 617 |
+
walk(child)
|
| 618 |
+
elif tag == skip_tag:
|
| 619 |
+
continue
|
| 620 |
+
|
| 621 |
+
walk(self._p)
|
| 622 |
+
return units
|
| 623 |
+
|
| 624 |
+
@staticmethod
|
| 625 |
+
def _unit_boundaries(units: List[etree._Element]) -> List[tuple[int, int, int]]:
|
| 626 |
+
"""Return ``(unit_index, start_offset, end_offset)`` for each unit."""
|
| 627 |
+
boundaries: List[tuple[int, int, int]] = []
|
| 628 |
+
offset = 0
|
| 629 |
+
for i, r in enumerate(units):
|
| 630 |
+
# Sum text from both w:t and w:delText direct children
|
| 631 |
+
run_len = 0
|
| 632 |
+
for child in r.xpath("./w:t | ./w:delText"):
|
| 633 |
+
run_len += len(child.text or "")
|
| 634 |
+
boundaries.append((i, offset, offset + run_len))
|
| 635 |
+
offset += run_len
|
| 636 |
+
return boundaries
|
| 637 |
+
|
| 638 |
+
@staticmethod
|
| 639 |
+
def _find_unit_at_offset(boundaries: List[tuple[int, int, int]], offset: int) -> tuple[int, int]:
|
| 640 |
+
"""Find which unit contains *offset* and the offset within that unit."""
|
| 641 |
+
for unit_idx, unit_start, unit_end in boundaries:
|
| 642 |
+
if unit_start <= offset < unit_end or (offset == unit_end and unit_idx == len(boundaries) - 1):
|
| 643 |
+
return unit_idx, offset - unit_start
|
| 644 |
+
last_idx, last_start, _ = boundaries[-1]
|
| 645 |
+
return last_idx, offset - last_start
|
| 646 |
+
|
| 647 |
+
# Back-compat aliases (used by older external code or tests that may import them)
|
| 648 |
+
def _get_run_boundaries(self) -> List[tuple[int, int, int]]:
|
| 649 |
+
"""Deprecated: use :meth:`_get_editable_units` + :meth:`_unit_boundaries`."""
|
| 650 |
+
return self._unit_boundaries(self._get_editable_units("text"))
|
| 651 |
+
|
| 652 |
+
def _find_run_at_offset(self, boundaries: List[tuple[int, int, int]], offset: int) -> tuple[int, int]:
|
| 653 |
+
"""Deprecated: use :meth:`_find_unit_at_offset`."""
|
| 654 |
+
return self._find_unit_at_offset(boundaries, offset)
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/revision.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""TrackedInsertion and TrackedDeletion classes for accessing and manipulating
|
| 2 |
+
tracked changes (revisions) in a Word document.
|
| 3 |
+
|
| 4 |
+
These proxy objects wrap ``w:ins`` and ``w:del`` OXML elements and provide a
|
| 5 |
+
high-level API for reading metadata, extracting text, and accepting or
|
| 6 |
+
rejecting individual revisions.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import datetime as dt
|
| 12 |
+
from typing import TYPE_CHECKING, Iterator, List
|
| 13 |
+
|
| 14 |
+
from docx.oxml.ns import qn
|
| 15 |
+
from docx.shared import Parented
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
import docx.types as t
|
| 19 |
+
from docx.table import Table
|
| 20 |
+
from docx.text.paragraph import Paragraph
|
| 21 |
+
from docx.text.run import Run
|
| 22 |
+
|
| 23 |
+
from docx_revisions.oxml import CT_RunTrackChange
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class TrackedChange(Parented):
|
| 27 |
+
"""Base class for tracked change proxy objects.
|
| 28 |
+
|
| 29 |
+
Provides common functionality for both insertions and deletions.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, element: CT_RunTrackChange, parent: t.ProvidesStoryPart):
|
| 33 |
+
super().__init__(parent)
|
| 34 |
+
self._element = element
|
| 35 |
+
|
| 36 |
+
@property
|
| 37 |
+
def author(self) -> str:
|
| 38 |
+
"""The author who made this change."""
|
| 39 |
+
return self._element.author
|
| 40 |
+
|
| 41 |
+
@author.setter
|
| 42 |
+
def author(self, value: str):
|
| 43 |
+
self._element.author = value
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def date(self) -> dt.datetime | None:
|
| 47 |
+
"""The date/time when this change was made, or None if not recorded."""
|
| 48 |
+
return self._element.date_value
|
| 49 |
+
|
| 50 |
+
@date.setter
|
| 51 |
+
def date(self, value: dt.datetime | None):
|
| 52 |
+
self._element.date_value = value
|
| 53 |
+
|
| 54 |
+
@property
|
| 55 |
+
def revision_id(self) -> int:
|
| 56 |
+
"""The unique identifier for this revision."""
|
| 57 |
+
return self._element.id
|
| 58 |
+
|
| 59 |
+
@revision_id.setter
|
| 60 |
+
def revision_id(self, value: int):
|
| 61 |
+
self._element.id = value
|
| 62 |
+
|
| 63 |
+
# ------------------------------------------------------------------
|
| 64 |
+
# Shared content-access properties
|
| 65 |
+
# ------------------------------------------------------------------
|
| 66 |
+
|
| 67 |
+
@property
|
| 68 |
+
def is_block_level(self) -> bool:
|
| 69 |
+
"""True if this change contains block-level content (paragraphs/tables)."""
|
| 70 |
+
return bool(self._element.inner_content_elements)
|
| 71 |
+
|
| 72 |
+
@property
|
| 73 |
+
def is_run_level(self) -> bool:
|
| 74 |
+
"""True if this change contains run-level content."""
|
| 75 |
+
return bool(self._element.run_content_elements)
|
| 76 |
+
|
| 77 |
+
def iter_inner_content(self) -> Iterator[Paragraph | Table]:
|
| 78 |
+
"""Generate Paragraph or Table objects for block-level content."""
|
| 79 |
+
from docx.table import Table
|
| 80 |
+
from docx.text.paragraph import Paragraph
|
| 81 |
+
|
| 82 |
+
for element in self._element.inner_content_elements:
|
| 83 |
+
tag = element.tag # pyright: ignore[reportUnknownMemberType]
|
| 84 |
+
if tag == qn("w:p"):
|
| 85 |
+
yield Paragraph(element, self._parent) # pyright: ignore[reportArgumentType]
|
| 86 |
+
elif tag == qn("w:tbl"):
|
| 87 |
+
yield Table(element, self._parent) # pyright: ignore[reportArgumentType]
|
| 88 |
+
|
| 89 |
+
def iter_runs(self) -> Iterator[Run]:
|
| 90 |
+
"""Generate Run objects for run-level content."""
|
| 91 |
+
from docx.text.run import Run
|
| 92 |
+
|
| 93 |
+
for r in self._element.run_content_elements:
|
| 94 |
+
yield Run(r, self._parent) # pyright: ignore[reportArgumentType]
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def paragraphs(self) -> List[Paragraph]:
|
| 98 |
+
"""List of paragraphs in this change (for block-level changes)."""
|
| 99 |
+
from docx.text.paragraph import Paragraph
|
| 100 |
+
|
| 101 |
+
return [
|
| 102 |
+
Paragraph(p, self._parent) # pyright: ignore[reportArgumentType]
|
| 103 |
+
for p in self._element.p_lst
|
| 104 |
+
]
|
| 105 |
+
|
| 106 |
+
@property
|
| 107 |
+
def runs(self) -> List[Run]:
|
| 108 |
+
"""List of runs in this change (for run-level changes)."""
|
| 109 |
+
from docx.text.run import Run
|
| 110 |
+
|
| 111 |
+
return [
|
| 112 |
+
Run(r, self._parent) # pyright: ignore[reportArgumentType]
|
| 113 |
+
for r in self._element.r_lst
|
| 114 |
+
]
|
| 115 |
+
|
| 116 |
+
def accept(self) -> None:
|
| 117 |
+
"""Accept this tracked change.
|
| 118 |
+
|
| 119 |
+
For an insertion, this removes the revision wrapper, keeping the content.
|
| 120 |
+
For a deletion, this removes both the wrapper and the content.
|
| 121 |
+
"""
|
| 122 |
+
raise NotImplementedError("Subclasses must implement accept()")
|
| 123 |
+
|
| 124 |
+
def reject(self) -> None:
|
| 125 |
+
"""Reject this tracked change.
|
| 126 |
+
|
| 127 |
+
For an insertion, this removes both the wrapper and the content.
|
| 128 |
+
For a deletion, this removes the revision wrapper, keeping the content.
|
| 129 |
+
"""
|
| 130 |
+
raise NotImplementedError("Subclasses must implement reject()")
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class TrackedInsertion(TrackedChange):
|
| 134 |
+
"""Proxy object wrapping a ``w:ins`` element.
|
| 135 |
+
|
| 136 |
+
Represents content that was inserted while track changes was enabled.
|
| 137 |
+
The inserted content can be paragraphs, tables, or runs depending on
|
| 138 |
+
context.
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
@property
|
| 142 |
+
def text(self) -> str:
|
| 143 |
+
"""The text content of this insertion.
|
| 144 |
+
|
| 145 |
+
For block-level insertions, returns concatenated text of all paragraphs.
|
| 146 |
+
For run-level insertions, returns concatenated text of all runs.
|
| 147 |
+
"""
|
| 148 |
+
if self.is_block_level:
|
| 149 |
+
return "\n".join(p.text for p in self.paragraphs)
|
| 150 |
+
return "".join(r.text for r in self.runs)
|
| 151 |
+
|
| 152 |
+
def accept(self) -> None:
|
| 153 |
+
"""Accept this insertion, keeping the content but removing the revision wrapper."""
|
| 154 |
+
parent = self._element.getparent()
|
| 155 |
+
if parent is None:
|
| 156 |
+
return
|
| 157 |
+
|
| 158 |
+
index = list(parent).index(self._element)
|
| 159 |
+
for child in reversed(list(self._element)):
|
| 160 |
+
parent.insert(index, child)
|
| 161 |
+
|
| 162 |
+
parent.remove(self._element)
|
| 163 |
+
|
| 164 |
+
def reject(self) -> None:
|
| 165 |
+
"""Reject this insertion, removing both the content and the revision wrapper."""
|
| 166 |
+
parent = self._element.getparent()
|
| 167 |
+
if parent is not None:
|
| 168 |
+
_rescue_comment_markers(self._element, parent, list(parent).index(self._element))
|
| 169 |
+
parent.remove(self._element)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _rescue_comment_markers(element, parent, index: int) -> int:
|
| 173 |
+
"""Before removing ``element`` (an accepted deletion or rejected insertion), relocate any
|
| 174 |
+
comment-range markers it contains — ``w:commentRangeStart``/``End`` and any run holding a
|
| 175 |
+
``w:commentReference`` — up to ``parent`` at ``index``, so removing the span does not orphan a
|
| 176 |
+
comment range (leaving an unterminated range that renders with a document-spanning anchor)."""
|
| 177 |
+
marker_tags = (qn("w:commentRangeStart"), qn("w:commentRangeEnd"))
|
| 178 |
+
rescued = []
|
| 179 |
+
for m in list(element.iter()):
|
| 180 |
+
if m is element:
|
| 181 |
+
continue
|
| 182 |
+
if m.tag in marker_tags:
|
| 183 |
+
rescued.append(m)
|
| 184 |
+
elif m.tag == qn("w:r") and m.find(qn("w:commentReference")) is not None:
|
| 185 |
+
rescued.append(m)
|
| 186 |
+
for m in rescued:
|
| 187 |
+
mp = m.getparent()
|
| 188 |
+
if mp is not None:
|
| 189 |
+
mp.remove(m)
|
| 190 |
+
parent.insert(index, m)
|
| 191 |
+
index += 1
|
| 192 |
+
return index
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class TrackedDeletion(TrackedChange):
|
| 196 |
+
"""Proxy object wrapping a ``w:del`` element.
|
| 197 |
+
|
| 198 |
+
Represents content that was deleted while track changes was enabled.
|
| 199 |
+
The deleted content is still present in the document but marked as
|
| 200 |
+
deleted.
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
@property
|
| 204 |
+
def text(self) -> str:
|
| 205 |
+
"""The text content of this deletion.
|
| 206 |
+
|
| 207 |
+
For block-level deletions, returns concatenated text of all paragraphs.
|
| 208 |
+
For run-level deletions, concatenates text from ``w:delText`` elements
|
| 209 |
+
found via xpath, since ``Run.text`` only reads ``w:t``.
|
| 210 |
+
"""
|
| 211 |
+
if self.is_block_level:
|
| 212 |
+
return "\n".join(p.text for p in self.paragraphs)
|
| 213 |
+
# w:del runs use w:delText instead of w:t, so we need xpath
|
| 214 |
+
del_texts = self._element.xpath(".//w:delText")
|
| 215 |
+
if del_texts:
|
| 216 |
+
return "".join(t.text or "" for t in del_texts)
|
| 217 |
+
# Fallback: try normal run text (for cases where w:t is still used)
|
| 218 |
+
return "".join(r.text for r in self.runs)
|
| 219 |
+
|
| 220 |
+
def accept(self) -> None:
|
| 221 |
+
"""Accept this deletion, removing both the content and the revision wrapper."""
|
| 222 |
+
parent = self._element.getparent()
|
| 223 |
+
if parent is not None:
|
| 224 |
+
_rescue_comment_markers(self._element, parent, list(parent).index(self._element))
|
| 225 |
+
parent.remove(self._element)
|
| 226 |
+
|
| 227 |
+
def reject(self) -> None:
|
| 228 |
+
"""Reject this deletion, keeping the content but removing the revision wrapper.
|
| 229 |
+
|
| 230 |
+
Also converts ``w:delText`` elements back to ``w:t`` so the text
|
| 231 |
+
becomes visible again.
|
| 232 |
+
"""
|
| 233 |
+
parent = self._element.getparent()
|
| 234 |
+
if parent is None:
|
| 235 |
+
return
|
| 236 |
+
|
| 237 |
+
# Convert w:delText back to w:t before unwrapping
|
| 238 |
+
for del_text in self._element.xpath(".//w:delText"):
|
| 239 |
+
from docx.oxml.parser import OxmlElement
|
| 240 |
+
|
| 241 |
+
t_elem = OxmlElement("w:t")
|
| 242 |
+
t_elem.text = del_text.text
|
| 243 |
+
space_val = del_text.get(qn("xml:space"))
|
| 244 |
+
if space_val:
|
| 245 |
+
t_elem.set(qn("xml:space"), space_val)
|
| 246 |
+
del_text_parent = del_text.getparent()
|
| 247 |
+
if del_text_parent is not None:
|
| 248 |
+
del_text_parent.replace(del_text, t_elem)
|
| 249 |
+
|
| 250 |
+
index = list(parent).index(self._element)
|
| 251 |
+
for child in reversed(list(self._element)):
|
| 252 |
+
parent.insert(index, child)
|
| 253 |
+
|
| 254 |
+
parent.remove(self._element)
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/docx_revisions/run.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RevisionRun — a ``Run`` subclass with track-change support.
|
| 2 |
+
|
| 3 |
+
Wraps an existing ``Run`` (sharing the same XML element) and adds methods
|
| 4 |
+
for creating tracked deletions and offset-based replacements.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import datetime as dt
|
| 10 |
+
|
| 11 |
+
from docx.oxml.ns import qn
|
| 12 |
+
from docx.oxml.parser import OxmlElement
|
| 13 |
+
from docx.text.run import Run
|
| 14 |
+
|
| 15 |
+
from docx_revisions._helpers import next_revision_id, revision_attrs, splice_tracked_replace
|
| 16 |
+
from docx_revisions.revision import TrackedDeletion
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class RevisionRun(Run):
|
| 20 |
+
"""A ``Run`` subclass that adds track-change support.
|
| 21 |
+
|
| 22 |
+
Create from an existing ``Run`` with ``from_run()`` — the two objects
|
| 23 |
+
share the same underlying XML element.
|
| 24 |
+
|
| 25 |
+
Example:
|
| 26 |
+
```python
|
| 27 |
+
from docx_revisions import RevisionRun
|
| 28 |
+
|
| 29 |
+
run = paragraph.runs[0]
|
| 30 |
+
rr = RevisionRun.from_run(run)
|
| 31 |
+
tracked = rr.delete_tracked(author="Editor")
|
| 32 |
+
```
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
@classmethod
|
| 36 |
+
def from_run(cls, run: Run) -> RevisionRun:
|
| 37 |
+
"""Create a ``RevisionRun`` that shares *run*'s XML element.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
run: An existing ``Run`` object.
|
| 41 |
+
|
| 42 |
+
Returns:
|
| 43 |
+
A ``RevisionRun`` wrapping the same ``<w:r>`` element.
|
| 44 |
+
"""
|
| 45 |
+
return cls(run._r, run._parent)
|
| 46 |
+
|
| 47 |
+
def delete_tracked(self, author: str = "", revision_id: int | None = None) -> TrackedDeletion:
|
| 48 |
+
"""Mark this run as deleted with track changes.
|
| 49 |
+
|
| 50 |
+
Instead of removing the run, it is wrapped in a ``w:del`` element to
|
| 51 |
+
mark it as deleted content. The run remains in the document but is
|
| 52 |
+
displayed as deleted text (e.g., with strikethrough). The ``w:t``
|
| 53 |
+
elements are converted to ``w:delText``.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
author: Author name for the revision.
|
| 57 |
+
revision_id: Unique ID for this revision. Auto-generated if not
|
| 58 |
+
provided.
|
| 59 |
+
|
| 60 |
+
Returns:
|
| 61 |
+
A ``TrackedDeletion`` wrapping the ``w:del`` element.
|
| 62 |
+
|
| 63 |
+
Raises:
|
| 64 |
+
ValueError: If the run has no parent element.
|
| 65 |
+
"""
|
| 66 |
+
if revision_id is None:
|
| 67 |
+
revision_id = self._next_revision_id()
|
| 68 |
+
|
| 69 |
+
parent = self._r.getparent()
|
| 70 |
+
if parent is None:
|
| 71 |
+
raise ValueError("Run has no parent element")
|
| 72 |
+
|
| 73 |
+
del_elem = OxmlElement(
|
| 74 |
+
"w:del",
|
| 75 |
+
attrs=revision_attrs(revision_id, author, dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")),
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
for t_elem in self._r.findall(qn("w:t")):
|
| 79 |
+
delText = OxmlElement("w:delText")
|
| 80 |
+
delText.text = t_elem.text
|
| 81 |
+
if t_elem.get(qn("xml:space")) == "preserve":
|
| 82 |
+
delText.set(qn("xml:space"), "preserve")
|
| 83 |
+
t_elem.getparent().replace(t_elem, delText) # pyright: ignore[reportOptionalMemberAccess]
|
| 84 |
+
|
| 85 |
+
index = list(parent).index(self._r)
|
| 86 |
+
parent.insert(index, del_elem)
|
| 87 |
+
del_elem.append(self._r)
|
| 88 |
+
|
| 89 |
+
return TrackedDeletion(del_elem, self._parent) # pyright: ignore[reportArgumentType]
|
| 90 |
+
|
| 91 |
+
def replace_tracked_at(self, start: int, end: int, replace_text: str, author: str = "") -> None:
|
| 92 |
+
"""Replace text at character offsets *[start, end)* using track changes.
|
| 93 |
+
|
| 94 |
+
Creates a tracked deletion of the text at positions ``[start, end)``
|
| 95 |
+
and a tracked insertion of *replace_text* at that position.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
start: Starting character offset (0-based, inclusive).
|
| 99 |
+
end: Ending character offset (0-based, exclusive).
|
| 100 |
+
replace_text: Text to insert in place of the deleted text.
|
| 101 |
+
author: Author name for the revision.
|
| 102 |
+
|
| 103 |
+
Raises:
|
| 104 |
+
ValueError: If *start* or *end* are out of bounds or *start* >= *end*.
|
| 105 |
+
"""
|
| 106 |
+
text = self.text
|
| 107 |
+
if start < 0 or end > len(text) or start >= end:
|
| 108 |
+
raise ValueError(f"Invalid offsets: start={start}, end={end} for text of length {len(text)}")
|
| 109 |
+
|
| 110 |
+
now = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 111 |
+
before_text = text[:start] or None
|
| 112 |
+
deleted_text = text[start:end]
|
| 113 |
+
after_text = text[end:] or None
|
| 114 |
+
|
| 115 |
+
r_elem = self._r
|
| 116 |
+
parent = r_elem.getparent()
|
| 117 |
+
if parent is None:
|
| 118 |
+
raise ValueError("Run has no parent element")
|
| 119 |
+
|
| 120 |
+
index = list(parent).index(r_elem)
|
| 121 |
+
parent.remove(r_elem)
|
| 122 |
+
|
| 123 |
+
splice_tracked_replace(
|
| 124 |
+
parent, index, before_text, deleted_text, replace_text, after_text, author, self._next_revision_id, now
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
def _next_revision_id(self) -> int:
|
| 128 |
+
"""Generate the next unique revision ID for this document."""
|
| 129 |
+
return next_revision_id(self._r)
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/mark_reserved.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Remove an entire numbered section from a .docx contract, in place,
|
| 3 |
+
replacing it with "Reserved." so downstream numbering stays intact.
|
| 4 |
+
|
| 5 |
+
Usage:
|
| 6 |
+
python mark_reserved.py CONTRACT.docx --start p-031 --end p-035 \
|
| 7 |
+
--comment "We removed the on-site audit section because ..." \
|
| 8 |
+
--author "Jane (AgentCo Legal)"
|
| 9 |
+
|
| 10 |
+
Tracked-deletes the body text of every paragraph from --start through --end
|
| 11 |
+
(inclusive) and tracked-inserts "Reserved." into the first one. Use this for
|
| 12 |
+
whole-section removal instead of propose_edits.py delete ops. Prints a JSON
|
| 13 |
+
result.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import json
|
| 20 |
+
import sys
|
| 21 |
+
from dataclasses import asdict
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 25 |
+
|
| 26 |
+
from redline_engine.document import DocumentView # noqa: E402
|
| 27 |
+
from redline_engine.reserved import mark_paragraph_range_reserved # noqa: E402
|
| 28 |
+
|
| 29 |
+
DEFAULT_AUTHOR = "Counsel"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _lock_docx(docx_path):
|
| 34 |
+
"""Exclusive cross-process lock for a .docx read-modify-write. opencode can fire parallel bash
|
| 35 |
+
calls, so two of these scripts may run at once on the same file; without serialization they collide
|
| 36 |
+
(duplicate comment ids, silently clobbered edits, or a corrupted zip). Hold an flock on a sidecar
|
| 37 |
+
lock file for the whole load->save; the returned handle keeps the lock until this process exits.
|
| 38 |
+
Returns None on platforms without fcntl (e.g. Windows) rather than failing."""
|
| 39 |
+
try:
|
| 40 |
+
import fcntl
|
| 41 |
+
except ImportError:
|
| 42 |
+
return None
|
| 43 |
+
from pathlib import Path as _P
|
| 44 |
+
f = open(str(_P(str(docx_path) + ".lock")), "w")
|
| 45 |
+
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
|
| 46 |
+
return f
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def main() -> int:
|
| 50 |
+
parser = argparse.ArgumentParser(
|
| 51 |
+
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
| 52 |
+
)
|
| 53 |
+
parser.add_argument("docx", help="path to the .docx file (edited in place)")
|
| 54 |
+
parser.add_argument("--start", required=True, help="first paragraph id of the section, e.g. p-031")
|
| 55 |
+
parser.add_argument("--end", required=True, help="last paragraph id of the section, e.g. p-035")
|
| 56 |
+
parser.add_argument("--comment", required=True, help="rationale comment for the removal")
|
| 57 |
+
parser.add_argument("--author", default=DEFAULT_AUTHOR, help="tracked-change author name")
|
| 58 |
+
args = parser.parse_args()
|
| 59 |
+
|
| 60 |
+
path = Path(args.docx)
|
| 61 |
+
if not path.exists():
|
| 62 |
+
print(f"error: file not found: {path}", file=sys.stderr)
|
| 63 |
+
return 1
|
| 64 |
+
|
| 65 |
+
_docx_lock = _lock_docx(path) # noqa: F841 (held until process exit; serializes concurrent writers)
|
| 66 |
+
view = DocumentView.load(path)
|
| 67 |
+
res = mark_paragraph_range_reserved(
|
| 68 |
+
view,
|
| 69 |
+
start_paragraph_id=args.start,
|
| 70 |
+
end_paragraph_id=args.end,
|
| 71 |
+
comment=args.comment,
|
| 72 |
+
author=args.author,
|
| 73 |
+
)
|
| 74 |
+
view._docx.save(str(path)) # noqa: SLF001
|
| 75 |
+
|
| 76 |
+
out = {k: v for k, v in asdict(res).items() if v not in (None, [], "")}
|
| 77 |
+
print(json.dumps(out, indent=2))
|
| 78 |
+
return 0 if out.get("status") == "ok" else 1
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
if __name__ == "__main__":
|
| 82 |
+
sys.exit(main())
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner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|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Apply a batch of tracked-change edits to a .docx contract, in place.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
python propose_edits.py CONTRACT.docx EDITS.json --author "Jane (AgentCo Legal)"
|
| 6 |
+
|
| 7 |
+
EDITS.json is a JSON array of edit objects:
|
| 8 |
+
|
| 9 |
+
[
|
| 10 |
+
{
|
| 11 |
+
"op": "replace", // "replace" | "delete" | "insert_after" | "insert_paragraph_after"
|
| 12 |
+
"anchor": {
|
| 13 |
+
"paragraph_id": "p-027", // strongly recommended
|
| 14 |
+
"text": "ninety (90) days", // verbatim substring of that paragraph
|
| 15 |
+
"context_before": "within ", // optional disambiguators
|
| 16 |
+
"context_after": " after",
|
| 17 |
+
"occurrence": 1 // optional, 1-indexed
|
| 18 |
+
},
|
| 19 |
+
"new_text": "thirty (30) days", // required for replace / insert_after / insert_paragraph_after
|
| 20 |
+
"comment": "We shortened the notice period because ..." // required
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
Ops:
|
| 24 |
+
* "replace" / "delete" — tracked edit WITHIN the anchor paragraph.
|
| 25 |
+
* "insert_after" — insert new text INLINE, right after the anchor
|
| 26 |
+
span, in the SAME paragraph.
|
| 27 |
+
* "insert_paragraph_after" — add a NEW standalone paragraph (a real new
|
| 28 |
+
<w:p>, fully tracked) immediately AFTER the
|
| 29 |
+
anchor paragraph. Use this — not insert_after —
|
| 30 |
+
when a redline must add a new numbered section
|
| 31 |
+
or clause (e.g. "insert as Section 3.5 …");
|
| 32 |
+
insert_after cannot create a new paragraph.
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
Each edit becomes a real Word tracked change (<w:ins>/<w:del>) attributed to
|
| 36 |
+
--author, with the comment attached to the paragraph. Results are printed as
|
| 37 |
+
JSON, one object per edit, in order. Edits are independent: a failed anchor
|
| 38 |
+
does not abort the rest of the batch.
|
| 39 |
+
|
| 40 |
+
Exit code 0 if every edit applied, 1 if any edit failed (inspect the JSON:
|
| 41 |
+
failed edits have status "anchor_failed" or "runtime_error", and ambiguous
|
| 42 |
+
anchors list candidate paragraph IDs).
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
from __future__ import annotations
|
| 46 |
+
|
| 47 |
+
import argparse
|
| 48 |
+
import json
|
| 49 |
+
import sys
|
| 50 |
+
from dataclasses import asdict
|
| 51 |
+
from pathlib import Path
|
| 52 |
+
|
| 53 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 54 |
+
|
| 55 |
+
from redline_engine.document import DocumentView # noqa: E402
|
| 56 |
+
from redline_engine.ops import ( # noqa: E402
|
| 57 |
+
delete_text,
|
| 58 |
+
insert_after_text,
|
| 59 |
+
insert_paragraph_after,
|
| 60 |
+
replace_text,
|
| 61 |
+
resolve_revisions,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
DEFAULT_AUTHOR = "Counsel"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _apply_one(view: DocumentView, edit: dict, author: str) -> dict:
|
| 68 |
+
op = edit.get("op")
|
| 69 |
+
anchor = edit.get("anchor") or {}
|
| 70 |
+
comment = edit.get("comment", "")
|
| 71 |
+
new_text = edit.get("new_text", "")
|
| 72 |
+
if op == "replace":
|
| 73 |
+
res = replace_text(view, anchor=anchor, new_text=new_text, comment=comment, author=author)
|
| 74 |
+
elif op == "delete":
|
| 75 |
+
res = delete_text(view, anchor=anchor, comment=comment, author=author)
|
| 76 |
+
elif op == "insert_after":
|
| 77 |
+
res = insert_after_text(
|
| 78 |
+
view, anchor=anchor, new_text=new_text, comment=comment, author=author
|
| 79 |
+
)
|
| 80 |
+
elif op == "insert_paragraph_after":
|
| 81 |
+
res = insert_paragraph_after(
|
| 82 |
+
view, anchor=anchor, new_text=new_text, comment=comment, author=author
|
| 83 |
+
)
|
| 84 |
+
elif op in ("accept", "reject"):
|
| 85 |
+
rids = edit.get("revision_ids")
|
| 86 |
+
if rids is None and edit.get("revision_id") is not None:
|
| 87 |
+
rids = [edit["revision_id"]]
|
| 88 |
+
res = resolve_revisions(
|
| 89 |
+
view, revision_ids=rids or [], disposition=op, comment=comment, author=author
|
| 90 |
+
)
|
| 91 |
+
else:
|
| 92 |
+
return {"op": str(op), "status": "runtime_error", "error": f"unknown op: {op!r}"}
|
| 93 |
+
return {k: v for k, v in asdict(res).items() if v not in (None, [], "")}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _lock_docx(docx_path):
|
| 98 |
+
"""Exclusive cross-process lock for a .docx read-modify-write. opencode can fire parallel bash
|
| 99 |
+
calls, so two of these scripts may run at once on the same file; without serialization they collide
|
| 100 |
+
(duplicate comment ids, silently clobbered edits, or a corrupted zip). Hold an flock on a sidecar
|
| 101 |
+
lock file for the whole load->save; the returned handle keeps the lock until this process exits.
|
| 102 |
+
Returns None on platforms without fcntl (e.g. Windows) rather than failing."""
|
| 103 |
+
try:
|
| 104 |
+
import fcntl
|
| 105 |
+
except ImportError:
|
| 106 |
+
return None
|
| 107 |
+
from pathlib import Path as _P
|
| 108 |
+
f = open(str(_P(str(docx_path) + ".lock")), "w")
|
| 109 |
+
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
|
| 110 |
+
return f
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def main() -> int:
|
| 114 |
+
parser = argparse.ArgumentParser(
|
| 115 |
+
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
| 116 |
+
)
|
| 117 |
+
parser.add_argument("docx", help="path to the .docx file (edited in place)")
|
| 118 |
+
parser.add_argument("edits", help="path to a JSON file with the edits array, or '-' for stdin")
|
| 119 |
+
parser.add_argument("--author", default=DEFAULT_AUTHOR, help="tracked-change author name")
|
| 120 |
+
args = parser.parse_args()
|
| 121 |
+
|
| 122 |
+
path = Path(args.docx)
|
| 123 |
+
if not path.exists():
|
| 124 |
+
print(f"error: file not found: {path}", file=sys.stderr)
|
| 125 |
+
return 1
|
| 126 |
+
|
| 127 |
+
raw = sys.stdin.read() if args.edits == "-" else Path(args.edits).read_text()
|
| 128 |
+
try:
|
| 129 |
+
edits = json.loads(raw)
|
| 130 |
+
except json.JSONDecodeError as exc:
|
| 131 |
+
print(f"error: edits file is not valid JSON: {exc}", file=sys.stderr)
|
| 132 |
+
return 1
|
| 133 |
+
if not isinstance(edits, list):
|
| 134 |
+
print("error: edits must be a JSON array of edit objects", file=sys.stderr)
|
| 135 |
+
return 1
|
| 136 |
+
|
| 137 |
+
_docx_lock = _lock_docx(path) # noqa: F841 (held until process exit; serializes concurrent writers)
|
| 138 |
+
view = DocumentView.load(path)
|
| 139 |
+
results = []
|
| 140 |
+
for edit in edits:
|
| 141 |
+
if not isinstance(edit, dict):
|
| 142 |
+
results.append(
|
| 143 |
+
{
|
| 144 |
+
"op": "unknown",
|
| 145 |
+
"status": "runtime_error",
|
| 146 |
+
"error": f"each edit must be an object; got {type(edit).__name__}",
|
| 147 |
+
}
|
| 148 |
+
)
|
| 149 |
+
continue
|
| 150 |
+
results.append(_apply_one(view, edit, args.author))
|
| 151 |
+
|
| 152 |
+
view._docx.save(str(path)) # noqa: SLF001 — mirrors the engine's save convention
|
| 153 |
+
|
| 154 |
+
print(json.dumps({"applied_to": str(path), "results": results}, indent=2))
|
| 155 |
+
failed = sum(1 for r in results if r.get("status") != "ok")
|
| 156 |
+
if failed:
|
| 157 |
+
print(f"\n{failed}/{len(results)} edits FAILED — fix anchors and resubmit only those.",
|
| 158 |
+
file=sys.stderr)
|
| 159 |
+
return 1
|
| 160 |
+
return 0
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
if __name__ == "__main__":
|
| 164 |
+
sys.exit(main())
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/read_document.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Print a .docx contract as Markdown with stable paragraph IDs.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
python read_document.py CONTRACT.docx [--max-chars N]
|
| 6 |
+
|
| 7 |
+
Output: a stats line, then the document as Markdown. Each paragraph is
|
| 8 |
+
prefixed with its ID like `[p-027]`. Paragraphs carrying tracked changes or
|
| 9 |
+
comments are flagged, and an appendix lists every existing comment (cmt-N)
|
| 10 |
+
and tracked change (rev-N) with its author and text.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 20 |
+
|
| 21 |
+
from redline_engine.document import DocumentView # noqa: E402
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def main() -> int:
|
| 25 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 26 |
+
parser.add_argument("docx", help="path to the .docx file")
|
| 27 |
+
parser.add_argument(
|
| 28 |
+
"--max-chars",
|
| 29 |
+
type=int,
|
| 30 |
+
default=None,
|
| 31 |
+
help="truncate output after N characters (default: no limit)",
|
| 32 |
+
)
|
| 33 |
+
args = parser.parse_args()
|
| 34 |
+
|
| 35 |
+
path = Path(args.docx)
|
| 36 |
+
if not path.exists():
|
| 37 |
+
print(f"error: file not found: {path}", file=sys.stderr)
|
| 38 |
+
return 1
|
| 39 |
+
|
| 40 |
+
view = DocumentView.load(path)
|
| 41 |
+
stats = view.stats()
|
| 42 |
+
try:
|
| 43 |
+
print(f"# stats: {stats}")
|
| 44 |
+
print(view.to_markdown(max_chars=args.max_chars))
|
| 45 |
+
except BrokenPipeError: # e.g. piped to `head`
|
| 46 |
+
sys.stderr.close()
|
| 47 |
+
return 0
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
sys.exit(main())
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/redline_engine/__init__.py
ADDED
|
File without changes
|
tasks/ip-whithill-hartsong-t1-a/environment/skills/contract-redliner/scripts/redline_engine/anchoring.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
| 3 |
+
The LLM's anchor schema is::
|
| 4 |
+
|
| 5 |
+
{
|
| 6 |
+
"paragraph_id": "p-027", # required when we can; primary key
|
| 7 |
+
"text": "non-exclusive, royalty-free", # exact text to find inside that paragraph
|
| 8 |
+
"context_before": "...", # optional, used to disambiguate when text appears twice
|
| 9 |
+
"context_after": "...", # optional, same purpose
|
| 10 |
+
"occurrence": 1 # optional, 1-indexed, defaults to 1
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
We match against the paragraph's **accepted text** — the text as it reads with
|
| 14 |
+
prior insertions kept and prior deletions removed — so the model can anchor to
|
| 15 |
+
text a counterparty inserted on an earlier turn (a response-turn doc is full of
|
| 16 |
+
such text). We fold smart quotes / dashes / whitespace before matching, but map
|
| 17 |
+
the match back to **exact offsets into the accepted text** so the applied edit
|
| 18 |
+
lands on the real characters (a `normalize`-vs-raw offset skew previously caused
|
| 19 |
+
`Invalid offsets` runtime errors). A fail-loud invariant rejects any anchor whose
|
| 20 |
+
recovered span doesn't fold back to the needle, so a bad map degrades to a clean
|
| 21 |
+
`anchor_failed` rather than a silently mis-placed edit.
|
| 22 |
+
|
| 23 |
+
Resolution reads the **live** paragraph each call (not a load-time snapshot), so
|
| 24 |
+
a batch of edits on one paragraph doesn't drift on stale offsets.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import re
|
| 30 |
+
import unicodedata
|
| 31 |
+
from dataclasses import dataclass
|
| 32 |
+
from typing import Optional
|
| 33 |
+
|
| 34 |
+
from docx_revisions import RevisionParagraph
|
| 35 |
+
|
| 36 |
+
from .document import DocumentView
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Smart quote / dash / whitespace folding. LLMs love re-typing curly quotes
|
| 40 |
+
# slightly differently than the source; this is the most common false-mismatch.
|
| 41 |
+
_QUOTE_MAP = str.maketrans(
|
| 42 |
+
{
|
| 43 |
+
"‘": "'", # left single quote
|
| 44 |
+
"’": "'", # right single quote
|
| 45 |
+
"‚": "'", # single low-9 quote
|
| 46 |
+
"‛": "'", # single high-reversed-9 quote
|
| 47 |
+
"“": '"', # left double quote
|
| 48 |
+
"”": '"', # right double quote
|
| 49 |
+
"„": '"', # double low-9 quote
|
| 50 |
+
"‟": '"', # double high-reversed-9 quote
|
| 51 |
+
"–": "-", # en dash
|
| 52 |
+
"—": "-", # em dash
|
| 53 |
+
"−": "-", # minus sign
|
| 54 |
+
"\xa0": " ", # non-breaking space
|
| 55 |
+
}
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
_WHITESPACE_RE = re.compile(r"\s+")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def normalize(text: str) -> str:
|
| 62 |
+
"""Normalize text for robust matching. Idempotent.
|
| 63 |
+
|
| 64 |
+
NFC → smart-quote/dash fold → whitespace collapse → strip. Used for the
|
| 65 |
+
needle, the context strings, and the fail-loud invariant. `normalize_with_map`
|
| 66 |
+
produces the same output for the haystack but also returns an index map back
|
| 67 |
+
to the raw (accepted-text) offsets.
|
| 68 |
+
"""
|
| 69 |
+
if not text:
|
| 70 |
+
return ""
|
| 71 |
+
text = unicodedata.normalize("NFC", text)
|
| 72 |
+
text = text.translate(_QUOTE_MAP)
|
| 73 |
+
text = _WHITESPACE_RE.sub(" ", text)
|
| 74 |
+
return text.strip()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def normalize_with_map(raw: str) -> tuple[str, list[int]]:
|
| 78 |
+
"""Fold `raw` the same way `normalize` does, but return `(norm, idx_map)`
|
| 79 |
+
where `idx_map[i]` is the index into `raw` of `norm[i]` (and `idx_map[len]`
|
| 80 |
+
is the index one past the last consumed char). This lets a match at
|
| 81 |
+
`norm[s:e]` recover the exact raw span `raw[idx_map[s]:idx_map[e]]`.
|
| 82 |
+
|
| 83 |
+
NFC is deliberately **not** applied here: the offsets must line up with the
|
| 84 |
+
real `accepted_text` the vendored `replace_tracked_at(index_mode="accepted")`
|
| 85 |
+
indexes. `_QUOTE_MAP` is a 1:1 translation (index-preserving); only the
|
| 86 |
+
whitespace collapse is many:1, which the map records. For the NFC-stable
|
| 87 |
+
contract text this yields the same folded string as `normalize`; any residual
|
| 88 |
+
difference is caught by the fail-loud invariant in `resolve`.
|
| 89 |
+
"""
|
| 90 |
+
raw = raw or ""
|
| 91 |
+
translated = raw.translate(_QUOTE_MAP) # 1:1 — indices match `raw`
|
| 92 |
+
out: list[str] = []
|
| 93 |
+
idx: list[int] = []
|
| 94 |
+
pos = 0
|
| 95 |
+
n = len(translated)
|
| 96 |
+
for m in _WHITESPACE_RE.finditer(translated):
|
| 97 |
+
for k in range(pos, m.start()):
|
| 98 |
+
out.append(translated[k])
|
| 99 |
+
idx.append(k)
|
| 100 |
+
out.append(" ")
|
| 101 |
+
idx.append(m.start())
|
| 102 |
+
pos = m.end()
|
| 103 |
+
for k in range(pos, n):
|
| 104 |
+
out.append(translated[k])
|
| 105 |
+
idx.append(k)
|
| 106 |
+
idx.append(n) # sentinel: one past the end
|
| 107 |
+
norm = "".join(out)
|
| 108 |
+
# Replicate `.strip()`: after collapse, boundary whitespace is single spaces.
|
| 109 |
+
lo, hi = 0, len(norm)
|
| 110 |
+
while lo < hi and norm[lo] == " ":
|
| 111 |
+
lo += 1
|
| 112 |
+
while hi > lo and norm[hi - 1] == " ":
|
| 113 |
+
hi -= 1
|
| 114 |
+
return norm[lo:hi], idx[lo:hi] + [idx[hi]]
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@dataclass
|
| 118 |
+
class ResolvedAnchor:
|
| 119 |
+
paragraph_id: str
|
| 120 |
+
# The exact matched substring of the paragraph's accepted text, and its
|
| 121 |
+
# offsets into that accepted text. Ops apply with index_mode="accepted".
|
| 122 |
+
raw_text: str
|
| 123 |
+
start: int
|
| 124 |
+
end: int
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@dataclass
|
| 128 |
+
class AnchorError:
|
| 129 |
+
"""Structured failure that gets handed back to the LLM."""
|
| 130 |
+
|
| 131 |
+
kind: str # "paragraph_not_found" | "text_not_found" | "ambiguous" | "no_paragraph_id"
|
| 132 |
+
message: str
|
| 133 |
+
# For ambiguous matches, list the paragraph IDs that contained the text.
|
| 134 |
+
candidates: list[str] | None = None
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _accepted_text(view: DocumentView, paragraph_id: str) -> Optional[str]:
|
| 138 |
+
"""The LIVE accepted text of a paragraph (insertions kept, deletions removed),
|
| 139 |
+
read fresh from the runtime element so a batch of edits sees prior mutations.
|
| 140 |
+
"""
|
| 141 |
+
para = view.runtime_paragraph(paragraph_id)
|
| 142 |
+
if para is None:
|
| 143 |
+
return None
|
| 144 |
+
return RevisionParagraph.from_paragraph(para).accepted_text
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def resolve(view: DocumentView, anchor: dict) -> ResolvedAnchor | AnchorError:
|
| 148 |
+
"""Resolve an LLM anchor dict to a `ResolvedAnchor` or `AnchorError`."""
|
| 149 |
+
paragraph_id: Optional[str] = anchor.get("paragraph_id")
|
| 150 |
+
text: Optional[str] = anchor.get("text")
|
| 151 |
+
# `occurrence` is explicit (None = let resolver decide; only works when unique).
|
| 152 |
+
occurrence_raw = anchor.get("occurrence")
|
| 153 |
+
occurrence: int | None = int(occurrence_raw) if occurrence_raw is not None else None
|
| 154 |
+
context_before: str = normalize(anchor.get("context_before", "") or "")
|
| 155 |
+
context_after: str = normalize(anchor.get("context_after", "") or "")
|
| 156 |
+
|
| 157 |
+
if not text:
|
| 158 |
+
return AnchorError("text_not_found", "anchor.text is required and must be non-empty")
|
| 159 |
+
|
| 160 |
+
needle = normalize(text)
|
| 161 |
+
if not needle:
|
| 162 |
+
return AnchorError("text_not_found", "anchor.text normalizes to empty")
|
| 163 |
+
|
| 164 |
+
# If paragraph_id is supplied, restrict the search to that paragraph.
|
| 165 |
+
if paragraph_id:
|
| 166 |
+
raw = _accepted_text(view, paragraph_id)
|
| 167 |
+
if raw is None:
|
| 168 |
+
return AnchorError(
|
| 169 |
+
"paragraph_not_found",
|
| 170 |
+
f"no paragraph with id={paragraph_id!r}",
|
| 171 |
+
)
|
| 172 |
+
return _resolve_within_paragraph(
|
| 173 |
+
paragraph_id, raw, text, needle, context_before, context_after, occurrence
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
# No paragraph_id — search the whole doc (live accepted text per paragraph).
|
| 177 |
+
candidates: list[tuple[str, int, int, str]] = []
|
| 178 |
+
for p in view.paragraphs:
|
| 179 |
+
raw = _accepted_text(view, p.id)
|
| 180 |
+
if not raw or not raw.strip():
|
| 181 |
+
continue
|
| 182 |
+
norm, idx_map = normalize_with_map(raw)
|
| 183 |
+
for m in re.finditer(re.escape(needle), norm):
|
| 184 |
+
if _context_matches(norm, m.start(), m.end(), context_before, context_after):
|
| 185 |
+
rs, re_ = idx_map[m.start()], idx_map[m.end()]
|
| 186 |
+
candidates.append((p.id, rs, re_, raw))
|
| 187 |
+
|
| 188 |
+
if not candidates:
|
| 189 |
+
return AnchorError(
|
| 190 |
+
"text_not_found",
|
| 191 |
+
f"text {text!r} not found in any paragraph (after normalization)",
|
| 192 |
+
)
|
| 193 |
+
if len(candidates) > 1:
|
| 194 |
+
if occurrence is None or not (1 <= occurrence <= len(candidates)):
|
| 195 |
+
return AnchorError(
|
| 196 |
+
"ambiguous",
|
| 197 |
+
f"text {text!r} appears {len(candidates)} times; "
|
| 198 |
+
"provide paragraph_id, context_before/after, or occurrence",
|
| 199 |
+
candidates=[c[0] for c in candidates],
|
| 200 |
+
)
|
| 201 |
+
pid, rs, re_, raw = candidates[occurrence - 1]
|
| 202 |
+
else:
|
| 203 |
+
pid, rs, re_, raw = candidates[0]
|
| 204 |
+
return _finalize(pid, raw, rs, re_, needle)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _resolve_within_paragraph(
|
| 208 |
+
paragraph_id: str,
|
| 209 |
+
raw_text: str,
|
| 210 |
+
original_text: str,
|
| 211 |
+
needle: str,
|
| 212 |
+
context_before: str,
|
| 213 |
+
context_after: str,
|
| 214 |
+
occurrence: int | None,
|
| 215 |
+
) -> ResolvedAnchor | AnchorError:
|
| 216 |
+
norm, idx_map = normalize_with_map(raw_text)
|
| 217 |
+
matches: list[tuple[int, int]] = []
|
| 218 |
+
for m in re.finditer(re.escape(needle), norm):
|
| 219 |
+
if _context_matches(norm, m.start(), m.end(), context_before, context_after):
|
| 220 |
+
matches.append((idx_map[m.start()], idx_map[m.end()]))
|
| 221 |
+
if not matches:
|
| 222 |
+
return AnchorError(
|
| 223 |
+
"text_not_found",
|
| 224 |
+
f"text {original_text!r} not found in paragraph {paragraph_id}",
|
| 225 |
+
)
|
| 226 |
+
if len(matches) > 1:
|
| 227 |
+
if occurrence is None or not (1 <= occurrence <= len(matches)):
|
| 228 |
+
return AnchorError(
|
| 229 |
+
"ambiguous",
|
| 230 |
+
f"text {original_text!r} appears {len(matches)} times in {paragraph_id}; "
|
| 231 |
+
"supply occurrence",
|
| 232 |
+
candidates=[paragraph_id],
|
| 233 |
+
)
|
| 234 |
+
rs, re_ = matches[occurrence - 1]
|
| 235 |
+
else:
|
| 236 |
+
rs, re_ = matches[0]
|
| 237 |
+
return _finalize(paragraph_id, raw_text, rs, re_, needle)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _finalize(
|
| 241 |
+
paragraph_id: str, raw: str, start: int, end: int, needle: str
|
| 242 |
+
) -> ResolvedAnchor | AnchorError:
|
| 243 |
+
"""Build a ResolvedAnchor after checking the offset-map invariant."""
|
| 244 |
+
span = raw[start:end]
|
| 245 |
+
if normalize(span) != needle:
|
| 246 |
+
# The index map disagrees with the match — refuse rather than apply an
|
| 247 |
+
# edit to the wrong characters (this is the class of bug that produced
|
| 248 |
+
# `Invalid offsets` / wrong-text deletes).
|
| 249 |
+
return AnchorError(
|
| 250 |
+
"text_not_found",
|
| 251 |
+
f"anchor offset-map invariant failed in {paragraph_id} "
|
| 252 |
+
f"(recovered {span!r} != {needle!r})",
|
| 253 |
+
)
|
| 254 |
+
return ResolvedAnchor(paragraph_id=paragraph_id, raw_text=span, start=start, end=end)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _context_matches(hay: str, start: int, end: int, before: str, after: str) -> bool:
|
| 258 |
+
"""Both context fields are optional; absent → always matches.
|
| 259 |
+
|
| 260 |
+
Boundaries are whitespace-trimmed before comparing: `normalize()` strips
|
| 261 |
+
the context strings, so a context like "at least " must still match even
|
| 262 |
+
though the paragraph has a space between it and the anchored text.
|
| 263 |
+
"""
|
| 264 |
+
if before:
|
| 265 |
+
# The chars immediately before `start` should end with `before`.
|
| 266 |
+
if not hay[:start].rstrip().endswith(before):
|
| 267 |
+
return False
|
| 268 |
+
if after:
|
| 269 |
+
if not hay[end:].lstrip().startswith(after):
|
| 270 |
+
return False
|
| 271 |
+
return True
|