Eric Putnam Claude Opus 5 (1M context) commited on
Commit
3d968d9
·
1 Parent(s): 7d20a0f

feat: deploy simpledocreview as a browser-only static space

Browse files

Upstream is a Python standard-library server, and a Hugging Face Static Space
runs no compute, so app.py cannot run there. The front end ships unchanged and
the server moves into the browser:

- overlay/sdr-api-core.js ports app.py's API: all 18 routes, the rubric
analyzer, DOCX extraction (own ZIP reader plus DecompressionStream, no
dependency), status recalculation, the notification queue, and the record
migrations. No DOM and no storage, so it can be tested against the original.
- overlay/sdr-api-shim.js supplies the environment: IndexedDB, an
XMLHttpRequest interceptor (a Proxy over a real XHR, since upstream uses XHR
rather than fetch), and a capture-phase click handler for Download, which
upstream implements as a navigation a page cannot cancel.
- build-static.ps1 inserts the two script tags into upstream's index.html
instead of keeping a modified copy in overlay/, so there is no second copy of
an upstream file to drift.

The Space is a demo and cannot be more than one: IndexedDB is per-browser, dies
with site data, and may be refused entirely in a partitioned iframe. Someone who
mistook it for a service and ran a real approval round through it would lose the
record with no warning, so the framing is load-bearing - the Space card, a badge
next to the title, and a first-load notice all say so, and a browser test fails
if any of them goes missing.

A hand port of 1,200 lines of Python needs guarding three ways:

- overlay/ported-from.json pins the SHA-256 of app.py and static/app.js; the
build refuses to run until an upstream change has been read and acknowledged.
- tests/parity/ imports the real app.py, replaces its clock and uuid4 with
counters, serves it over HTTP, and replays 67 requests through both
implementations - then diffs every response, the final record store, and the
stored uploads. Sequential timestamps mean the port must call the clock the
same number of times in the same order.
- tests/browser/ drives the built site in headless Chromium over the DevTools
protocol through upload, review, assign, approve, download, and reload.

Both suites run in deploy.ps1 before any push, because a Static Space goes live
the moment the push lands.

Removes style.css from the Space's blank template; the build does not emit it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

.dockerignore ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ .gitattributes
3
+ .gitignore
4
+ .claude
5
+ .build
6
+ scripts
7
+ overlay
8
+ tests
9
+ *.md
10
+ .space-build-manifest
11
+ UPSTREAM.json
12
+
13
+ # The generated site at the repository root. The container serves upstream's own
14
+ # static/ through app.py instead, and the browser-side API must not be present -
15
+ # it would answer /api/ before the real server got the chance.
16
+ index.html
17
+ static
18
+ sdr-api-core.js
19
+ sdr-api-shim.js
20
+
21
+ # Review data from a local run, and Python scratch.
22
+ app/data
23
+ app/uploads
24
+ app/__pycache__
.gitattributes CHANGED
@@ -1,3 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
 
1
+ # Normalize to LF in the repository. The Dockerfile and the files the container
2
+ # executes must not arrive with CRLF, which breaks shell lines inside the image.
3
+ * text=auto eol=lf
4
+
5
+ Dockerfile text eol=lf
6
+ *.sh text eol=lf
7
+ *.py text eol=lf
8
+
9
+ # Keep PowerShell CRLF locally; Windows PowerShell tolerates LF but editors and
10
+ # diffs on Windows are cleaner with CRLF, and these never run in the container.
11
+ *.ps1 text eol=crlf
12
+
13
+ # Parity fixtures are compared byte for byte, and one of the rubric rules counts
14
+ # characters between sentence terminators - so a CRLF checkout would change a
15
+ # finding. Never normalize them.
16
+ tests/parity/corpus/** -text
17
+
18
+ *.png binary
19
+ *.jpg binary
20
+ *.ico binary
21
+ *.woff binary
22
+ *.woff2 binary
23
+ *.docx binary
24
+
25
+ # --- Hugging Face default LFS rules, preserved from the Space's initial commit.
26
+ # Nothing in the current build matches these (the site is html/css/js only), but
27
+ # they matter if large assets are ever added.
28
  *.7z filter=lfs diff=lfs merge=lfs -text
29
  *.arrow filter=lfs diff=lfs merge=lfs -text
30
  *.bin filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Build scratch (staged site before it is copied to the repository root)
2
+ .build/
3
+
4
+ # Generated test fixtures: binary DOCX archives and encoding-specific files that
5
+ # reference.py writes before each parity run. Regenerated, never reviewed.
6
+ tests/parity/.corpus/
7
+
8
+ # A local `python app.py` run inside app/ would create these. Review data is a
9
+ # user's documents; it must never reach a public Space.
10
+ app/data/
11
+ app/uploads/
12
+ app/__pycache__/
13
+ __pycache__/
14
+ *.pyc
15
+
16
+ # Logs and env
17
+ *.log
18
+ .env
19
+ .env.local
20
+ .env.*.local
21
+
22
+ # Editors / OS
23
+ .DS_Store
24
+ Thumbs.db
25
+ .vscode/
26
+ .idea/
27
+ *.swp
28
+
29
+ # Claude Code (personal overrides - not for team)
30
+ .claude/settings.local.json
31
+
32
+ # NOTE: the generated site (index.html, static/, sdr-api-core.js,
33
+ # sdr-api-shim.js) IS committed on purpose - a Static Space serves the repository
34
+ # root directly. The generated paths are listed in .space-build-manifest.
.space-build-manifest ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Generated by scripts/build-static.ps1 - do not edit.
2
+ # Top-level repository paths that are build output, deleted and rewritten
3
+ # on each build.
4
+ index.html
5
+ sdr-api-core.js
6
+ sdr-api-shim.js
7
+ static
CLAUDE.md ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CLAUDE.md
2
+
3
+ Guidance for Claude Code when working in this repository.
4
+
5
+ ## What this repo is
6
+
7
+ The Hugging Face Space **deployment repo** for SimpleDocReview — a local-first
8
+ document review tool built on the Python standard library. It contains no
9
+ application logic. Its job is to take the upstream app, make it run without a
10
+ server, and push it to a Static Space.
11
+
12
+ Upstream lives at `C:\dev\SimpleDocReview`
13
+ (https://github.com/eputnam77/SimpleDocReview).
14
+
15
+ Two naming traps:
16
+
17
+ - The repo name is a historical artifact. This Space runs **no Streamlit and no
18
+ Python**. It is named after its sibling `dep-streamlit`, which is itself named
19
+ after `fsv-streamlit`, which is the only one that actually uses Streamlit.
20
+ - The `Dockerfile` is **not** what the Space uses. The Space is `sdk: static`,
21
+ because creating Docker Spaces requires a paid HF plan. The Dockerfile runs
22
+ upstream unmodified, for local use and as the paid-plan escape hatch.
23
+
24
+ ## The one thing to keep straight
25
+
26
+ **The Space is a demo and cannot be anything else.** A Static Space runs no
27
+ code, so `app.py` does not run and there is no server-side storage. The API is
28
+ reimplemented in JavaScript and stores records in the visitor's IndexedDB, which
29
+ means:
30
+
31
+ - records are per-browser, so a second reviewer sees an empty workspace;
32
+ - records die with the browser's site data, and there is no export;
33
+ - in an iframe with partitioned storage, records last only for the visit.
34
+
35
+ Someone who mistakes it for a service and runs a real approval round through it
36
+ loses the record with no warning. That is the one harm this deployment can cause,
37
+ so the demo framing is load-bearing, not decoration. It appears in three places
38
+ and all three must stay accurate:
39
+
40
+ 1. `README.md` — the Space card, including a table of what the demo is not
41
+ 2. the "Demo" badge `sdr-api-shim.js` injects next to the title, which never
42
+ goes away
43
+ 3. the first-load notice, which names where the data lives and links to upstream
44
+
45
+ Do not weaken, hide, or make dismissible-forever any of the three. Do not add
46
+ features that imply durability (export-all, share links, "saved" indicators)
47
+ without solving storage first, which a Static Space cannot.
48
+
49
+ ## Layout
50
+
51
+ ```
52
+ README.md Space card (sdk: static) - front matter is load-bearing
53
+ DEPLOY.md Deployment runbook and troubleshooting
54
+ Dockerfile NOT used by the Space; local run / paid-plan option
55
+ UPSTREAM.json Generated: which upstream commit is deployed
56
+ .space-build-manifest Generated: which root paths are build output
57
+ app/ Vendored upstream - GENERATED, never hand-edit
58
+ overlay/ The browser-side server - hand-maintained
59
+ sdr-api-core.js app.py's API ported to JavaScript (no DOM, no storage)
60
+ sdr-api-shim.js IndexedDB, XHR interception, download, demo notice
61
+ ported-from.json Upstream hashes the port was reviewed against
62
+ scripts/
63
+ sync-upstream.ps1 Mirror local upstream checkout -> app/
64
+ build-static.ps1 app/ + overlay/ -> .build/out -> repo root
65
+ deploy.ps1 sync + build + test + commit + push to hf
66
+ tests/
67
+ parity/ Replay one workflow through app.py and the port, diff
68
+ browser/ Drive the built site in headless Chromium
69
+ .build/ Gitignored scratch
70
+ index.html, static/, ... Generated site at the repo root - COMMITTED on purpose
71
+ ```
72
+
73
+ ## Hard rules
74
+
75
+ - **Never edit anything under `app/`.** It is a `robocopy /MIR` mirror; edits are
76
+ destroyed on the next sync and silently diverge the Space from upstream. Fix
77
+ upstream, then re-run `scripts\sync-upstream.ps1`.
78
+ - **Never hand-edit the generated site at the repo root** (`index.html`,
79
+ `static/`, `sdr-api-*.js`). `build-static.ps1` deletes and rewrites everything
80
+ named in `.space-build-manifest`.
81
+ - **Never hand-edit `UPSTREAM.json` or `.space-build-manifest`.** Both are generated.
82
+ - **Keep `overlay/` additive.** It must contain no copy of an upstream file. The
83
+ script tags it needs are *inserted* into upstream's `index.html` at build time
84
+ precisely so there is no second copy of that file to rot.
85
+ - **Review logic changes belong upstream, then in the port.** Both, in that
86
+ order. Changing only `sdr-api-core.js` makes the Space lie about what the tool
87
+ does.
88
+ - Application behavior changes belong upstream. Only build tooling, the Space
89
+ card, the overlay, and the tests belong here.
90
+
91
+ ## Commands
92
+
93
+ ```powershell
94
+ .\scripts\sync-upstream.ps1 # refresh app/ from C:\dev\SimpleDocReview
95
+ .\scripts\build-static.ps1 # build the site into the repo root
96
+ node tests\parity\run-parity.mjs # diff the port against the real app.py
97
+ node tests\browser\run-browser-check.mjs # drive the built site in a browser
98
+ python -m http.server 8000 # preview at http://localhost:8000
99
+ .\scripts\deploy.ps1 -DryRun # show what would ship
100
+ .\scripts\deploy.ps1 # sync, build, test, commit, push to hf
101
+ ```
102
+
103
+ ## Remotes
104
+
105
+ - `origin` → GitHub mirror of this deployment repo
106
+ - `hf` → the Hugging Face Space (added manually; see DEPLOY.md)
107
+
108
+ `deploy.ps1` pushes to `hf` by default and to `origin` only with `-AlsoPushOrigin`.
109
+
110
+ ## The port, and why it is guarded three ways
111
+
112
+ `overlay/sdr-api-core.js` reimplements `app.py`. A copy-and-inject build would
113
+ not notice if the two diverged, so:
114
+
115
+ - **`overlay/ported-from.json`** pins the SHA-256 of `app.py` and
116
+ `static/app.js`. `build-static.ps1` refuses to build when either changes.
117
+ Read the upstream diff, carry the change into the port, re-run the tests, then
118
+ `.\scripts\build-static.ps1 -AcceptUpstreamChanges`. Do not acknowledge a
119
+ change you have not read.
120
+ - **`tests/parity/`** imports the real `app.py`, replaces its clock and `uuid4`
121
+ with counters, serves it over HTTP, and replays 67 requests through both
122
+ implementations — then diffs every response, the final record store, and the
123
+ stored uploads. Sequential timestamps mean the port must *call* the clock the
124
+ same number of times in the same order, so a missing `utc_now()` fails rather
125
+ than hiding. One divergence is accepted and printed on every run (see the
126
+ `ACCEPTED_DIVERGENCES` list and its stated reason).
127
+ - **`tests/browser/`** covers what parity cannot: the inserted script tags, the
128
+ XHR interception upstream actually goes through, IndexedDB across a reload, and
129
+ the download click.
130
+
131
+ When editing the port, keep the comments that name the `app.py` function each
132
+ part mirrors. They are how the next reader checks the port against the original.
133
+
134
+ ## Build constraints worth remembering
135
+
136
+ - **The overlay must load before `app.js`,** which fires three requests as soon
137
+ as it is parsed. `sdr-api-core.js` must come before `sdr-api-shim.js`.
138
+ - **Requests are intercepted at `XMLHttpRequest`,** because that is what upstream
139
+ uses. The interceptor is a `Proxy` over a real XHR so unsimulated members still
140
+ work. `fetch` is covered defensively.
141
+ - **Download is a click interception, not a request interception.** Upstream
142
+ assigns `window.location.href`, which a page cannot cancel. The capture-phase
143
+ listener runs before upstream's own handler and serves a blob URL instead. The
144
+ document id comes from tracking API traffic, because the click does not carry
145
+ it.
146
+ - **DOCX extraction has no dependency:** the port reads the ZIP central
147
+ directory itself and inflates with `DecompressionStream`. ZIP64 and unusual
148
+ compression methods are rejected with a clear message rather than guessed at.
149
+ - **The site must sit at the repo root**, not a subdirectory — HF serves the
150
+ repository root as the web root and upstream's `index.html` uses absolute asset
151
+ paths (`/static/styles.css`).
152
+ - **Storage may be refused.** In a partitioned iframe the shim falls back to an
153
+ in-memory store for the visit and the notice says so. Do not remove that path.
154
+
155
+ ## Known divergences from upstream
156
+
157
+ Small, deliberate, and worth not rediscovering:
158
+
159
+ - **`.docx` download Content-Type.** `app.py` asks `mimetypes.guess_type`, which
160
+ on Windows consults the registry and can answer `application/octet-stream`.
161
+ The port always sends the real OOXML type.
162
+ - **cp1252 decoding.** WHATWG `windows-1252` maps the five bytes Python's cp1252
163
+ rejects, so a file Python would fall through to replacement-character UTF-8
164
+ decodes as cp1252 here.
165
+ - **XML entity unescaping** covers what WordprocessingML emits, not the full
166
+ HTML5 named-entity list `html.unescape` knows.
167
+ - **The 5 MB upload ceiling** is measured against the file. `app.py` measures
168
+ `Content-Length`, which also covers the multipart part headers, so the port is
169
+ marginally more permissive within a few hundred bytes of the limit.
170
+
171
+ Each is commented at the code that causes it. Add to this list rather than
172
+ letting a fourth one go unrecorded.
173
+
174
+ ## Conventions
175
+
176
+ - Commit style: Conventional Commits. Sync commits are
177
+ `chore: sync simpledocreview @ <sha>`.
178
+ - PowerShell for tooling, Node for tests — this repo is developed on Windows and
179
+ the tests need a JavaScript runtime anyway.
180
+ - The overlay is written in ES5-flavoured JavaScript with `var` and no build
181
+ step, matching upstream's own front end. Keep it that way; there is no
182
+ transpiler here.
DEPLOY.md ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Deploying to Hugging Face
2
+
3
+ This repo deploys [SimpleDocReview](https://github.com/eputnam77/SimpleDocReview)
4
+ to a Hugging Face **Static** Space as a browser-only demo. It holds no
5
+ application logic of its own — only the build tooling, the Space card, a vendored
6
+ copy of upstream in `app/`, the browser-side API in `overlay/`, and the generated
7
+ site at the repository root.
8
+
9
+ ## Why static
10
+
11
+ Per Hugging Face's own docs, [Static Spaces][static-docs] are free for everyone —
12
+ "served directly without running on compute, so unlike Gradio and Docker Spaces,
13
+ creating them never requires a paid plan."
14
+
15
+ Upstream is a good fit in one respect and a poor fit in another, and both matter:
16
+
17
+ - **Good fit:** the front end is plain HTML, CSS, and JavaScript with no build
18
+ step, no framework, and no bundler. It is served byte-for-byte as upstream
19
+ wrote it.
20
+ - **Poor fit:** upstream is a *server*. `app.py` owns the review logic and the
21
+ storage. A Static Space cannot run it, so the API is reimplemented in the
22
+ browser and the storage becomes IndexedDB.
23
+
24
+ That second point is the whole design constraint of this repository, and it is
25
+ why the Space is a demo. See [What the demo cannot be](#what-the-demo-cannot-be).
26
+
27
+ [static-docs]: https://huggingface.co/docs/hub/spaces-sdks-static
28
+
29
+ ## The everyday workflow
30
+
31
+ After you change something in `C:\dev\SimpleDocReview` and commit it there:
32
+
33
+ ```powershell
34
+ cd C:\dev\sdr-streamlit
35
+ .\scripts\deploy.ps1
36
+ ```
37
+
38
+ That syncs `app/`, builds the site into the repository root, commits with the
39
+ upstream commit in the message, and pushes to `hf`. Because a Static Space serves
40
+ files directly, the update is live as soon as the push lands.
41
+
42
+ To see what would change without committing:
43
+
44
+ ```powershell
45
+ .\scripts\deploy.ps1 -DryRun
46
+ ```
47
+
48
+ Individual steps, when you want them:
49
+
50
+ ```powershell
51
+ .\scripts\sync-upstream.ps1 # refresh app/ from the local upstream checkout
52
+ .\scripts\build-static.ps1 # build the site into the repository root
53
+ node tests\parity\run-parity.mjs # diff the browser API against the real app.py
54
+ node tests\browser\run-browser-check.mjs # drive the built site in headless Chromium
55
+ python -m http.server 8000 # preview at http://localhost:8000
56
+ ```
57
+
58
+ ### Useful flags
59
+
60
+ | Flag | Effect |
61
+ | --- | --- |
62
+ | `-Message "feat: ..."` | Custom commit message |
63
+ | `-AlsoPushOrigin` | Also push to the GitHub mirror of this repo |
64
+ | `-UpstreamPath D:\other\checkout` | Sync from a different checkout |
65
+ | `-AllowDirty` | Deploy from an uncommitted upstream working tree |
66
+ | `-SkipSync` | Build and deploy `app/` as it stands, no re-mirror |
67
+ | `-SkipBuild` | Commit and push the existing site, no rebuild |
68
+ | `-SkipTests` | Skip the parity and browser checks (they run by default) |
69
+ | `-DryRun` | Show the plan, change nothing |
70
+
71
+ By default a dirty upstream working tree is an **error**, because `UPSTREAM.json`
72
+ would otherwise record a commit that does not describe what actually shipped.
73
+ Commit upstream first, or opt in with `-AllowDirty`.
74
+
75
+ ## First-time setup
76
+
77
+ 1. Create the Space at https://huggingface.co/new-space — choose the **Static**
78
+ SDK and the **Blank** template. Name it `SimpleDocReview`.
79
+
80
+ 2. Add it as a remote:
81
+
82
+ ```powershell
83
+ git remote add hf https://huggingface.co/spaces/Hoctar77/SimpleDocReview
84
+ ```
85
+
86
+ 3. Authenticate. Use a Hugging Face access token with **write** scope from
87
+ https://huggingface.co/settings/tokens as the password when git prompts, or
88
+ store it once:
89
+
90
+ ```powershell
91
+ git config credential.helper manager
92
+ ```
93
+
94
+ 4. Build and push:
95
+
96
+ ```powershell
97
+ .\scripts\deploy.ps1 -AlsoPushOrigin
98
+ ```
99
+
100
+ A blank Space starts with its own initial commit, so the first push may be
101
+ rejected as non-fast-forward. Reconcile once:
102
+
103
+ ```powershell
104
+ git pull --rebase hf main
105
+ git push hf main
106
+ ```
107
+
108
+ ## How the build works
109
+
110
+ ```
111
+ app/ clean upstream mirror (generated by sync-upstream.ps1)
112
+ overlay/ the browser-side API (hand-maintained)
113
+ |
114
+ v copy + insert two <script> tags into index.html
115
+ .build/out/
116
+ |
117
+ v copied to the repository root
118
+ index.html, static/, sdr-api-core.js, sdr-api-shim.js (committed; HF serves these)
119
+ ```
120
+
121
+ There is no compiler and no package manager. `build-static.ps1` copies
122
+ `app/static/index.html` to the site root, copies the rest of `app/static/` to
123
+ `/static/`, copies the two overlay scripts, and inserts their `<script>` tags
124
+ immediately before upstream's `app.js` tag.
125
+
126
+ The repository root is the web root, which is why the site lives there rather
127
+ than in a subdirectory — `index.html` asks for `/static/styles.css` by absolute
128
+ path.
129
+
130
+ Everything the build emits is recorded in `.space-build-manifest` and deleted
131
+ before the next copy, so nothing stale accumulates. The cleanup refuses to touch
132
+ a protected list (`README.md`, `app/`, `scripts/`, …) even if the manifest
133
+ somehow named one.
134
+
135
+ ### Why the script tags are inserted rather than committed
136
+
137
+ The overlay has to load before `app.js`, which fires its first three requests as
138
+ soon as it is parsed. The alternative — keeping a modified `index.html` in
139
+ `overlay/` — would mean a second copy of an upstream file that silently rots
140
+ every time upstream edits its markup. Inserting a tag is a *transform* of
141
+ upstream's HTML, so there is nothing to drift.
142
+
143
+ `build-static.ps1` fails loudly if it cannot find upstream's `app.js` tag, rather
144
+ than shipping a page where the overlay never loads.
145
+
146
+ ## The browser-side API
147
+
148
+ `overlay/sdr-api-core.js` is a port of `app.py`: every route, the rubric
149
+ analyzer, the DOCX text extractor, the status recalculation, the notification
150
+ queue, and the record migrations. `overlay/sdr-api-shim.js` supplies what a
151
+ browser has and Python does not — IndexedDB, an `XMLHttpRequest` interceptor, and
152
+ a click handler for the Download button.
153
+
154
+ Three things in that split are worth knowing:
155
+
156
+ - **Requests are intercepted at `XMLHttpRequest`,** not `fetch`, because that is
157
+ what upstream's `app.js` uses. The interceptor is a `Proxy` over a real
158
+ `XMLHttpRequest`, so anything the shim does not simulate still reaches the
159
+ genuine object. `fetch` is covered too, defensively, in case upstream migrates.
160
+ - **Download is a click interception, not a request interception.** Upstream
161
+ navigates: `window.location.href = "/api/documents/<id>/download"`. A page
162
+ cannot cancel that assignment, so the click is caught in the capture phase
163
+ before upstream's own handler runs, and the file is handed over as a blob URL.
164
+ The shim tracks which document is on screen from the API traffic, because the
165
+ click event does not carry the id.
166
+ - **DOCX extraction has no dependency.** `app.py` uses `zipfile`; the port reads
167
+ the ZIP central directory itself and inflates with `DecompressionStream`,
168
+ which every current browser has. ZIP64 is rejected rather than guessed at.
169
+
170
+ ### Keeping the port honest
171
+
172
+ A port that silently diverges from the server it mirrors is worse than no port,
173
+ so three things guard it.
174
+
175
+ **A hash guard.** `overlay/ported-from.json` records the SHA-256 of `app.py` and
176
+ `static/app.js` as of the last time the port was reviewed.
177
+ `build-static.ps1` refuses to build when either changes:
178
+
179
+ ```
180
+ Upstream changed in files the overlay reimplements: app.py
181
+ ```
182
+
183
+ Read the upstream diff, carry any behavior change into `sdr-api-core.js`, re-run
184
+ the tests, then acknowledge it:
185
+
186
+ ```powershell
187
+ .\scripts\build-static.ps1 -AcceptUpstreamChanges
188
+ ```
189
+
190
+ This is deliberately annoying. An upstream change to a rubric rule or a status
191
+ transition will not reach the Space on its own, and nothing else in a
192
+ copy-and-inject build would notice.
193
+
194
+ **A parity test.** `tests/parity/` replays a 67-request workflow through the real
195
+ `app.py` — imported from `app/`, behind a real HTTP server, with its clock and
196
+ `uuid4` replaced by counters — and through the JavaScript port in Node, then
197
+ diffs every response, the final record store, and the list of stored uploads.
198
+ Making the clock sequential means the port has to *call* it the same number of
199
+ times in the same order, so a missing timestamp is a failure rather than a value
200
+ nobody compares.
201
+
202
+ One divergence is accepted and printed on every run: `mimetypes.guess_type`
203
+ returns `application/octet-stream` for `.docx` on a Windows machine with no
204
+ Office mapping, where the port always sends the real OOXML type.
205
+
206
+ **A browser test.** `tests/browser/` serves the repository root, opens it in
207
+ headless Chromium via the DevTools protocol, and runs upload → review → assign →
208
+ approve → download → reload through the real UI. That covers what the parity test
209
+ cannot: the inserted script tags, the XHR interception, IndexedDB persistence
210
+ across a reload, and the download click.
211
+
212
+ ## What the demo cannot be
213
+
214
+ Storage is the constraint, and it is not fixable inside a Static Space:
215
+
216
+ - **Records are per-browser.** IndexedDB is scoped to one origin in one browser
217
+ profile. A reviewer opening the same URL sees an empty workspace, so a real
218
+ multi-person approval round cannot happen here.
219
+ - **Records are disposable.** Clearing site data deletes them, with no export
220
+ other than downloading the original files one at a time.
221
+ - **Records may not persist at all.** The Space renders in an iframe on
222
+ huggingface.co, and a browser that partitions or blocks storage for embedded
223
+ third parties leaves the shim with an in-memory store for the length of the
224
+ visit. It says so in the notice when that happens.
225
+
226
+ The Space says all of this in three places: the Space card, a badge next to the
227
+ title that does not go away, and a dismissible notice on first load. Keep them
228
+ accurate. Someone who mistakes this for a service and runs a real approval round
229
+ through it loses the record with no warning, and that is the one failure mode
230
+ this deployment can actually cause.
231
+
232
+ If you need the Space to be the real thing, it needs to run `app.py`, which
233
+ means the Docker SDK on a paid plan — and even then, a Space's filesystem is
234
+ ephemeral, so `data/reviews.json` and `uploads/` would need a persistent volume
235
+ or an external store. The `Dockerfile` here runs upstream unmodified for local
236
+ use and as that starting point; the Space does not use it.
237
+
238
+ ## Troubleshooting
239
+
240
+ | Symptom | Cause and fix |
241
+ | --- | --- |
242
+ | Space shows a directory listing or 404 | `app_file: index.html` must be in the front matter and `index.html` must exist at the repo root. Re-run `build-static.ps1`. |
243
+ | The page loads but stays empty, console shows 404s for `/api/...` | The overlay did not load. Confirm both `<script>` tags are in the deployed `index.html`, before `app.js`. |
244
+ | `sdr-api-core.js did not load` in the console | The tags are in the wrong order. `sdr-api-core.js` must come first. |
245
+ | Build fails: "Upstream changed in files the overlay reimplements" | Working as intended. Review the upstream diff, update the overlay, then `-AcceptUpstreamChanges`. |
246
+ | Build fails: "Could not find upstream's app.js script tag" | Upstream changed its markup. Update the anchor in `build-static.ps1`. |
247
+ | Parity test fails after an upstream change | The port no longer matches `app.py`. The diff output names the exact field. |
248
+ | Browser test cannot find a browser | Set `BROWSER` to a `chrome.exe` or `msedge.exe` path. |
249
+ | Documents vanish between visits | Expected on a demo. See [What the demo cannot be](#what-the-demo-cannot-be). |
250
+ | Uploading a DOCX fails with "appears to be invalid" | The port rejects ZIP64 archives and unsupported compression methods. Re-save the file from Word. |
251
+ | Push rejected, non-fast-forward | The Space has commits this repo lacks: `git pull --rebase hf main`. |
252
+ | `robocopy` exit code 8 or higher | A real copy failure — a file was locked. Close anything watching `app/` or `.build/` and re-run. |
Dockerfile ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NOT used by the Hugging Face Space.
2
+ #
3
+ # The Space is `sdk: static` (see README.md's front matter), because creating a
4
+ # Docker Space requires a paid Hugging Face plan. This file exists for two
5
+ # reasons:
6
+ #
7
+ # 1. running upstream unmodified in a container locally, where app.py serves
8
+ # the real API and the browser overlay is not involved at all;
9
+ # 2. as the starting point if this ever moves to a paid plan.
10
+ #
11
+ # Read the caveat before reaching for reason 2: a Space's filesystem is
12
+ # ephemeral. Upstream stores documents in uploads/ and review records in
13
+ # data/reviews.json, so a restarted container starts empty. Making the Space a
14
+ # real review system needs a persistent volume or an external store, not just
15
+ # this Dockerfile.
16
+ #
17
+ # Upstream needs no third-party packages, so there is nothing to install.
18
+
19
+ FROM python:3.13-slim
20
+
21
+ # Hugging Face Spaces run as uid 1000 and expect the app on port 7860.
22
+ RUN useradd --create-home --uid 1000 app
23
+ USER app
24
+ WORKDIR /home/app
25
+
26
+ # The vendored upstream mirror, exactly as sync-upstream.ps1 left it. Nothing
27
+ # from overlay/ is copied: in a container the real server answers /api/, and the
28
+ # browser-side reimplementation would be a second, conflicting answer.
29
+ COPY --chown=app:app app/ ./
30
+
31
+ # Written at runtime by app.py's ensure_storage(), and ephemeral in a Space.
32
+ RUN mkdir -p data uploads
33
+
34
+ EXPOSE 7860
35
+
36
+ # app.py's run() defaults to 127.0.0.1:4173, which is unreachable from outside a
37
+ # container, so host and port are passed explicitly. sync-upstream.ps1 warns if
38
+ # upstream ever changes that signature.
39
+ CMD ["python", "-c", "import app; app.run('0.0.0.0', 7860)"]
README.md CHANGED
@@ -1,10 +1,124 @@
1
  ---
2
  title: SimpleDocReview
3
- emoji: 🐠
4
- colorFrom: pink
5
- colorTo: red
6
  sdk: static
 
7
  pinned: false
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: SimpleDocReview
3
+ emoji: "📄"
4
+ colorFrom: blue
5
+ colorTo: gray
6
  sdk: static
7
+ app_file: index.html
8
  pinned: false
9
+ short_description: Browser-only demo of a local-first document review workflow
10
  ---
11
 
12
+ # SimpleDocReview (demo)
13
+
14
+ Upload a `.txt`, `.md`, or `.docx` file, run a local quality review, assign
15
+ reviewers, collect comments and change requests, and record approvals — the full
16
+ [SimpleDocReview](https://github.com/eputnam77/SimpleDocReview) workflow, with
17
+ nothing to install.
18
+
19
+ ## This is a demo, not a review system
20
+
21
+ SimpleDocReview is a local-first tool: you run a small Python server on your own
22
+ machine and your documents stay on your disk. This Space is a **Static Space**,
23
+ which means Hugging Face serves files and runs no code at all — so there is no
24
+ Python server here, and no server-side storage.
25
+
26
+ Instead, the server's API is reimplemented in JavaScript and runs in your
27
+ browser. That makes the demo complete and private, and it also makes it
28
+ disposable:
29
+
30
+ | | Demo Space | Running it locally |
31
+ | --- | --- | --- |
32
+ | Where documents go | Your browser's IndexedDB | `uploads/` on your disk |
33
+ | Where review records go | Your browser's IndexedDB | `data/reviews.json` |
34
+ | Who else can see them | Nobody — they never leave the browser | Nobody |
35
+ | Survives clearing site data | No | Yes |
36
+ | Survives a different browser or device | No | n/a |
37
+ | Suitable for real approval rounds | **No** | Yes |
38
+
39
+ Use it to see what the tool does. Do not use it to hold a review you need to
40
+ keep: clear your site data, switch browsers, or open the Space on your phone,
41
+ and the workspace is empty again. Nothing is recoverable, because nothing was
42
+ ever stored anywhere but locally.
43
+
44
+ Even locally, SimpleDocReview records approvals as workflow acknowledgements
45
+ with a name and a timestamp — not digital signatures, and not a tamper-evident
46
+ audit trail. For document control with revision history and verifiable audit
47
+ records, upstream points at
48
+ [DocReview360](https://github.com/eputnam77/DocReview360).
49
+
50
+ ## What works here
51
+
52
+ Everything in the upstream UI:
53
+
54
+ - Upload TXT, MD, and DOCX up to 5 MB, with local text extraction
55
+ - Deterministic quality review: missing sections, unresolved placeholders, vague
56
+ language, very short documents, overlong sentences
57
+ - A reviewer directory, reviewer assignment, and per-reviewer status
58
+ - Reviewer comments, change requests, and signed approvals; a document is
59
+ approved only once every assigned reviewer has approved
60
+ - The notification queue, with copyable message text
61
+ - The activity timeline
62
+ - Downloading the original file
63
+
64
+ Nothing is stubbed or disabled. The demo's only difference from the real thing
65
+ is where the data lives.
66
+
67
+ ## About this repository
68
+
69
+ This is the **deployment repository** for the Space. The application is
70
+ developed in [SimpleDocReview](https://github.com/eputnam77/SimpleDocReview) and
71
+ vendored into [`app/`](app); `UPSTREAM.json` records exactly which upstream
72
+ commit is deployed.
73
+
74
+ Do not edit files under `app/` — it is a mirror, and edits are overwritten on
75
+ the next sync. Change upstream, then re-sync. See [DEPLOY.md](DEPLOY.md).
76
+
77
+ ### How the Space runs
78
+
79
+ Upstream is a Python standard-library HTTP server (`app.py`) serving a vanilla
80
+ HTML/CSS/JavaScript front end (`static/`) and storing everything in local files.
81
+ A Static Space can serve the front end unchanged, but the server has to go
82
+ somewhere. It goes into the browser:
83
+
84
+ ```
85
+ app/static/index.html -> /index.html (upstream, with two script tags added)
86
+ app/static/app.js -> /static/app.js (upstream, untouched)
87
+ app/static/styles.css -> /static/styles.css (upstream, untouched)
88
+ overlay/sdr-api-core.js -> /sdr-api-core.js app.py's API, ported to JavaScript
89
+ overlay/sdr-api-shim.js -> /sdr-api-shim.js IndexedDB, request interception
90
+ ```
91
+
92
+ `sdr-api-shim.js` intercepts every `/api/` request upstream's `app.js` makes and
93
+ answers it from `sdr-api-core.js`, which is a port of `app.py` — the same routes,
94
+ the same rubric, the same status transitions, the same record shapes.
95
+
96
+ Because that port could silently drift from the Python it mirrors,
97
+ [`tests/`](tests) exists to catch it: `tests/parity/` replays a 67-request
98
+ workflow through both the real `app.py` and the JavaScript port and diffs every
99
+ response and the final record store, and `tests/browser/` drives the built site
100
+ in headless Chromium through an upload-review-assign-approve round.
101
+
102
+ ### Local development
103
+
104
+ Build and preview exactly what the Space serves:
105
+
106
+ ```powershell
107
+ .\scripts\build-static.ps1
108
+ python -m http.server 8000
109
+ ```
110
+
111
+ Verify the port still matches upstream:
112
+
113
+ ```powershell
114
+ node tests\parity\run-parity.mjs
115
+ node tests\browser\run-browser-check.mjs
116
+ ```
117
+
118
+ For real feature work use the upstream repo. Application behavior belongs there;
119
+ only the build tooling, the Space card, and the browser-side API belong here.
120
+
121
+ ## License
122
+
123
+ Inherited from the upstream project. See
124
+ [SimpleDocReview](https://github.com/eputnam77/SimpleDocReview).
UPSTREAM.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "upstreamRepo": "https://github.com/eputnam77/SimpleDocReview.git",
3
+ "upstreamPath": "C:\\dev\\SimpleDocReview",
4
+ "commit": "2c22f4147eddc711ad3be3fa18d2f10150642a2d",
5
+ "branch": "main",
6
+ "dirtyWorkingTree": false,
7
+ "serverVersion": "SimpleDocReview/2.0",
8
+ "portedSources": {
9
+ "app.py": "008df80aaec9b971e42162328972823a01d6cb85e9ce5013dfe5a2d9949ba939",
10
+ "static/app.js": "3b24215db79c090d3565eb58be4ececd006b96b7605fac474b24daf0dc47c6ef"
11
+ },
12
+ "syncedAtUtc": "2026-08-20T12:07:54Z"
13
+ }
app/app.py ADDED
@@ -0,0 +1,1211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import html
4
+ import json
5
+ import mimetypes
6
+ import re
7
+ import shutil
8
+ import uuid
9
+ import zipfile
10
+ from datetime import datetime, timezone
11
+ from email.parser import BytesParser
12
+ from email.policy import default as email_policy
13
+ from http import HTTPStatus
14
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
15
+ from io import BytesIO
16
+ from pathlib import Path
17
+ from urllib.parse import unquote, urlparse
18
+
19
+
20
+ ROOT = Path(__file__).resolve().parent
21
+ STATIC_DIR = ROOT / "static"
22
+ DATA_DIR = ROOT / "data"
23
+ UPLOAD_DIR = ROOT / "uploads"
24
+ DB_PATH = DATA_DIR / "reviews.json"
25
+
26
+ MAX_UPLOAD_BYTES = 5 * 1024 * 1024
27
+ ALLOWED_EXTENSIONS = {".txt", ".md", ".docx"}
28
+ CONTACT_FIELDS = ("email", "slack", "teams")
29
+
30
+
31
+ STATUS_LABELS = {
32
+ "uploaded": "Uploaded",
33
+ "in_review": "In review",
34
+ "changes_requested": "Changes requested",
35
+ "approved": "Approved",
36
+ }
37
+
38
+ ASSIGNMENT_LABELS = {
39
+ "pending": "Pending",
40
+ "commented": "Commented",
41
+ "changes_requested": "Changes requested",
42
+ "approved": "Approved",
43
+ }
44
+
45
+
46
+ def utc_now() -> str:
47
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
48
+
49
+
50
+ def ensure_storage() -> None:
51
+ DATA_DIR.mkdir(exist_ok=True)
52
+ UPLOAD_DIR.mkdir(exist_ok=True)
53
+ if not DB_PATH.exists():
54
+ save_db({"documents": [], "reviewers": [], "notifications": []})
55
+
56
+
57
+ def load_db() -> dict:
58
+ ensure_storage()
59
+ try:
60
+ with DB_PATH.open("r", encoding="utf-8") as handle:
61
+ data = json.load(handle)
62
+ except json.JSONDecodeError:
63
+ data = {"documents": [], "reviewers": [], "notifications": []}
64
+
65
+ if migrate_db(data):
66
+ save_db(data)
67
+ return data
68
+
69
+
70
+ def save_db(data: dict) -> None:
71
+ DATA_DIR.mkdir(exist_ok=True)
72
+ tmp_path = DB_PATH.with_suffix(".json.tmp")
73
+ with tmp_path.open("w", encoding="utf-8") as handle:
74
+ json.dump(data, handle, indent=2)
75
+ tmp_path.replace(DB_PATH)
76
+
77
+
78
+ def clean_text(value: object, fallback: str = "", max_length: int = 240) -> str:
79
+ text = str(value or "").strip()
80
+ return (text or fallback)[:max_length]
81
+
82
+
83
+ def empty_contact() -> dict:
84
+ return {"email": "", "slack": "", "teams": ""}
85
+
86
+
87
+ def normalize_contact(payload: dict | None) -> dict:
88
+ payload = payload or {}
89
+ return {field: clean_text(payload.get(field), max_length=240) for field in CONTACT_FIELDS}
90
+
91
+
92
+ def owner_from_payload(payload: dict | None) -> dict:
93
+ payload = payload or {}
94
+ owner = {"name": clean_text(payload.get("name") or payload.get("owner_name"), "Owner", 120)}
95
+ owner.update(normalize_contact(payload))
96
+ return owner
97
+
98
+
99
+ def migrate_db(data: dict) -> bool:
100
+ changed = False
101
+ if not isinstance(data.get("documents"), list):
102
+ data["documents"] = []
103
+ changed = True
104
+ if not isinstance(data.get("reviewers"), list):
105
+ data["reviewers"] = []
106
+ changed = True
107
+ if not isinstance(data.get("notifications"), list):
108
+ data["notifications"] = []
109
+ changed = True
110
+
111
+ for reviewer in data["reviewers"]:
112
+ changed = migrate_reviewer(reviewer) or changed
113
+ for notification in data["notifications"]:
114
+ changed = migrate_notification(notification) or changed
115
+ for document in data["documents"]:
116
+ changed = migrate_document(document) or changed
117
+ return changed
118
+
119
+
120
+ def migrate_reviewer(reviewer: dict) -> bool:
121
+ changed = False
122
+ now = utc_now()
123
+ defaults = {
124
+ "id": uuid.uuid4().hex,
125
+ "name": "Reviewer",
126
+ "created_at": now,
127
+ "updated_at": now,
128
+ }
129
+ for key, value in defaults.items():
130
+ if not reviewer.get(key):
131
+ reviewer[key] = value
132
+ changed = True
133
+ for field in CONTACT_FIELDS:
134
+ if field not in reviewer:
135
+ reviewer[field] = ""
136
+ changed = True
137
+ return changed
138
+
139
+
140
+ def migrate_notification(notification: dict) -> bool:
141
+ changed = False
142
+ defaults = {
143
+ "id": uuid.uuid4().hex,
144
+ "recipient_type": "owner",
145
+ "recipient_name": "Owner",
146
+ "recipient_contact": empty_contact(),
147
+ "document_id": "",
148
+ "document_title": "",
149
+ "event": "notice",
150
+ "message": "",
151
+ "created_at": utc_now(),
152
+ "read_at": None,
153
+ }
154
+ for key, value in defaults.items():
155
+ if key not in notification:
156
+ notification[key] = value
157
+ changed = True
158
+ if not isinstance(notification.get("recipient_contact"), dict):
159
+ notification["recipient_contact"] = empty_contact()
160
+ changed = True
161
+ else:
162
+ for field in CONTACT_FIELDS:
163
+ if field not in notification["recipient_contact"]:
164
+ notification["recipient_contact"][field] = ""
165
+ changed = True
166
+ return changed
167
+
168
+
169
+ def migrate_document(record: dict) -> bool:
170
+ changed = False
171
+ now = utc_now()
172
+ defaults = {
173
+ "id": uuid.uuid4().hex,
174
+ "filename": "document",
175
+ "extension": ".txt",
176
+ "status": "uploaded",
177
+ "created_at": now,
178
+ "updated_at": now,
179
+ "reviewed_at": None,
180
+ "approved_at": None,
181
+ "word_count": 0,
182
+ "findings": [],
183
+ "comments": [],
184
+ }
185
+ for key, value in defaults.items():
186
+ if key not in record:
187
+ record[key] = value
188
+ changed = True
189
+
190
+ if not isinstance(record.get("owner"), dict):
191
+ record["owner"] = owner_from_payload({})
192
+ changed = True
193
+ else:
194
+ owner = owner_from_payload(record["owner"])
195
+ if owner != record["owner"]:
196
+ record["owner"] = owner
197
+ changed = True
198
+
199
+ if not isinstance(record.get("assignments"), list):
200
+ record["assignments"] = []
201
+ changed = True
202
+ for assignment in record["assignments"]:
203
+ changed = migrate_assignment(assignment) or changed
204
+
205
+ if not isinstance(record.get("activity"), list):
206
+ record["activity"] = build_legacy_activity(record)
207
+ changed = True
208
+ elif not record["activity"]:
209
+ record["activity"] = build_legacy_activity(record)
210
+ changed = True
211
+
212
+ return changed
213
+
214
+
215
+ def migrate_assignment(assignment: dict) -> bool:
216
+ changed = False
217
+ now = utc_now()
218
+ defaults = {
219
+ "id": uuid.uuid4().hex,
220
+ "reviewer_id": "",
221
+ "reviewer_name": "Reviewer",
222
+ "reviewer_contact": empty_contact(),
223
+ "status": "pending",
224
+ "status_label": "Pending",
225
+ "assigned_at": now,
226
+ "updated_at": now,
227
+ "approved_at": None,
228
+ "approval_name": "",
229
+ "approval_initials": "",
230
+ "comments": [],
231
+ }
232
+ for key, value in defaults.items():
233
+ if key not in assignment:
234
+ assignment[key] = value
235
+ changed = True
236
+ if assignment["status_label"] != ASSIGNMENT_LABELS.get(assignment["status"], assignment["status"]):
237
+ assignment["status_label"] = ASSIGNMENT_LABELS.get(assignment["status"], assignment["status"])
238
+ changed = True
239
+ if not isinstance(assignment.get("reviewer_contact"), dict):
240
+ assignment["reviewer_contact"] = empty_contact()
241
+ changed = True
242
+ else:
243
+ for field in CONTACT_FIELDS:
244
+ if field not in assignment["reviewer_contact"]:
245
+ assignment["reviewer_contact"][field] = ""
246
+ changed = True
247
+ if not isinstance(assignment.get("comments"), list):
248
+ assignment["comments"] = []
249
+ changed = True
250
+ return changed
251
+
252
+
253
+ def build_legacy_activity(record: dict) -> list[dict]:
254
+ activity = [
255
+ {
256
+ "id": uuid.uuid4().hex,
257
+ "type": "uploaded",
258
+ "actor": record.get("owner", {}).get("name", "Owner"),
259
+ "message": f"Uploaded {record.get('filename', 'document')}.",
260
+ "created_at": record.get("created_at") or utc_now(),
261
+ }
262
+ ]
263
+ if record.get("reviewed_at"):
264
+ activity.append(
265
+ {
266
+ "id": uuid.uuid4().hex,
267
+ "type": "review_run",
268
+ "actor": "System",
269
+ "message": "Ran the local rubric review.",
270
+ "created_at": record["reviewed_at"],
271
+ }
272
+ )
273
+ for comment in record.get("comments", []):
274
+ activity.append(
275
+ {
276
+ "id": uuid.uuid4().hex,
277
+ "type": "comment_added",
278
+ "actor": comment.get("author", "Reviewer"),
279
+ "message": f"Commented: {comment.get('body', '')[:120]}",
280
+ "created_at": comment.get("created_at") or utc_now(),
281
+ }
282
+ )
283
+ if record.get("approved_at"):
284
+ activity.append(
285
+ {
286
+ "id": uuid.uuid4().hex,
287
+ "type": "approved",
288
+ "actor": "Reviewer",
289
+ "message": "Approved the document.",
290
+ "created_at": record["approved_at"],
291
+ }
292
+ )
293
+ return sorted(activity, key=lambda item: item["created_at"])
294
+
295
+
296
+ def sanitize_filename(filename: str) -> str:
297
+ name = Path(filename or "document").name.strip()
298
+ stem = Path(name).stem or "document"
299
+ suffix = Path(name).suffix.lower()
300
+ clean_stem = re.sub(r"[^A-Za-z0-9._ -]+", "-", stem).strip(" .-_")
301
+ return f"{clean_stem or 'document'}{suffix}"
302
+
303
+
304
+ def decode_text_bytes(content: bytes) -> str:
305
+ for encoding in ("utf-8-sig", "utf-16", "cp1252"):
306
+ try:
307
+ return content.decode(encoding)
308
+ except UnicodeDecodeError:
309
+ continue
310
+ return content.decode("utf-8", errors="replace")
311
+
312
+
313
+ def extract_docx_text(content: bytes) -> str:
314
+ with zipfile.ZipFile(BytesIO(content)) as archive:
315
+ try:
316
+ xml_bytes = archive.read("word/document.xml")
317
+ except KeyError as exc:
318
+ raise ValueError("The DOCX file does not contain document text.") from exc
319
+
320
+ xml_text = xml_bytes.decode("utf-8", errors="replace")
321
+ paragraphs = re.findall(r"<w:p\b[^>]*>(.*?)</w:p>", xml_text, flags=re.DOTALL)
322
+ extracted: list[str] = []
323
+ for paragraph in paragraphs:
324
+ text_runs = re.findall(r"<w:t\b[^>]*>(.*?)</w:t>", paragraph, flags=re.DOTALL)
325
+ if text_runs:
326
+ extracted.append("".join(html.unescape(run) for run in text_runs))
327
+ return "\n".join(line.strip() for line in extracted if line.strip())
328
+
329
+
330
+ def extract_text(filename: str, content: bytes) -> str:
331
+ extension = Path(filename).suffix.lower()
332
+ if extension in {".txt", ".md"}:
333
+ return decode_text_bytes(content).strip()
334
+ if extension == ".docx":
335
+ return extract_docx_text(content).strip()
336
+ raise ValueError("Unsupported document type.")
337
+
338
+
339
+ def snippet_for(text: str, pattern: re.Pattern[str]) -> str:
340
+ match = pattern.search(text)
341
+ if not match:
342
+ return ""
343
+ start = max(0, match.start() - 70)
344
+ end = min(len(text), match.end() + 70)
345
+ return re.sub(r"\s+", " ", text[start:end]).strip()
346
+
347
+
348
+ def has_section(text: str, terms: tuple[str, ...]) -> bool:
349
+ for term in terms:
350
+ heading_pattern = re.compile(rf"(?im)^\s*(?:#+\s*)?{re.escape(term)}\b")
351
+ if heading_pattern.search(text):
352
+ return True
353
+ label_pattern = re.compile(rf"(?i)\b{re.escape(term)}\s*:")
354
+ if label_pattern.search(text):
355
+ return True
356
+ return False
357
+
358
+
359
+ def analyze_document(text: str) -> dict:
360
+ findings: list[dict] = []
361
+ normalized_text = text.strip()
362
+ word_count = len(re.findall(r"\b[\w'-]+\b", normalized_text))
363
+
364
+ section_checks = [
365
+ ("purpose", ("purpose", "objective"), "Purpose or objective"),
366
+ ("scope", ("scope", "applicability"), "Scope"),
367
+ ("owner", ("owner", "document owner", "responsible party"), "Owner"),
368
+ ("date", ("date", "effective date", "review date"), "Date or review date"),
369
+ ("risk", ("risk", "risks", "risk assessment"), "Risk section"),
370
+ ("approval", ("approval", "approved by", "signature", "sign-off"), "Approval or signature"),
371
+ ]
372
+ for key, terms, label in section_checks:
373
+ if not has_section(normalized_text, terms):
374
+ severity = "high" if key == "approval" else "medium"
375
+ findings.append(
376
+ {
377
+ "id": f"missing-{key}",
378
+ "severity": severity,
379
+ "title": f"Missing {label.lower()}",
380
+ "detail": f"Add a clear {label.lower()} section or label before approval.",
381
+ "snippet": "",
382
+ }
383
+ )
384
+
385
+ placeholder_checks = [
386
+ ("todo", re.compile(r"(?i)\bTODO\b|\bTBD\b|\bTBA\b")),
387
+ ("insert", re.compile(r"(?i)\[(?:insert|add|fill in)[^\]]*\]|<\s*(?:insert|add|fill in)[^>]*>")),
388
+ ("blank", re.compile(r"_{4,}|\{\{[^}]+\}\}")),
389
+ ]
390
+ for key, pattern in placeholder_checks:
391
+ if pattern.search(normalized_text):
392
+ findings.append(
393
+ {
394
+ "id": f"placeholder-{key}",
395
+ "severity": "high",
396
+ "title": "Unresolved placeholder",
397
+ "detail": "Replace template placeholders before the document can be considered final.",
398
+ "snippet": snippet_for(normalized_text, pattern),
399
+ }
400
+ )
401
+
402
+ vague_language = [
403
+ "best effort",
404
+ "as needed",
405
+ "reasonable",
406
+ "as appropriate",
407
+ "when possible",
408
+ "from time to time",
409
+ ]
410
+ for phrase in vague_language:
411
+ pattern = re.compile(rf"(?i)\b{re.escape(phrase)}\b")
412
+ if pattern.search(normalized_text):
413
+ findings.append(
414
+ {
415
+ "id": f"vague-{phrase.replace(' ', '-')}",
416
+ "severity": "medium",
417
+ "title": f'Vague language: "{phrase}"',
418
+ "detail": "Make the requirement measurable, accountable, or time-bound.",
419
+ "snippet": snippet_for(normalized_text, pattern),
420
+ }
421
+ )
422
+
423
+ if word_count < 80:
424
+ findings.append(
425
+ {
426
+ "id": "short-document",
427
+ "severity": "low",
428
+ "title": "Very short document",
429
+ "detail": "Confirm the document has enough context for reviewers and approvers.",
430
+ "snippet": "",
431
+ }
432
+ )
433
+
434
+ long_sentence_pattern = re.compile(r"[^.!?]{260,}[.!?]")
435
+ if long_sentence_pattern.search(normalized_text):
436
+ findings.append(
437
+ {
438
+ "id": "long-sentence",
439
+ "severity": "low",
440
+ "title": "Long sentence",
441
+ "detail": "Break long sentences into shorter reviewable statements.",
442
+ "snippet": snippet_for(normalized_text, long_sentence_pattern),
443
+ }
444
+ )
445
+
446
+ severity_order = {"high": 0, "medium": 1, "low": 2}
447
+ findings.sort(key=lambda item: (severity_order[item["severity"]], item["title"]))
448
+ counts = {
449
+ "high": sum(1 for item in findings if item["severity"] == "high"),
450
+ "medium": sum(1 for item in findings if item["severity"] == "medium"),
451
+ "low": sum(1 for item in findings if item["severity"] == "low"),
452
+ }
453
+ return {
454
+ "reviewed_at": utc_now(),
455
+ "word_count": word_count,
456
+ "findings": findings,
457
+ "counts": counts,
458
+ }
459
+
460
+
461
+ def add_activity(record: dict, event_type: str, actor: str, message: str, timestamp: str | None = None) -> None:
462
+ record.setdefault("activity", []).append(
463
+ {
464
+ "id": uuid.uuid4().hex,
465
+ "type": event_type,
466
+ "actor": clean_text(actor, "System", 120),
467
+ "message": clean_text(message, max_length=500),
468
+ "created_at": timestamp or utc_now(),
469
+ }
470
+ )
471
+
472
+
473
+ def assignment_counts(record: dict) -> dict:
474
+ counts = {"pending": 0, "commented": 0, "changes_requested": 0, "approved": 0}
475
+ for assignment in record.get("assignments", []):
476
+ counts[assignment.get("status", "pending")] = counts.get(assignment.get("status", "pending"), 0) + 1
477
+ return counts
478
+
479
+
480
+ def recalculate_document_status(record: dict) -> None:
481
+ assignments = record.get("assignments", [])
482
+ if not assignments:
483
+ return
484
+
485
+ statuses = {assignment.get("status", "pending") for assignment in assignments}
486
+ if "changes_requested" in statuses:
487
+ record["status"] = "changes_requested"
488
+ record["approved_at"] = None
489
+ elif statuses == {"approved"}:
490
+ record["status"] = "approved"
491
+ record["approved_at"] = record.get("approved_at") or utc_now()
492
+ else:
493
+ record["status"] = "in_review"
494
+ record["approved_at"] = None
495
+
496
+
497
+ def public_assignment(assignment: dict) -> dict:
498
+ return {
499
+ "id": assignment["id"],
500
+ "reviewer_id": assignment["reviewer_id"],
501
+ "reviewer_name": assignment["reviewer_name"],
502
+ "reviewer_contact": assignment.get("reviewer_contact", empty_contact()),
503
+ "status": assignment["status"],
504
+ "status_label": ASSIGNMENT_LABELS.get(assignment["status"], assignment["status"]),
505
+ "assigned_at": assignment["assigned_at"],
506
+ "updated_at": assignment["updated_at"],
507
+ "approved_at": assignment.get("approved_at"),
508
+ "approval_name": assignment.get("approval_name", ""),
509
+ "approval_initials": assignment.get("approval_initials", ""),
510
+ "comments": assignment.get("comments", []),
511
+ }
512
+
513
+
514
+ def public_document(record: dict, include_text: bool = False) -> dict:
515
+ counts = assignment_counts(record)
516
+ public = {
517
+ "id": record["id"],
518
+ "filename": record["filename"],
519
+ "extension": record["extension"],
520
+ "status": record["status"],
521
+ "status_label": STATUS_LABELS.get(record["status"], record["status"]),
522
+ "created_at": record["created_at"],
523
+ "updated_at": record["updated_at"],
524
+ "reviewed_at": record.get("reviewed_at"),
525
+ "approved_at": record.get("approved_at"),
526
+ "word_count": record.get("word_count", 0),
527
+ "findings": record.get("findings", []),
528
+ "comments": record.get("comments", []),
529
+ "owner": record.get("owner", owner_from_payload({})),
530
+ "assignments": [public_assignment(item) for item in record.get("assignments", [])],
531
+ "assignment_counts": counts,
532
+ "activity": sorted(record.get("activity", []), key=lambda item: item.get("created_at", ""), reverse=True),
533
+ }
534
+ if include_text:
535
+ public["text"] = record.get("text", "")
536
+ return public
537
+
538
+
539
+ def public_reviewer(reviewer: dict) -> dict:
540
+ return {
541
+ "id": reviewer["id"],
542
+ "name": reviewer["name"],
543
+ "email": reviewer.get("email", ""),
544
+ "slack": reviewer.get("slack", ""),
545
+ "teams": reviewer.get("teams", ""),
546
+ "created_at": reviewer["created_at"],
547
+ "updated_at": reviewer["updated_at"],
548
+ }
549
+
550
+
551
+ def public_notification(notification: dict) -> dict:
552
+ return {
553
+ "id": notification["id"],
554
+ "recipient_type": notification["recipient_type"],
555
+ "recipient_name": notification["recipient_name"],
556
+ "recipient_contact": notification.get("recipient_contact", empty_contact()),
557
+ "document_id": notification["document_id"],
558
+ "document_title": notification["document_title"],
559
+ "event": notification["event"],
560
+ "message": notification["message"],
561
+ "created_at": notification["created_at"],
562
+ "read_at": notification.get("read_at"),
563
+ }
564
+
565
+
566
+ def find_document(data: dict, document_id: str) -> dict | None:
567
+ return next((doc for doc in data["documents"] if doc["id"] == document_id), None)
568
+
569
+
570
+ def find_reviewer(data: dict, reviewer_id: str) -> dict | None:
571
+ return next((reviewer for reviewer in data["reviewers"] if reviewer["id"] == reviewer_id), None)
572
+
573
+
574
+ def find_assignment(record: dict, reviewer_id: str) -> dict | None:
575
+ return next((item for item in record.get("assignments", []) if item["reviewer_id"] == reviewer_id), None)
576
+
577
+
578
+ def contact_summary(contact: dict) -> str:
579
+ parts = [contact.get("email", ""), contact.get("slack", ""), contact.get("teams", "")]
580
+ return " | ".join(part for part in parts if part)
581
+
582
+
583
+ def reviewer_payload(payload: dict, existing: dict | None = None) -> dict:
584
+ reviewer = dict(existing or {})
585
+ reviewer["name"] = clean_text(payload.get("name"), max_length=120)
586
+ if not reviewer["name"]:
587
+ raise ValueError("Reviewer name is required.")
588
+ reviewer.update(normalize_contact(payload))
589
+ return reviewer
590
+
591
+
592
+ def build_assignment(reviewer: dict) -> dict:
593
+ timestamp = utc_now()
594
+ assignment = {
595
+ "id": uuid.uuid4().hex,
596
+ "reviewer_id": reviewer["id"],
597
+ "reviewer_name": reviewer["name"],
598
+ "reviewer_contact": normalize_contact(reviewer),
599
+ "status": "pending",
600
+ "status_label": "Pending",
601
+ "assigned_at": timestamp,
602
+ "updated_at": timestamp,
603
+ "approved_at": None,
604
+ "approval_name": "",
605
+ "approval_initials": "",
606
+ "comments": [],
607
+ }
608
+ migrate_assignment(assignment)
609
+ return assignment
610
+
611
+
612
+ def create_notification(
613
+ data: dict,
614
+ record: dict,
615
+ recipient_type: str,
616
+ recipient_name: str,
617
+ recipient_contact: dict,
618
+ event: str,
619
+ message: str,
620
+ ) -> dict:
621
+ notification = {
622
+ "id": uuid.uuid4().hex,
623
+ "recipient_type": recipient_type,
624
+ "recipient_name": clean_text(recipient_name, "Recipient", 120),
625
+ "recipient_contact": normalize_contact(recipient_contact),
626
+ "document_id": record["id"],
627
+ "document_title": record["filename"],
628
+ "event": event,
629
+ "message": clean_text(message, max_length=1000),
630
+ "created_at": utc_now(),
631
+ "read_at": None,
632
+ }
633
+ data.setdefault("notifications", []).append(notification)
634
+ add_activity(
635
+ record,
636
+ "notification",
637
+ "System",
638
+ f"Queued notification for {notification['recipient_name']}: {notification['message']}",
639
+ notification["created_at"],
640
+ )
641
+ return notification
642
+
643
+
644
+ def parse_multipart_upload(content_type: str, body: bytes) -> tuple[str, bytes, dict]:
645
+ if "multipart/form-data" not in content_type:
646
+ raise ValueError("Upload must use multipart/form-data.")
647
+
648
+ message_bytes = (
649
+ f"Content-Type: {content_type}\r\nMIME-Version: 1.0\r\n\r\n".encode("utf-8")
650
+ + body
651
+ )
652
+ message = BytesParser(policy=email_policy).parsebytes(message_bytes)
653
+ if not message.is_multipart():
654
+ raise ValueError("Upload payload is not multipart.")
655
+
656
+ filename = ""
657
+ file_payload = b""
658
+ fields: dict[str, str] = {}
659
+ for part in message.iter_parts():
660
+ part_name = part.get_param("name", header="content-disposition")
661
+ part_filename = part.get_filename()
662
+ payload = part.get_payload(decode=True) or b""
663
+ if part_filename:
664
+ filename = sanitize_filename(part_filename)
665
+ file_payload = payload
666
+ elif part_name:
667
+ fields[part_name] = decode_text_bytes(payload).strip()
668
+
669
+ if not filename:
670
+ raise ValueError("No file part was found in the upload.")
671
+ return filename, file_payload, fields
672
+
673
+
674
+ class ReviewHandler(BaseHTTPRequestHandler):
675
+ server_version = "SimpleDocReview/2.0"
676
+
677
+ def log_message(self, format: str, *args: object) -> None:
678
+ print(f"{self.address_string()} - {format % args}")
679
+
680
+ def send_json(self, payload: dict | list, status: int = 200) -> None:
681
+ encoded = json.dumps(payload).encode("utf-8")
682
+ self.send_response(status)
683
+ self.send_header("Content-Type", "application/json; charset=utf-8")
684
+ self.send_header("Content-Length", str(len(encoded)))
685
+ self.end_headers()
686
+ self.wfile.write(encoded)
687
+
688
+ def send_error_json(self, message: str, status: int = 400) -> None:
689
+ self.send_json({"error": message}, status)
690
+
691
+ def read_json_body(self) -> dict:
692
+ length = int(self.headers.get("Content-Length", "0") or "0")
693
+ if length == 0:
694
+ return {}
695
+ raw = self.rfile.read(length)
696
+ try:
697
+ return json.loads(raw.decode("utf-8"))
698
+ except json.JSONDecodeError as exc:
699
+ raise ValueError("Request body must be valid JSON.") from exc
700
+
701
+ def path_parts(self) -> list[str]:
702
+ parsed = urlparse(self.path)
703
+ return [unquote(part) for part in parsed.path.strip("/").split("/") if part]
704
+
705
+ def do_GET(self) -> None:
706
+ parsed = urlparse(self.path)
707
+ path = parsed.path
708
+ parts = self.path_parts()
709
+
710
+ if path == "/" or path == "/index.html":
711
+ self.serve_static(STATIC_DIR / "index.html")
712
+ return
713
+ if path.startswith("/static/"):
714
+ requested = STATIC_DIR / unquote(path.removeprefix("/static/"))
715
+ self.serve_static(requested)
716
+ return
717
+ if parts == ["api", "documents"]:
718
+ data = load_db()
719
+ documents = [public_document(doc) for doc in data["documents"]]
720
+ documents.sort(key=lambda item: item["updated_at"], reverse=True)
721
+ self.send_json({"documents": documents})
722
+ return
723
+ if parts == ["api", "reviewers"]:
724
+ data = load_db()
725
+ reviewers = [public_reviewer(reviewer) for reviewer in data["reviewers"]]
726
+ reviewers.sort(key=lambda item: item["name"].lower())
727
+ self.send_json({"reviewers": reviewers})
728
+ return
729
+ if parts == ["api", "notifications"]:
730
+ data = load_db()
731
+ notifications = [public_notification(item) for item in data["notifications"]]
732
+ notifications.sort(key=lambda item: item["created_at"], reverse=True)
733
+ unread_count = sum(1 for item in notifications if not item.get("read_at"))
734
+ self.send_json({"notifications": notifications, "unread_count": unread_count})
735
+ return
736
+ if len(parts) == 3 and parts[:2] == ["api", "documents"]:
737
+ data = load_db()
738
+ record = find_document(data, parts[2])
739
+ if not record:
740
+ self.send_error_json("Document not found.", HTTPStatus.NOT_FOUND)
741
+ return
742
+ self.send_json(public_document(record, include_text=True))
743
+ return
744
+ if len(parts) == 4 and parts[:2] == ["api", "documents"] and parts[3] == "download":
745
+ data = load_db()
746
+ record = find_document(data, parts[2])
747
+ if not record:
748
+ self.send_error_json("Document not found.", HTTPStatus.NOT_FOUND)
749
+ return
750
+ self.serve_download(record)
751
+ return
752
+
753
+ self.send_error_json("Not found.", HTTPStatus.NOT_FOUND)
754
+
755
+ def do_POST(self) -> None:
756
+ parts = self.path_parts()
757
+ try:
758
+ if parts == ["api", "upload"]:
759
+ self.handle_upload()
760
+ return
761
+ if parts == ["api", "reviewers"]:
762
+ self.handle_create_reviewer()
763
+ return
764
+ if len(parts) == 4 and parts[:2] == ["api", "notifications"] and parts[3] == "read":
765
+ self.handle_notification_read(parts[2])
766
+ return
767
+ if len(parts) == 4 and parts[:2] == ["api", "documents"]:
768
+ action = parts[3]
769
+ if action == "review":
770
+ self.handle_review(parts[2])
771
+ return
772
+ if action == "comments":
773
+ self.handle_comment(parts[2])
774
+ return
775
+ if action == "approve":
776
+ self.handle_status(parts[2], "approved")
777
+ return
778
+ if action == "request-changes":
779
+ self.handle_status(parts[2], "changes_requested")
780
+ return
781
+ if action == "assign-reviewers":
782
+ self.handle_assign_reviewers(parts[2])
783
+ return
784
+ if action == "reviewer-comment":
785
+ self.handle_reviewer_comment(parts[2])
786
+ return
787
+ if action == "reviewer-approve":
788
+ self.handle_reviewer_approve(parts[2])
789
+ return
790
+ if action == "reviewer-request-changes":
791
+ self.handle_reviewer_request_changes(parts[2])
792
+ return
793
+ except ValueError as exc:
794
+ self.send_error_json(str(exc), HTTPStatus.BAD_REQUEST)
795
+ return
796
+ except zipfile.BadZipFile:
797
+ self.send_error_json("The DOCX file appears to be invalid.", HTTPStatus.BAD_REQUEST)
798
+ return
799
+
800
+ self.send_error_json("Not found.", HTTPStatus.NOT_FOUND)
801
+
802
+ def do_PUT(self) -> None:
803
+ parts = self.path_parts()
804
+ try:
805
+ if len(parts) == 3 and parts[:2] == ["api", "reviewers"]:
806
+ self.handle_update_reviewer(parts[2])
807
+ return
808
+ except ValueError as exc:
809
+ self.send_error_json(str(exc), HTTPStatus.BAD_REQUEST)
810
+ return
811
+ self.send_error_json("Not found.", HTTPStatus.NOT_FOUND)
812
+
813
+ def do_DELETE(self) -> None:
814
+ parts = self.path_parts()
815
+ if len(parts) == 3 and parts[:2] == ["api", "reviewers"]:
816
+ self.handle_delete_reviewer(parts[2])
817
+ return
818
+ self.send_error_json("Not found.", HTTPStatus.NOT_FOUND)
819
+
820
+ def serve_static(self, requested: Path) -> None:
821
+ try:
822
+ resolved = requested.resolve()
823
+ static_root = STATIC_DIR.resolve()
824
+ if static_root not in (resolved, *resolved.parents):
825
+ raise FileNotFoundError
826
+ if not resolved.is_file():
827
+ raise FileNotFoundError
828
+ except FileNotFoundError:
829
+ self.send_error_json("Static file not found.", HTTPStatus.NOT_FOUND)
830
+ return
831
+
832
+ content_type = mimetypes.guess_type(resolved.name)[0] or "application/octet-stream"
833
+ content = resolved.read_bytes()
834
+ self.send_response(HTTPStatus.OK)
835
+ self.send_header("Content-Type", content_type)
836
+ self.send_header("Content-Length", str(len(content)))
837
+ self.end_headers()
838
+ self.wfile.write(content)
839
+
840
+ def serve_download(self, record: dict) -> None:
841
+ file_path = UPLOAD_DIR / record["stored_name"]
842
+ if not file_path.exists():
843
+ self.send_error_json("Original upload is missing.", HTTPStatus.NOT_FOUND)
844
+ return
845
+ content_type = mimetypes.guess_type(record["filename"])[0] or "application/octet-stream"
846
+ self.send_response(HTTPStatus.OK)
847
+ self.send_header("Content-Type", content_type)
848
+ self.send_header("Content-Disposition", f'attachment; filename="{record["filename"]}"')
849
+ self.send_header("Content-Length", str(file_path.stat().st_size))
850
+ self.end_headers()
851
+ with file_path.open("rb") as handle:
852
+ shutil.copyfileobj(handle, self.wfile)
853
+
854
+ def handle_upload(self) -> None:
855
+ length = int(self.headers.get("Content-Length", "0") or "0")
856
+ if length <= 0:
857
+ raise ValueError("Upload cannot be empty.")
858
+ if length > MAX_UPLOAD_BYTES:
859
+ raise ValueError("Upload is too large. Maximum size is 5 MB.")
860
+
861
+ filename, content, fields = parse_multipart_upload(self.headers.get("Content-Type", ""), self.rfile.read(length))
862
+ extension = Path(filename).suffix.lower()
863
+ if extension not in ALLOWED_EXTENSIONS:
864
+ self.send_error_json("Unsupported file type. Upload TXT, MD, or DOCX.", HTTPStatus.UNSUPPORTED_MEDIA_TYPE)
865
+ return
866
+ if not content:
867
+ raise ValueError("Uploaded file is empty.")
868
+
869
+ text = extract_text(filename, content)
870
+ if not text:
871
+ raise ValueError("No readable text was found in the document.")
872
+
873
+ document_id = uuid.uuid4().hex
874
+ stored_name = f"{document_id}{extension}"
875
+ (UPLOAD_DIR / stored_name).write_bytes(content)
876
+
877
+ timestamp = utc_now()
878
+ owner = owner_from_payload(
879
+ {
880
+ "name": fields.get("owner_name") or fields.get("owner"),
881
+ "email": fields.get("owner_email"),
882
+ "slack": fields.get("owner_slack"),
883
+ "teams": fields.get("owner_teams"),
884
+ }
885
+ )
886
+ record = {
887
+ "id": document_id,
888
+ "filename": filename,
889
+ "stored_name": stored_name,
890
+ "extension": extension,
891
+ "status": "uploaded",
892
+ "created_at": timestamp,
893
+ "updated_at": timestamp,
894
+ "reviewed_at": None,
895
+ "approved_at": None,
896
+ "word_count": len(re.findall(r"\b[\w'-]+\b", text)),
897
+ "text": text,
898
+ "findings": [],
899
+ "comments": [],
900
+ "owner": owner,
901
+ "assignments": [],
902
+ "activity": [],
903
+ }
904
+ add_activity(record, "uploaded", owner["name"], f"Uploaded {filename}.", timestamp)
905
+
906
+ data = load_db()
907
+ data["documents"].append(record)
908
+ save_db(data)
909
+ self.send_json(public_document(record, include_text=True), HTTPStatus.CREATED)
910
+
911
+ def handle_review(self, document_id: str) -> None:
912
+ data = load_db()
913
+ record = find_document(data, document_id)
914
+ if not record:
915
+ self.send_error_json("Document not found.", HTTPStatus.NOT_FOUND)
916
+ return
917
+ result = analyze_document(record.get("text", ""))
918
+ record["findings"] = result["findings"]
919
+ record["reviewed_at"] = result["reviewed_at"]
920
+ record["word_count"] = result["word_count"]
921
+ if record["status"] != "approved":
922
+ record["status"] = "in_review"
923
+ record["updated_at"] = utc_now()
924
+ add_activity(record, "review_run", "System", "Ran the local rubric review.", result["reviewed_at"])
925
+ save_db(data)
926
+ self.send_json(public_document(record, include_text=True))
927
+
928
+ def handle_comment(self, document_id: str) -> None:
929
+ payload = self.read_json_body()
930
+ body = clean_text(payload.get("body"), max_length=2000)
931
+ author = clean_text(payload.get("author"), "Reviewer", 80)
932
+ if not body:
933
+ raise ValueError("Comment body is required.")
934
+
935
+ data = load_db()
936
+ record = find_document(data, document_id)
937
+ if not record:
938
+ self.send_error_json("Document not found.", HTTPStatus.NOT_FOUND)
939
+ return
940
+
941
+ timestamp = utc_now()
942
+ record.setdefault("comments", []).append(
943
+ {
944
+ "id": uuid.uuid4().hex,
945
+ "author": author,
946
+ "body": body,
947
+ "created_at": timestamp,
948
+ }
949
+ )
950
+ record["updated_at"] = timestamp
951
+ add_activity(record, "comment_added", author, f"Commented: {body[:120]}", timestamp)
952
+ save_db(data)
953
+ self.send_json(public_document(record, include_text=True))
954
+
955
+ def handle_status(self, document_id: str, status: str) -> None:
956
+ data = load_db()
957
+ record = find_document(data, document_id)
958
+ if not record:
959
+ self.send_error_json("Document not found.", HTTPStatus.NOT_FOUND)
960
+ return
961
+
962
+ record["status"] = status
963
+ record["updated_at"] = utc_now()
964
+ if status == "approved":
965
+ record["approved_at"] = utc_now()
966
+ add_activity(record, "approved", record.get("owner", {}).get("name", "Owner"), "Owner approved the document.")
967
+ else:
968
+ record["approved_at"] = None
969
+ add_activity(record, "changes_requested", record.get("owner", {}).get("name", "Owner"), "Owner requested changes.")
970
+ save_db(data)
971
+ self.send_json(public_document(record, include_text=True))
972
+
973
+ def handle_create_reviewer(self) -> None:
974
+ payload = self.read_json_body()
975
+ timestamp = utc_now()
976
+ reviewer = reviewer_payload(payload)
977
+ reviewer.update({"id": uuid.uuid4().hex, "created_at": timestamp, "updated_at": timestamp})
978
+ data = load_db()
979
+ data["reviewers"].append(reviewer)
980
+ save_db(data)
981
+ self.send_json(public_reviewer(reviewer), HTTPStatus.CREATED)
982
+
983
+ def handle_update_reviewer(self, reviewer_id: str) -> None:
984
+ data = load_db()
985
+ reviewer = find_reviewer(data, reviewer_id)
986
+ if not reviewer:
987
+ self.send_error_json("Reviewer not found.", HTTPStatus.NOT_FOUND)
988
+ return
989
+ updated = reviewer_payload(self.read_json_body(), existing=reviewer)
990
+ reviewer.update(updated)
991
+ reviewer["updated_at"] = utc_now()
992
+ save_db(data)
993
+ self.send_json(public_reviewer(reviewer))
994
+
995
+ def handle_delete_reviewer(self, reviewer_id: str) -> None:
996
+ data = load_db()
997
+ original_count = len(data["reviewers"])
998
+ data["reviewers"] = [reviewer for reviewer in data["reviewers"] if reviewer["id"] != reviewer_id]
999
+ if len(data["reviewers"]) == original_count:
1000
+ self.send_error_json("Reviewer not found.", HTTPStatus.NOT_FOUND)
1001
+ return
1002
+ save_db(data)
1003
+ self.send_json({"ok": True})
1004
+
1005
+ def handle_assign_reviewers(self, document_id: str) -> None:
1006
+ payload = self.read_json_body()
1007
+ reviewer_ids = payload.get("reviewer_ids", [])
1008
+ if not isinstance(reviewer_ids, list):
1009
+ raise ValueError("reviewer_ids must be a list.")
1010
+ reviewer_ids = list(dict.fromkeys(str(item) for item in reviewer_ids if str(item).strip()))
1011
+
1012
+ data = load_db()
1013
+ record = find_document(data, document_id)
1014
+ if not record:
1015
+ self.send_error_json("Document not found.", HTTPStatus.NOT_FOUND)
1016
+ return
1017
+
1018
+ reviewers_by_id = {reviewer["id"]: reviewer for reviewer in data["reviewers"]}
1019
+ missing = [reviewer_id for reviewer_id in reviewer_ids if reviewer_id not in reviewers_by_id]
1020
+ if missing:
1021
+ raise ValueError("One or more selected reviewers no longer exists.")
1022
+
1023
+ existing_by_id = {assignment["reviewer_id"]: assignment for assignment in record.get("assignments", [])}
1024
+ assignments = []
1025
+ new_assignments = []
1026
+ for reviewer_id in reviewer_ids:
1027
+ assignment = existing_by_id.get(reviewer_id)
1028
+ if assignment:
1029
+ assignments.append(assignment)
1030
+ else:
1031
+ assignment = build_assignment(reviewers_by_id[reviewer_id])
1032
+ assignments.append(assignment)
1033
+ new_assignments.append(assignment)
1034
+ record["assignments"] = assignments
1035
+
1036
+ timestamp = utc_now()
1037
+ record["updated_at"] = timestamp
1038
+ if reviewer_ids:
1039
+ record["status"] = "in_review"
1040
+ names = ", ".join(assignment["reviewer_name"] for assignment in assignments)
1041
+ add_activity(record, "reviewers_assigned", record["owner"]["name"], f"Assigned reviewers: {names}.", timestamp)
1042
+ else:
1043
+ record["status"] = "in_review" if record.get("reviewed_at") else "uploaded"
1044
+ record["approved_at"] = None
1045
+ add_activity(record, "reviewers_assigned", record["owner"]["name"], "Cleared reviewer assignments.", timestamp)
1046
+
1047
+ for assignment in new_assignments:
1048
+ message = (
1049
+ f"Please review {record['filename']} in SimpleDocReview. "
1050
+ f"Open the local app, select the document, and respond as {assignment['reviewer_name']}."
1051
+ )
1052
+ create_notification(
1053
+ data,
1054
+ record,
1055
+ "reviewer",
1056
+ assignment["reviewer_name"],
1057
+ assignment["reviewer_contact"],
1058
+ "review_assigned",
1059
+ message,
1060
+ )
1061
+
1062
+ recalculate_document_status(record)
1063
+ save_db(data)
1064
+ self.send_json(public_document(record, include_text=True))
1065
+
1066
+ def handle_reviewer_comment(self, document_id: str) -> None:
1067
+ payload = self.read_json_body()
1068
+ data, record, assignment = self.require_assignment(document_id, payload)
1069
+ body = clean_text(payload.get("body"), max_length=2000)
1070
+ signature = clean_text(payload.get("signature"), assignment["reviewer_name"], 120)
1071
+ if not body:
1072
+ raise ValueError("Comment body is required.")
1073
+
1074
+ timestamp = utc_now()
1075
+ comment = {
1076
+ "id": uuid.uuid4().hex,
1077
+ "author": signature,
1078
+ "reviewer_id": assignment["reviewer_id"],
1079
+ "body": body,
1080
+ "created_at": timestamp,
1081
+ }
1082
+ assignment.setdefault("comments", []).append(comment)
1083
+ if assignment["status"] not in {"approved", "changes_requested"}:
1084
+ assignment["status"] = "commented"
1085
+ assignment["updated_at"] = timestamp
1086
+ migrate_assignment(assignment)
1087
+ record.setdefault("comments", []).append(comment)
1088
+ record["updated_at"] = timestamp
1089
+ add_activity(record, "reviewer_comment", signature, f"Commented: {body[:120]}", timestamp)
1090
+ create_notification(
1091
+ data,
1092
+ record,
1093
+ "owner",
1094
+ record["owner"]["name"],
1095
+ record["owner"],
1096
+ "reviewer_comment",
1097
+ f"{signature} commented on {record['filename']}: {body[:180]}",
1098
+ )
1099
+ recalculate_document_status(record)
1100
+ save_db(data)
1101
+ self.send_json(public_document(record, include_text=True))
1102
+
1103
+ def handle_reviewer_approve(self, document_id: str) -> None:
1104
+ payload = self.read_json_body()
1105
+ data, record, assignment = self.require_assignment(document_id, payload)
1106
+ signature = clean_text(payload.get("signature"), max_length=120)
1107
+ if not signature:
1108
+ raise ValueError("Approval name or initials are required.")
1109
+
1110
+ was_final = record.get("status") == "approved"
1111
+ timestamp = utc_now()
1112
+ assignment["status"] = "approved"
1113
+ assignment["approval_name"] = signature
1114
+ assignment["approval_initials"] = clean_text(payload.get("initials") or signature, max_length=24)
1115
+ assignment["approved_at"] = timestamp
1116
+ assignment["updated_at"] = timestamp
1117
+ migrate_assignment(assignment)
1118
+ record["updated_at"] = timestamp
1119
+ add_activity(record, "reviewer_approved", signature, f"Approved as {signature}.", timestamp)
1120
+ recalculate_document_status(record)
1121
+ if record.get("status") == "approved" and not was_final:
1122
+ add_activity(record, "approved", "System", "All assigned reviewers approved the document.", record["approved_at"])
1123
+ create_notification(
1124
+ data,
1125
+ record,
1126
+ "owner",
1127
+ record["owner"]["name"],
1128
+ record["owner"],
1129
+ "reviewer_approved",
1130
+ f"{signature} approved {record['filename']}.",
1131
+ )
1132
+ save_db(data)
1133
+ self.send_json(public_document(record, include_text=True))
1134
+
1135
+ def handle_reviewer_request_changes(self, document_id: str) -> None:
1136
+ payload = self.read_json_body()
1137
+ data, record, assignment = self.require_assignment(document_id, payload)
1138
+ body = clean_text(payload.get("body"), max_length=2000)
1139
+ signature = clean_text(payload.get("signature"), assignment["reviewer_name"], 120)
1140
+ if not body:
1141
+ raise ValueError("A change request note is required.")
1142
+
1143
+ timestamp = utc_now()
1144
+ assignment["status"] = "changes_requested"
1145
+ assignment["approved_at"] = None
1146
+ assignment["approval_name"] = ""
1147
+ assignment["approval_initials"] = ""
1148
+ assignment["updated_at"] = timestamp
1149
+ comment = {
1150
+ "id": uuid.uuid4().hex,
1151
+ "author": signature,
1152
+ "reviewer_id": assignment["reviewer_id"],
1153
+ "body": body,
1154
+ "created_at": timestamp,
1155
+ }
1156
+ assignment.setdefault("comments", []).append(comment)
1157
+ migrate_assignment(assignment)
1158
+ record.setdefault("comments", []).append(comment)
1159
+ record["updated_at"] = timestamp
1160
+ recalculate_document_status(record)
1161
+ add_activity(record, "reviewer_changes_requested", signature, f"Requested changes: {body[:120]}", timestamp)
1162
+ create_notification(
1163
+ data,
1164
+ record,
1165
+ "owner",
1166
+ record["owner"]["name"],
1167
+ record["owner"],
1168
+ "reviewer_changes_requested",
1169
+ f"{signature} requested changes on {record['filename']}: {body[:180]}",
1170
+ )
1171
+ save_db(data)
1172
+ self.send_json(public_document(record, include_text=True))
1173
+
1174
+ def handle_notification_read(self, notification_id: str) -> None:
1175
+ data = load_db()
1176
+ notification = next((item for item in data["notifications"] if item["id"] == notification_id), None)
1177
+ if not notification:
1178
+ self.send_error_json("Notification not found.", HTTPStatus.NOT_FOUND)
1179
+ return
1180
+ notification["read_at"] = notification.get("read_at") or utc_now()
1181
+ save_db(data)
1182
+ self.send_json(public_notification(notification))
1183
+
1184
+ def require_assignment(self, document_id: str, payload: dict) -> tuple[dict, dict, dict]:
1185
+ reviewer_id = clean_text(payload.get("reviewer_id"), max_length=80)
1186
+ if not reviewer_id:
1187
+ raise ValueError("Reviewer is required.")
1188
+ data = load_db()
1189
+ record = find_document(data, document_id)
1190
+ if not record:
1191
+ raise ValueError("Document not found.")
1192
+ assignment = find_assignment(record, reviewer_id)
1193
+ if not assignment:
1194
+ raise ValueError("Reviewer is not assigned to this document.")
1195
+ return data, record, assignment
1196
+
1197
+
1198
+ def run(host: str = "127.0.0.1", port: int = 4173) -> None:
1199
+ ensure_storage()
1200
+ server = ThreadingHTTPServer((host, port), ReviewHandler)
1201
+ print(f"SimpleDocReview running at http://{host}:{port}")
1202
+ try:
1203
+ server.serve_forever()
1204
+ except KeyboardInterrupt:
1205
+ print("\nShutting down SimpleDocReview.")
1206
+ finally:
1207
+ server.server_close()
1208
+
1209
+
1210
+ if __name__ == "__main__":
1211
+ run()
app/static/app.js ADDED
@@ -0,0 +1,710 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const state = {
2
+ documents: [],
3
+ reviewers: [],
4
+ notifications: [],
5
+ selectedId: null,
6
+ selectedDocument: null,
7
+ filter: "all",
8
+ view: "documents",
9
+ reviewerAction: "comment",
10
+ };
11
+
12
+ const els = {
13
+ fileInput: document.querySelector("#fileInput"),
14
+ uploadButton: document.querySelector("#uploadButton"),
15
+ dropZone: document.querySelector("#dropZone"),
16
+ ownerName: document.querySelector("#ownerName"),
17
+ ownerEmail: document.querySelector("#ownerEmail"),
18
+ ownerSlack: document.querySelector("#ownerSlack"),
19
+ ownerTeams: document.querySelector("#ownerTeams"),
20
+ sideTabs: document.querySelectorAll(".side-tab"),
21
+ documentsView: document.querySelector("#documentsView"),
22
+ reviewersView: document.querySelector("#reviewersView"),
23
+ notificationsView: document.querySelector("#notificationsView"),
24
+ notificationBadge: document.querySelector("#notificationBadge"),
25
+ filters: document.querySelectorAll(".filter"),
26
+ documentList: document.querySelector("#documentList"),
27
+ reviewerForm: document.querySelector("#reviewerForm"),
28
+ reviewerId: document.querySelector("#reviewerId"),
29
+ reviewerName: document.querySelector("#reviewerName"),
30
+ reviewerEmail: document.querySelector("#reviewerEmail"),
31
+ reviewerSlack: document.querySelector("#reviewerSlack"),
32
+ reviewerTeams: document.querySelector("#reviewerTeams"),
33
+ reviewerSaveButton: document.querySelector("#reviewerSaveButton"),
34
+ reviewerCancelButton: document.querySelector("#reviewerCancelButton"),
35
+ reviewerList: document.querySelector("#reviewerList"),
36
+ notificationList: document.querySelector("#notificationList"),
37
+ emptyState: document.querySelector("#emptyState"),
38
+ documentPanel: document.querySelector("#documentPanel"),
39
+ documentMeta: document.querySelector("#documentMeta"),
40
+ documentTitle: document.querySelector("#documentTitle"),
41
+ ownerLine: document.querySelector("#ownerLine"),
42
+ statusPill: document.querySelector("#statusPill"),
43
+ downloadButton: document.querySelector("#downloadButton"),
44
+ reviewButton: document.querySelector("#reviewButton"),
45
+ assignmentSummary: document.querySelector("#assignmentSummary"),
46
+ assignmentForm: document.querySelector("#assignmentForm"),
47
+ assignmentChoices: document.querySelector("#assignmentChoices"),
48
+ assignmentList: document.querySelector("#assignmentList"),
49
+ reviewerActionForm: document.querySelector("#reviewerActionForm"),
50
+ reviewerActionSelect: document.querySelector("#reviewerActionSelect"),
51
+ reviewerSignature: document.querySelector("#reviewerSignature"),
52
+ reviewerNote: document.querySelector("#reviewerNote"),
53
+ findings: document.querySelector("#findings"),
54
+ findingSummary: document.querySelector("#findingSummary"),
55
+ commentForm: document.querySelector("#commentForm"),
56
+ commentBody: document.querySelector("#commentBody"),
57
+ comments: document.querySelector("#comments"),
58
+ commentCount: document.querySelector("#commentCount"),
59
+ activityTimeline: document.querySelector("#activityTimeline"),
60
+ activityCount: document.querySelector("#activityCount"),
61
+ textPreview: document.querySelector("#textPreview"),
62
+ wordCount: document.querySelector("#wordCount"),
63
+ toast: document.querySelector("#toast"),
64
+ };
65
+
66
+ async function api(path, options = {}) {
67
+ return new Promise((resolve, reject) => {
68
+ const request = new XMLHttpRequest();
69
+ request.open(options.method || "GET", path, true);
70
+ for (const [key, value] of Object.entries(options.headers || {})) {
71
+ request.setRequestHeader(key, value);
72
+ }
73
+ request.onload = () => {
74
+ const contentType = request.getResponseHeader("Content-Type") || "";
75
+ const payload = contentType.includes("application/json") && request.responseText
76
+ ? JSON.parse(request.responseText)
77
+ : null;
78
+ if (request.status >= 200 && request.status < 300) {
79
+ resolve(payload);
80
+ } else {
81
+ reject(new Error(payload?.error || `Request failed with ${request.status}`));
82
+ }
83
+ };
84
+ request.onerror = () => reject(new Error("Request failed."));
85
+ request.send(options.body || null);
86
+ });
87
+ }
88
+
89
+ function showToast(message, isError = false) {
90
+ els.toast.textContent = message;
91
+ els.toast.classList.toggle("error", isError);
92
+ els.toast.classList.remove("hidden");
93
+ clearTimeout(showToast.timer);
94
+ showToast.timer = setTimeout(() => els.toast.classList.add("hidden"), 3600);
95
+ }
96
+
97
+ function formatDate(value) {
98
+ if (!value) return "Not recorded";
99
+ return new Intl.DateTimeFormat(undefined, {
100
+ month: "short",
101
+ day: "numeric",
102
+ hour: "numeric",
103
+ minute: "2-digit",
104
+ }).format(new Date(value));
105
+ }
106
+
107
+ function countsFor(document) {
108
+ const counts = { high: 0, medium: 0, low: 0 };
109
+ for (const finding of document.findings || []) {
110
+ counts[finding.severity] += 1;
111
+ }
112
+ return counts;
113
+ }
114
+
115
+ function contactLine(contact = {}) {
116
+ return [contact.email, contact.slack, contact.teams].filter(Boolean).join(" | ");
117
+ }
118
+
119
+ async function loadAll() {
120
+ const [documents, reviewers, notifications] = await Promise.all([
121
+ api("/api/documents"),
122
+ api("/api/reviewers"),
123
+ api("/api/notifications"),
124
+ ]);
125
+ state.documents = documents.documents;
126
+ state.reviewers = reviewers.reviewers;
127
+ state.notifications = notifications.notifications;
128
+ renderNavigation(notifications.unread_count || 0);
129
+ renderList();
130
+ renderReviewerList();
131
+ renderNotifications();
132
+
133
+ if (state.selectedId && state.documents.some((doc) => doc.id === state.selectedId)) {
134
+ await selectDocument(state.selectedId);
135
+ } else if (state.documents.length > 0 && !state.selectedId) {
136
+ await selectDocument(state.documents[0].id);
137
+ } else if (state.documents.length === 0) {
138
+ renderEmpty();
139
+ }
140
+ }
141
+
142
+ async function refreshSelected() {
143
+ const [documents, notifications] = await Promise.all([api("/api/documents"), api("/api/notifications")]);
144
+ state.documents = documents.documents;
145
+ state.notifications = notifications.notifications;
146
+ renderNavigation(notifications.unread_count || 0);
147
+ renderList();
148
+ renderNotifications();
149
+ if (state.selectedId) {
150
+ state.selectedDocument = await api(`/api/documents/${state.selectedId}`);
151
+ renderDocument();
152
+ }
153
+ }
154
+
155
+ function renderNavigation(unreadCount = 0) {
156
+ els.sideTabs.forEach((button) => button.classList.toggle("active", button.dataset.view === state.view));
157
+ els.documentsView.classList.toggle("hidden", state.view !== "documents");
158
+ els.reviewersView.classList.toggle("hidden", state.view !== "reviewers");
159
+ els.notificationsView.classList.toggle("hidden", state.view !== "notifications");
160
+ els.notificationBadge.textContent = `${unreadCount}`;
161
+ els.notificationBadge.classList.toggle("hidden", unreadCount === 0);
162
+ }
163
+
164
+ function renderList() {
165
+ const filtered = state.documents.filter((document) => {
166
+ if (state.filter === "all") return true;
167
+ if (state.filter === "in_review") return document.status === "in_review" || document.status === "uploaded";
168
+ return document.status === state.filter;
169
+ });
170
+
171
+ if (!filtered.length) {
172
+ els.documentList.innerHTML = `<p class="quiet">No documents in this view.</p>`;
173
+ return;
174
+ }
175
+
176
+ els.documentList.innerHTML = filtered
177
+ .map((document) => {
178
+ const counts = countsFor(document);
179
+ const assignments = document.assignment_counts || {};
180
+ return `
181
+ <button class="queue-item ${document.id === state.selectedId ? "active" : ""}" type="button" data-id="${document.id}">
182
+ <span class="queue-title">${escapeHtml(document.filename)}</span>
183
+ <span class="queue-meta">
184
+ <span>${escapeHtml(document.status_label)}</span>
185
+ <span>${document.word_count || 0} words</span>
186
+ </span>
187
+ <span class="queue-meta">
188
+ <span>${assignments.approved || 0}/${assignmentTotal(assignments)} approved</span>
189
+ <span class="mini-counts" title="High, medium, and low findings">
190
+ <span>${counts.high}</span><span>${counts.medium}</span><span>${counts.low}</span>
191
+ </span>
192
+ </span>
193
+ </button>
194
+ `;
195
+ })
196
+ .join("");
197
+
198
+ els.documentList.querySelectorAll("[data-id]").forEach((button) => {
199
+ button.addEventListener("click", () => selectDocument(button.dataset.id));
200
+ });
201
+ }
202
+
203
+ function assignmentTotal(counts) {
204
+ return (counts.pending || 0) + (counts.commented || 0) + (counts.changes_requested || 0) + (counts.approved || 0);
205
+ }
206
+
207
+ function renderEmpty() {
208
+ state.selectedDocument = null;
209
+ els.emptyState.classList.remove("hidden");
210
+ els.documentPanel.classList.add("hidden");
211
+ }
212
+
213
+ async function selectDocument(id) {
214
+ state.selectedId = id;
215
+ state.selectedDocument = await api(`/api/documents/${id}`);
216
+ renderList();
217
+ renderDocument();
218
+ }
219
+
220
+ function renderDocument() {
221
+ const document = state.selectedDocument;
222
+ if (!document) {
223
+ renderEmpty();
224
+ return;
225
+ }
226
+
227
+ els.emptyState.classList.add("hidden");
228
+ els.documentPanel.classList.remove("hidden");
229
+ els.documentTitle.textContent = document.filename;
230
+ els.documentMeta.textContent = `${document.extension.toUpperCase().replace(".", "")} | Uploaded ${formatDate(document.created_at)}`;
231
+ els.ownerLine.textContent = `Owner: ${document.owner?.name || "Owner"}${contactLine(document.owner) ? ` | ${contactLine(document.owner)}` : ""}`;
232
+ els.statusPill.textContent = document.status_label;
233
+ els.statusPill.className = `status-pill ${document.status}`;
234
+ els.wordCount.textContent = `${document.word_count || 0} words`;
235
+ els.textPreview.textContent = document.text || "";
236
+ els.downloadButton.onclick = () => {
237
+ window.location.href = `/api/documents/${document.id}/download`;
238
+ };
239
+
240
+ renderAssignments(document);
241
+ renderFindings(document);
242
+ renderComments(document);
243
+ renderActivity(document);
244
+ }
245
+
246
+ function renderAssignments(document) {
247
+ const selectedReviewerIds = new Set((document.assignments || []).map((assignment) => assignment.reviewer_id));
248
+ if (!state.reviewers.length) {
249
+ els.assignmentChoices.innerHTML = `<p class="quiet">Add reviewers in the sidebar first.</p>`;
250
+ } else {
251
+ els.assignmentChoices.innerHTML = state.reviewers
252
+ .map(
253
+ (reviewer) => `
254
+ <label class="check-card">
255
+ <input type="checkbox" value="${escapeHtml(reviewer.id)}" ${selectedReviewerIds.has(reviewer.id) ? "checked" : ""}>
256
+ <span>
257
+ <strong>${escapeHtml(reviewer.name)}</strong>
258
+ <small>${escapeHtml(contactLine(reviewer) || "No contact set")}</small>
259
+ </span>
260
+ </label>
261
+ `,
262
+ )
263
+ .join("");
264
+ }
265
+
266
+ const counts = document.assignment_counts || {};
267
+ const total = assignmentTotal(counts);
268
+ els.assignmentSummary.textContent = total ? `${counts.approved || 0}/${total} approved` : "No reviewers";
269
+
270
+ if (!(document.assignments || []).length) {
271
+ els.assignmentList.innerHTML = `<p class="quiet">No reviewers assigned.</p>`;
272
+ els.reviewerActionSelect.innerHTML = `<option value="">Assign a reviewer first</option>`;
273
+ els.reviewerActionForm.classList.add("muted-panel");
274
+ return;
275
+ }
276
+
277
+ els.reviewerActionForm.classList.remove("muted-panel");
278
+ els.assignmentList.innerHTML = document.assignments
279
+ .map(
280
+ (assignment) => `
281
+ <article class="assignment-card ${assignment.status}">
282
+ <div>
283
+ <strong>${escapeHtml(assignment.reviewer_name)}</strong>
284
+ <small>${escapeHtml(contactLine(assignment.reviewer_contact) || "No contact set")}</small>
285
+ </div>
286
+ <span class="status-chip ${assignment.status}">${escapeHtml(assignment.status_label)}</span>
287
+ ${assignment.approved_at ? `<small>Approved ${formatDate(assignment.approved_at)} as ${escapeHtml(assignment.approval_name)}</small>` : ""}
288
+ </article>
289
+ `,
290
+ )
291
+ .join("");
292
+ els.reviewerActionSelect.innerHTML = document.assignments
293
+ .map((assignment) => `<option value="${escapeHtml(assignment.reviewer_id)}">${escapeHtml(assignment.reviewer_name)}</option>`)
294
+ .join("");
295
+ }
296
+
297
+ function renderFindings(document) {
298
+ const findings = document.findings || [];
299
+ if (!document.reviewed_at) {
300
+ els.findingSummary.textContent = "Not reviewed";
301
+ els.findings.innerHTML = `<p class="quiet">Run a review to check required sections, placeholders, and vague language.</p>`;
302
+ return;
303
+ }
304
+
305
+ const counts = countsFor(document);
306
+ els.findingSummary.textContent = `${counts.high} high, ${counts.medium} medium, ${counts.low} low`;
307
+
308
+ if (!findings.length) {
309
+ els.findings.innerHTML = `<p class="quiet">No findings from the local rubric.</p>`;
310
+ return;
311
+ }
312
+
313
+ const groups = ["high", "medium", "low"]
314
+ .map((severity) => findings.filter((finding) => finding.severity === severity))
315
+ .filter((group) => group.length);
316
+
317
+ els.findings.innerHTML = groups
318
+ .map((group) => {
319
+ const severity = group[0].severity;
320
+ return `
321
+ <div class="finding-group">
322
+ <div class="severity-heading">
323
+ <span class="severity-dot ${severity}"></span>
324
+ ${severity} severity
325
+ </div>
326
+ ${group.map(renderFinding).join("")}
327
+ </div>
328
+ `;
329
+ })
330
+ .join("");
331
+ }
332
+
333
+ function renderFinding(finding) {
334
+ return `
335
+ <article class="finding ${finding.severity}">
336
+ <h4>${escapeHtml(finding.title)}</h4>
337
+ <p>${escapeHtml(finding.detail)}</p>
338
+ ${finding.snippet ? `<div class="snippet">${escapeHtml(finding.snippet)}</div>` : ""}
339
+ </article>
340
+ `;
341
+ }
342
+
343
+ function renderComments(document) {
344
+ const comments = document.comments || [];
345
+ els.commentCount.textContent = `${comments.length}`;
346
+ if (!comments.length) {
347
+ els.comments.innerHTML = `<p class="quiet">No comments yet.</p>`;
348
+ return;
349
+ }
350
+ els.comments.innerHTML = comments
351
+ .slice()
352
+ .reverse()
353
+ .map(
354
+ (comment) => `
355
+ <article class="comment">
356
+ <strong>${escapeHtml(comment.author)}</strong>
357
+ <time>${formatDate(comment.created_at)}</time>
358
+ <p>${escapeHtml(comment.body)}</p>
359
+ </article>
360
+ `,
361
+ )
362
+ .join("");
363
+ }
364
+
365
+ function renderActivity(document) {
366
+ const activity = document.activity || [];
367
+ els.activityCount.textContent = `${activity.length}`;
368
+ if (!activity.length) {
369
+ els.activityTimeline.innerHTML = `<p class="quiet">No activity yet.</p>`;
370
+ return;
371
+ }
372
+ els.activityTimeline.innerHTML = activity
373
+ .map(
374
+ (item) => `
375
+ <article class="timeline-item">
376
+ <span></span>
377
+ <div>
378
+ <strong>${escapeHtml(item.actor)}</strong>
379
+ <p>${escapeHtml(item.message)}</p>
380
+ <time>${formatDate(item.created_at)}</time>
381
+ </div>
382
+ </article>
383
+ `,
384
+ )
385
+ .join("");
386
+ }
387
+
388
+ function renderReviewerList() {
389
+ if (!state.reviewers.length) {
390
+ els.reviewerList.innerHTML = `<p class="quiet">No reviewers yet.</p>`;
391
+ return;
392
+ }
393
+ els.reviewerList.innerHTML = state.reviewers
394
+ .map(
395
+ (reviewer) => `
396
+ <article class="person-card">
397
+ <div>
398
+ <strong>${escapeHtml(reviewer.name)}</strong>
399
+ <small>${escapeHtml(contactLine(reviewer) || "No contact set")}</small>
400
+ </div>
401
+ <div class="icon-row">
402
+ <button class="secondary tiny" type="button" data-edit-reviewer="${escapeHtml(reviewer.id)}">Edit</button>
403
+ <button class="secondary tiny danger-text" type="button" data-delete-reviewer="${escapeHtml(reviewer.id)}">Remove</button>
404
+ </div>
405
+ </article>
406
+ `,
407
+ )
408
+ .join("");
409
+
410
+ els.reviewerList.querySelectorAll("[data-edit-reviewer]").forEach((button) => {
411
+ button.addEventListener("click", () => editReviewer(button.dataset.editReviewer));
412
+ });
413
+ els.reviewerList.querySelectorAll("[data-delete-reviewer]").forEach((button) => {
414
+ button.addEventListener("click", () => deleteReviewer(button.dataset.deleteReviewer));
415
+ });
416
+ }
417
+
418
+ function renderNotifications() {
419
+ if (!state.notifications.length) {
420
+ els.notificationList.innerHTML = `<p class="quiet">No notifications yet.</p>`;
421
+ return;
422
+ }
423
+ els.notificationList.innerHTML = state.notifications
424
+ .map(
425
+ (notification) => `
426
+ <article class="notification-card ${notification.read_at ? "" : "unread"}">
427
+ <div>
428
+ <strong>${escapeHtml(notification.recipient_name)}</strong>
429
+ <small>${escapeHtml(notification.recipient_type)} | ${formatDate(notification.created_at)}</small>
430
+ </div>
431
+ <p>${escapeHtml(notification.message)}</p>
432
+ <div class="icon-row">
433
+ <button class="secondary tiny" type="button" data-copy-notification="${escapeHtml(notification.id)}">Copy</button>
434
+ ${
435
+ notification.read_at
436
+ ? `<span class="quiet tiny-label">Read</span>`
437
+ : `<button class="secondary tiny" type="button" data-read-notification="${escapeHtml(notification.id)}">Mark read</button>`
438
+ }
439
+ </div>
440
+ </article>
441
+ `,
442
+ )
443
+ .join("");
444
+
445
+ els.notificationList.querySelectorAll("[data-copy-notification]").forEach((button) => {
446
+ button.addEventListener("click", () => copyNotification(button.dataset.copyNotification));
447
+ });
448
+ els.notificationList.querySelectorAll("[data-read-notification]").forEach((button) => {
449
+ button.addEventListener("click", () => markNotificationRead(button.dataset.readNotification));
450
+ });
451
+ }
452
+
453
+ async function uploadFile(file) {
454
+ if (!file) return;
455
+ const form = new FormData();
456
+ form.append("file", file);
457
+ form.append("owner_name", els.ownerName.value.trim());
458
+ form.append("owner_email", els.ownerEmail.value.trim());
459
+ form.append("owner_slack", els.ownerSlack.value.trim());
460
+ form.append("owner_teams", els.ownerTeams.value.trim());
461
+ els.uploadButton.disabled = true;
462
+ els.uploadButton.textContent = "Uploading...";
463
+ try {
464
+ const document = await api("/api/upload", { method: "POST", body: form });
465
+ showToast("Document uploaded.");
466
+ state.selectedId = document.id;
467
+ await loadAll();
468
+ } catch (error) {
469
+ showToast(error.message, true);
470
+ } finally {
471
+ els.uploadButton.disabled = false;
472
+ els.uploadButton.innerHTML = `<span class="button-icon">+</span>Upload document`;
473
+ els.fileInput.value = "";
474
+ }
475
+ }
476
+
477
+ async function refreshSelectedWith(action, message) {
478
+ if (!state.selectedId) return;
479
+ try {
480
+ state.selectedDocument = await api(`/api/documents/${state.selectedId}/${action}`, { method: "POST" });
481
+ showToast(message);
482
+ await refreshSelected();
483
+ } catch (error) {
484
+ showToast(error.message, true);
485
+ }
486
+ }
487
+
488
+ async function saveReviewer(event) {
489
+ event.preventDefault();
490
+ const payload = {
491
+ name: els.reviewerName.value.trim(),
492
+ email: els.reviewerEmail.value.trim(),
493
+ slack: els.reviewerSlack.value.trim(),
494
+ teams: els.reviewerTeams.value.trim(),
495
+ };
496
+ const id = els.reviewerId.value;
497
+ try {
498
+ if (id) {
499
+ await api(`/api/reviewers/${id}`, {
500
+ method: "PUT",
501
+ headers: { "Content-Type": "application/json" },
502
+ body: JSON.stringify(payload),
503
+ });
504
+ showToast("Reviewer updated.");
505
+ } else {
506
+ await api("/api/reviewers", {
507
+ method: "POST",
508
+ headers: { "Content-Type": "application/json" },
509
+ body: JSON.stringify(payload),
510
+ });
511
+ showToast("Reviewer added.");
512
+ }
513
+ resetReviewerForm();
514
+ await loadAll();
515
+ } catch (error) {
516
+ showToast(error.message, true);
517
+ }
518
+ }
519
+
520
+ function editReviewer(id) {
521
+ const reviewer = state.reviewers.find((item) => item.id === id);
522
+ if (!reviewer) return;
523
+ els.reviewerId.value = reviewer.id;
524
+ els.reviewerName.value = reviewer.name;
525
+ els.reviewerEmail.value = reviewer.email || "";
526
+ els.reviewerSlack.value = reviewer.slack || "";
527
+ els.reviewerTeams.value = reviewer.teams || "";
528
+ els.reviewerSaveButton.textContent = "Update reviewer";
529
+ els.reviewerCancelButton.classList.remove("hidden");
530
+ }
531
+
532
+ function resetReviewerForm() {
533
+ els.reviewerForm.reset();
534
+ els.reviewerId.value = "";
535
+ els.reviewerSaveButton.textContent = "Save reviewer";
536
+ els.reviewerCancelButton.classList.add("hidden");
537
+ }
538
+
539
+ async function deleteReviewer(id) {
540
+ const reviewer = state.reviewers.find((item) => item.id === id);
541
+ if (!reviewer) return;
542
+ if (!window.confirm(`Remove ${reviewer.name} from the reviewer directory? Historical assignments stay on documents.`)) {
543
+ return;
544
+ }
545
+ try {
546
+ await api(`/api/reviewers/${id}`, { method: "DELETE" });
547
+ showToast("Reviewer removed.");
548
+ await loadAll();
549
+ } catch (error) {
550
+ showToast(error.message, true);
551
+ }
552
+ }
553
+
554
+ async function assignReviewers(event) {
555
+ event.preventDefault();
556
+ if (!state.selectedId) return;
557
+ const reviewerIds = Array.from(els.assignmentChoices.querySelectorAll("input[type='checkbox']:checked")).map((input) => input.value);
558
+ try {
559
+ await api(`/api/documents/${state.selectedId}/assign-reviewers`, {
560
+ method: "POST",
561
+ headers: { "Content-Type": "application/json" },
562
+ body: JSON.stringify({ reviewer_ids: reviewerIds }),
563
+ });
564
+ showToast("Reviewer assignments updated.");
565
+ await refreshSelected();
566
+ } catch (error) {
567
+ showToast(error.message, true);
568
+ }
569
+ }
570
+
571
+ async function submitReviewerAction(event) {
572
+ event.preventDefault();
573
+ const submitter = event.submitter;
574
+ const action = submitter?.dataset.reviewerAction || state.reviewerAction;
575
+ const reviewerId = els.reviewerActionSelect.value;
576
+ const signature = els.reviewerSignature.value.trim();
577
+ const body = els.reviewerNote.value.trim();
578
+ if (!reviewerId) {
579
+ showToast("Choose an assigned reviewer.", true);
580
+ return;
581
+ }
582
+ if (action === "approve" && !signature) {
583
+ showToast("Enter a name or initials to approve.", true);
584
+ return;
585
+ }
586
+ if ((action === "comment" || action === "request") && !body) {
587
+ showToast("Add a note first.", true);
588
+ return;
589
+ }
590
+ if (action === "approve" && (state.selectedDocument?.findings || []).length) {
591
+ if (!window.confirm("This document still has review findings. Approve anyway?")) {
592
+ return;
593
+ }
594
+ }
595
+
596
+ const endpoint = {
597
+ comment: "reviewer-comment",
598
+ request: "reviewer-request-changes",
599
+ approve: "reviewer-approve",
600
+ }[action];
601
+
602
+ try {
603
+ await api(`/api/documents/${state.selectedId}/${endpoint}`, {
604
+ method: "POST",
605
+ headers: { "Content-Type": "application/json" },
606
+ body: JSON.stringify({ reviewer_id: reviewerId, signature, body }),
607
+ });
608
+ els.reviewerNote.value = "";
609
+ els.reviewerSignature.value = "";
610
+ showToast(action === "approve" ? "Reviewer approval recorded." : "Reviewer response recorded.");
611
+ await refreshSelected();
612
+ } catch (error) {
613
+ showToast(error.message, true);
614
+ }
615
+ }
616
+
617
+ async function copyNotification(id) {
618
+ const notification = state.notifications.find((item) => item.id === id);
619
+ if (!notification) return;
620
+ try {
621
+ await navigator.clipboard.writeText(notification.message);
622
+ showToast("Notification copied.");
623
+ } catch {
624
+ showToast(notification.message);
625
+ }
626
+ }
627
+
628
+ async function markNotificationRead(id) {
629
+ try {
630
+ await api(`/api/notifications/${id}/read`, { method: "POST" });
631
+ showToast("Notification marked read.");
632
+ const payload = await api("/api/notifications");
633
+ state.notifications = payload.notifications;
634
+ renderNavigation(payload.unread_count || 0);
635
+ renderNotifications();
636
+ } catch (error) {
637
+ showToast(error.message, true);
638
+ }
639
+ }
640
+
641
+ function escapeHtml(value) {
642
+ return String(value ?? "")
643
+ .replaceAll("&", "&amp;")
644
+ .replaceAll("<", "&lt;")
645
+ .replaceAll(">", "&gt;")
646
+ .replaceAll('"', "&quot;")
647
+ .replaceAll("'", "&#039;");
648
+ }
649
+
650
+ els.sideTabs.forEach((button) => {
651
+ button.addEventListener("click", () => {
652
+ state.view = button.dataset.view;
653
+ renderNavigation(state.notifications.filter((item) => !item.read_at).length);
654
+ });
655
+ });
656
+
657
+ els.uploadButton.addEventListener("click", () => els.fileInput.click());
658
+ els.fileInput.addEventListener("change", () => uploadFile(els.fileInput.files[0]));
659
+
660
+ ["dragenter", "dragover"].forEach((eventName) => {
661
+ els.dropZone.addEventListener(eventName, (event) => {
662
+ event.preventDefault();
663
+ els.dropZone.classList.add("dragging");
664
+ });
665
+ });
666
+
667
+ ["dragleave", "drop"].forEach((eventName) => {
668
+ els.dropZone.addEventListener(eventName, (event) => {
669
+ event.preventDefault();
670
+ els.dropZone.classList.remove("dragging");
671
+ });
672
+ });
673
+
674
+ els.dropZone.addEventListener("drop", (event) => uploadFile(event.dataTransfer.files[0]));
675
+
676
+ els.filters.forEach((button) => {
677
+ button.addEventListener("click", () => {
678
+ state.filter = button.dataset.filter;
679
+ els.filters.forEach((item) => item.classList.toggle("active", item === button));
680
+ renderList();
681
+ });
682
+ });
683
+
684
+ els.reviewerForm.addEventListener("submit", saveReviewer);
685
+ els.reviewerCancelButton.addEventListener("click", resetReviewerForm);
686
+ els.assignmentForm.addEventListener("submit", assignReviewers);
687
+ els.reviewerActionForm.addEventListener("submit", submitReviewerAction);
688
+ els.reviewButton.addEventListener("click", () => refreshSelectedWith("review", "Review complete."));
689
+
690
+ els.commentForm.addEventListener("submit", async (event) => {
691
+ event.preventDefault();
692
+ if (!state.selectedId) return;
693
+ const body = els.commentBody.value.trim();
694
+ if (!body) return;
695
+
696
+ try {
697
+ state.selectedDocument = await api(`/api/documents/${state.selectedId}/comments`, {
698
+ method: "POST",
699
+ headers: { "Content-Type": "application/json" },
700
+ body: JSON.stringify({ body, author: state.selectedDocument?.owner?.name || "Owner" }),
701
+ });
702
+ els.commentBody.value = "";
703
+ showToast("Comment added.");
704
+ await refreshSelected();
705
+ } catch (error) {
706
+ showToast(error.message, true);
707
+ }
708
+ });
709
+
710
+ loadAll().catch((error) => showToast(error.message, true));
app/static/index.html ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>SimpleDocReview</title>
7
+ <link rel="stylesheet" href="/static/styles.css">
8
+ </head>
9
+ <body>
10
+ <main class="app-shell">
11
+ <aside class="sidebar" aria-label="SimpleDocReview navigation">
12
+ <header class="brand">
13
+ <div>
14
+ <p class="eyebrow">Document Review</p>
15
+ <h1>SimpleDocReview</h1>
16
+ </div>
17
+ <span class="live-dot" title="Local app"></span>
18
+ </header>
19
+
20
+ <section class="upload-zone" id="dropZone">
21
+ <input id="fileInput" type="file" accept=".txt,.md,.docx">
22
+ <div class="owner-fields">
23
+ <input id="ownerName" type="text" placeholder="Owner name">
24
+ <input id="ownerEmail" type="email" placeholder="Owner email">
25
+ <input id="ownerSlack" type="text" placeholder="Owner Slack">
26
+ <input id="ownerTeams" type="text" placeholder="Owner Teams">
27
+ </div>
28
+ <button class="upload-button" id="uploadButton" type="button">
29
+ <span class="button-icon">+</span>
30
+ Upload document
31
+ </button>
32
+ <p>TXT, MD, or DOCX up to 5 MB</p>
33
+ </section>
34
+
35
+ <nav class="sidebar-tabs" aria-label="Workspace views">
36
+ <button class="side-tab active" type="button" data-view="documents">Docs</button>
37
+ <button class="side-tab" type="button" data-view="reviewers">Reviewers</button>
38
+ <button class="side-tab" type="button" data-view="notifications">
39
+ Inbox <span id="notificationBadge" class="badge hidden">0</span>
40
+ </button>
41
+ </nav>
42
+
43
+ <section id="documentsView" class="side-view">
44
+ <div class="filters" role="tablist" aria-label="Document status filters">
45
+ <button class="filter active" type="button" data-filter="all">All</button>
46
+ <button class="filter" type="button" data-filter="in_review">Review</button>
47
+ <button class="filter" type="button" data-filter="changes_requested">Changes</button>
48
+ <button class="filter" type="button" data-filter="approved">Approved</button>
49
+ </div>
50
+ <section class="queue" id="documentList" aria-live="polite"></section>
51
+ </section>
52
+
53
+ <section id="reviewersView" class="side-view hidden">
54
+ <form class="compact-form" id="reviewerForm">
55
+ <input id="reviewerId" type="hidden">
56
+ <input id="reviewerName" type="text" placeholder="Reviewer name" required>
57
+ <input id="reviewerEmail" type="email" placeholder="Email">
58
+ <input id="reviewerSlack" type="text" placeholder="Slack">
59
+ <input id="reviewerTeams" type="text" placeholder="Teams">
60
+ <div class="form-row">
61
+ <button class="primary" id="reviewerSaveButton" type="submit">Save reviewer</button>
62
+ <button class="secondary hidden" id="reviewerCancelButton" type="button">Cancel</button>
63
+ </div>
64
+ </form>
65
+ <div class="people-list" id="reviewerList"></div>
66
+ </section>
67
+
68
+ <section id="notificationsView" class="side-view hidden">
69
+ <div class="notification-list" id="notificationList"></div>
70
+ </section>
71
+ </aside>
72
+
73
+ <section class="workspace" aria-label="Review workspace">
74
+ <div class="empty-state" id="emptyState">
75
+ <div class="empty-mark">RD</div>
76
+ <h2>Select or upload a document</h2>
77
+ <p>Assign reviewers, capture approvals, and keep a local activity trail.</p>
78
+ </div>
79
+
80
+ <article class="document-panel hidden" id="documentPanel">
81
+ <header class="document-header">
82
+ <div>
83
+ <p class="eyebrow" id="documentMeta">Document</p>
84
+ <h2 id="documentTitle"></h2>
85
+ <p class="owner-line" id="ownerLine"></p>
86
+ </div>
87
+ <span class="status-pill" id="statusPill"></span>
88
+ </header>
89
+
90
+ <div class="actions" aria-label="Document actions">
91
+ <button class="secondary" id="downloadButton" type="button">
92
+ <span class="button-icon">v</span>
93
+ Download
94
+ </button>
95
+ <button class="secondary" id="reviewButton" type="button">
96
+ <span class="button-icon">?</span>
97
+ Run review
98
+ </button>
99
+ </div>
100
+
101
+ <section class="review-column assignment-panel">
102
+ <div class="section-heading">
103
+ <h3>Reviewer workflow</h3>
104
+ <span id="assignmentSummary">No reviewers</span>
105
+ </div>
106
+ <form class="assignment-form" id="assignmentForm">
107
+ <div class="check-grid" id="assignmentChoices"></div>
108
+ <button class="secondary" type="submit">Assign selected reviewers</button>
109
+ </form>
110
+ <div class="assignment-list" id="assignmentList"></div>
111
+ <form class="reviewer-action-form" id="reviewerActionForm">
112
+ <div class="form-row">
113
+ <select id="reviewerActionSelect"></select>
114
+ <input id="reviewerSignature" type="text" placeholder="Name or initials">
115
+ </div>
116
+ <textarea id="reviewerNote" rows="3" placeholder="Reviewer note"></textarea>
117
+ <div class="form-row">
118
+ <button class="secondary" type="submit" data-reviewer-action="comment">Add comment</button>
119
+ <button class="warning" type="submit" data-reviewer-action="request">Request changes</button>
120
+ <button class="primary" type="submit" data-reviewer-action="approve">Approve</button>
121
+ </div>
122
+ </form>
123
+ </section>
124
+
125
+ <div class="review-grid">
126
+ <section class="review-column">
127
+ <div class="section-heading">
128
+ <h3>Findings</h3>
129
+ <span id="findingSummary">Not reviewed</span>
130
+ </div>
131
+ <div id="findings"></div>
132
+ </section>
133
+
134
+ <section class="review-column">
135
+ <div class="section-heading">
136
+ <h3>Comments</h3>
137
+ <span id="commentCount">0</span>
138
+ </div>
139
+ <form class="comment-form" id="commentForm">
140
+ <textarea id="commentBody" rows="3" placeholder="Add an owner/general comment"></textarea>
141
+ <button class="secondary" type="submit">Add comment</button>
142
+ </form>
143
+ <div class="comments" id="comments"></div>
144
+ </section>
145
+ </div>
146
+
147
+ <section class="review-column">
148
+ <div class="section-heading">
149
+ <h3>Activity timeline</h3>
150
+ <span id="activityCount">0</span>
151
+ </div>
152
+ <div class="timeline" id="activityTimeline"></div>
153
+ </section>
154
+
155
+ <section class="preview">
156
+ <div class="section-heading">
157
+ <h3>Text preview</h3>
158
+ <span id="wordCount">0 words</span>
159
+ </div>
160
+ <pre id="textPreview"></pre>
161
+ </section>
162
+ </article>
163
+ </section>
164
+ </main>
165
+
166
+ <div class="toast hidden" id="toast" role="status" aria-live="polite"></div>
167
+ <script src="/static/app.js"></script>
168
+ </body>
169
+ </html>
app/static/styles.css ADDED
@@ -0,0 +1,838 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --ink: #172126;
3
+ --muted: #64737c;
4
+ --line: #d9e1e4;
5
+ --panel: #ffffff;
6
+ --wash: #f3f6f4;
7
+ --accent: #0f766e;
8
+ --accent-dark: #0a5c56;
9
+ --danger: #b42318;
10
+ --warning: #b85b00;
11
+ --low: #52606a;
12
+ --shadow: 0 18px 45px rgba(23, 33, 38, 0.12);
13
+ }
14
+
15
+ * {
16
+ box-sizing: border-box;
17
+ }
18
+
19
+ body {
20
+ margin: 0;
21
+ min-height: 100vh;
22
+ color: var(--ink);
23
+ background:
24
+ linear-gradient(180deg, rgba(15, 118, 110, 0.08), transparent 320px),
25
+ var(--wash);
26
+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
27
+ }
28
+
29
+ button,
30
+ input,
31
+ textarea {
32
+ font: inherit;
33
+ }
34
+
35
+ button {
36
+ border: 0;
37
+ cursor: pointer;
38
+ }
39
+
40
+ .app-shell {
41
+ display: grid;
42
+ grid-template-columns: 360px minmax(0, 1fr);
43
+ min-height: 100vh;
44
+ }
45
+
46
+ .sidebar {
47
+ display: flex;
48
+ flex-direction: column;
49
+ gap: 18px;
50
+ padding: 24px;
51
+ border-right: 1px solid var(--line);
52
+ background: rgba(255, 255, 255, 0.72);
53
+ backdrop-filter: blur(14px);
54
+ }
55
+
56
+ .brand {
57
+ display: flex;
58
+ align-items: flex-start;
59
+ justify-content: space-between;
60
+ gap: 16px;
61
+ }
62
+
63
+ .eyebrow {
64
+ margin: 0 0 6px;
65
+ color: var(--muted);
66
+ font-size: 0.75rem;
67
+ font-weight: 700;
68
+ letter-spacing: 0;
69
+ text-transform: uppercase;
70
+ }
71
+
72
+ h1,
73
+ h2,
74
+ h3,
75
+ p {
76
+ margin-top: 0;
77
+ }
78
+
79
+ h1 {
80
+ margin-bottom: 0;
81
+ font-size: 2rem;
82
+ line-height: 1.05;
83
+ }
84
+
85
+ h2 {
86
+ margin-bottom: 0;
87
+ font-size: clamp(1.4rem, 2vw, 2.3rem);
88
+ line-height: 1.08;
89
+ }
90
+
91
+ h3 {
92
+ margin-bottom: 0;
93
+ font-size: 1rem;
94
+ }
95
+
96
+ .live-dot {
97
+ width: 12px;
98
+ height: 12px;
99
+ margin-top: 9px;
100
+ border-radius: 999px;
101
+ background: #20a46b;
102
+ box-shadow: 0 0 0 5px rgba(32, 164, 107, 0.15);
103
+ }
104
+
105
+ .upload-zone {
106
+ display: grid;
107
+ gap: 10px;
108
+ padding: 16px;
109
+ border: 1px dashed #9eb3b1;
110
+ border-radius: 8px;
111
+ background: #f8fbfa;
112
+ transition: border-color 160ms ease, background 160ms ease;
113
+ }
114
+
115
+ .upload-zone.dragging {
116
+ border-color: var(--accent);
117
+ background: #e9f6f3;
118
+ }
119
+
120
+ #fileInput {
121
+ display: none;
122
+ }
123
+
124
+ .upload-zone p {
125
+ margin-bottom: 0;
126
+ color: var(--muted);
127
+ font-size: 0.88rem;
128
+ }
129
+
130
+ .upload-button,
131
+ .primary,
132
+ .secondary,
133
+ .warning {
134
+ display: inline-flex;
135
+ min-height: 40px;
136
+ align-items: center;
137
+ justify-content: center;
138
+ gap: 8px;
139
+ padding: 0 14px;
140
+ border-radius: 8px;
141
+ font-weight: 700;
142
+ transition: transform 120ms ease, box-shadow 120ms ease, background 120ms ease;
143
+ }
144
+
145
+ .upload-button,
146
+ .primary {
147
+ color: #fff;
148
+ background: var(--accent);
149
+ }
150
+
151
+ .upload-button:hover,
152
+ .primary:hover {
153
+ background: var(--accent-dark);
154
+ }
155
+
156
+ .secondary {
157
+ color: var(--ink);
158
+ background: #e8eeee;
159
+ }
160
+
161
+ .secondary:hover {
162
+ background: #dce5e5;
163
+ }
164
+
165
+ .warning {
166
+ color: #fff;
167
+ background: var(--warning);
168
+ }
169
+
170
+ .warning:hover {
171
+ background: #984a00;
172
+ }
173
+
174
+ .button-icon {
175
+ display: inline-grid;
176
+ min-width: 18px;
177
+ height: 18px;
178
+ place-items: center;
179
+ font-size: 0.76rem;
180
+ font-weight: 900;
181
+ line-height: 1;
182
+ }
183
+
184
+ .filters {
185
+ display: grid;
186
+ grid-template-columns: repeat(4, minmax(0, 1fr));
187
+ gap: 4px;
188
+ padding: 4px;
189
+ border: 1px solid var(--line);
190
+ border-radius: 8px;
191
+ background: #edf2f1;
192
+ }
193
+
194
+ .filter {
195
+ min-height: 34px;
196
+ border-radius: 6px;
197
+ color: var(--muted);
198
+ background: transparent;
199
+ font-size: 0.82rem;
200
+ font-weight: 800;
201
+ }
202
+
203
+ .filter.active {
204
+ color: var(--ink);
205
+ background: #fff;
206
+ box-shadow: 0 1px 4px rgba(23, 33, 38, 0.08);
207
+ }
208
+
209
+ .queue {
210
+ display: grid;
211
+ gap: 10px;
212
+ min-height: 0;
213
+ overflow: auto;
214
+ padding-right: 2px;
215
+ }
216
+
217
+ .queue-item {
218
+ display: grid;
219
+ gap: 8px;
220
+ width: 100%;
221
+ padding: 14px;
222
+ border: 1px solid var(--line);
223
+ border-radius: 8px;
224
+ color: var(--ink);
225
+ background: rgba(255, 255, 255, 0.86);
226
+ text-align: left;
227
+ }
228
+
229
+ .queue-item.active {
230
+ border-color: var(--accent);
231
+ box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.12);
232
+ }
233
+
234
+ .queue-title {
235
+ overflow: hidden;
236
+ font-weight: 800;
237
+ text-overflow: ellipsis;
238
+ white-space: nowrap;
239
+ }
240
+
241
+ .queue-meta {
242
+ display: flex;
243
+ align-items: center;
244
+ justify-content: space-between;
245
+ gap: 10px;
246
+ color: var(--muted);
247
+ font-size: 0.8rem;
248
+ }
249
+
250
+ .mini-counts {
251
+ display: inline-flex;
252
+ gap: 6px;
253
+ }
254
+
255
+ .mini-counts span {
256
+ min-width: 22px;
257
+ padding: 2px 6px;
258
+ border-radius: 999px;
259
+ background: #eef2f2;
260
+ text-align: center;
261
+ font-weight: 800;
262
+ }
263
+
264
+ .workspace {
265
+ min-width: 0;
266
+ padding: 30px;
267
+ }
268
+
269
+ .empty-state,
270
+ .document-panel {
271
+ width: min(1120px, 100%);
272
+ margin: 0 auto;
273
+ }
274
+
275
+ .empty-state {
276
+ display: grid;
277
+ min-height: calc(100vh - 60px);
278
+ place-content: center;
279
+ text-align: center;
280
+ }
281
+
282
+ .empty-mark {
283
+ display: grid;
284
+ width: 70px;
285
+ height: 70px;
286
+ place-items: center;
287
+ margin: 0 auto 20px;
288
+ border-radius: 8px;
289
+ color: #fff;
290
+ background: var(--accent);
291
+ font-weight: 900;
292
+ }
293
+
294
+ .empty-state p {
295
+ color: var(--muted);
296
+ }
297
+
298
+ .document-panel {
299
+ display: grid;
300
+ gap: 20px;
301
+ }
302
+
303
+ .hidden {
304
+ display: none !important;
305
+ }
306
+
307
+ .document-header {
308
+ display: flex;
309
+ align-items: flex-start;
310
+ justify-content: space-between;
311
+ gap: 20px;
312
+ }
313
+
314
+ .status-pill {
315
+ display: inline-flex;
316
+ min-height: 32px;
317
+ align-items: center;
318
+ padding: 0 12px;
319
+ border-radius: 999px;
320
+ color: var(--accent-dark);
321
+ background: #dff2ee;
322
+ font-size: 0.8rem;
323
+ font-weight: 900;
324
+ white-space: nowrap;
325
+ }
326
+
327
+ .status-pill.changes_requested {
328
+ color: #823b00;
329
+ background: #ffe6c7;
330
+ }
331
+
332
+ .status-pill.approved {
333
+ color: #0d5d36;
334
+ background: #dff6e9;
335
+ }
336
+
337
+ .status-pill.uploaded {
338
+ color: #44515a;
339
+ background: #e9eeee;
340
+ }
341
+
342
+ .actions {
343
+ display: flex;
344
+ flex-wrap: wrap;
345
+ gap: 10px;
346
+ }
347
+
348
+ .review-grid {
349
+ display: grid;
350
+ grid-template-columns: minmax(0, 1.2fr) minmax(300px, 0.8fr);
351
+ gap: 18px;
352
+ align-items: start;
353
+ }
354
+
355
+ .review-column,
356
+ .preview {
357
+ display: grid;
358
+ gap: 14px;
359
+ padding: 18px;
360
+ border: 1px solid var(--line);
361
+ border-radius: 8px;
362
+ background: rgba(255, 255, 255, 0.9);
363
+ box-shadow: var(--shadow);
364
+ }
365
+
366
+ .section-heading {
367
+ display: flex;
368
+ align-items: center;
369
+ justify-content: space-between;
370
+ gap: 12px;
371
+ }
372
+
373
+ .section-heading span {
374
+ color: var(--muted);
375
+ font-size: 0.86rem;
376
+ font-weight: 800;
377
+ }
378
+
379
+ .finding-group {
380
+ display: grid;
381
+ gap: 10px;
382
+ margin-bottom: 16px;
383
+ }
384
+
385
+ .finding-group:last-child {
386
+ margin-bottom: 0;
387
+ }
388
+
389
+ .severity-heading {
390
+ display: flex;
391
+ align-items: center;
392
+ gap: 8px;
393
+ color: var(--muted);
394
+ font-size: 0.78rem;
395
+ font-weight: 900;
396
+ text-transform: uppercase;
397
+ }
398
+
399
+ .severity-dot {
400
+ width: 9px;
401
+ height: 9px;
402
+ border-radius: 99px;
403
+ background: var(--low);
404
+ }
405
+
406
+ .severity-dot.high {
407
+ background: var(--danger);
408
+ }
409
+
410
+ .severity-dot.medium {
411
+ background: var(--warning);
412
+ }
413
+
414
+ .finding {
415
+ display: grid;
416
+ gap: 6px;
417
+ padding: 12px;
418
+ border: 1px solid var(--line);
419
+ border-left: 4px solid var(--low);
420
+ border-radius: 8px;
421
+ background: #fbfcfc;
422
+ }
423
+
424
+ .finding.high {
425
+ border-left-color: var(--danger);
426
+ }
427
+
428
+ .finding.medium {
429
+ border-left-color: var(--warning);
430
+ }
431
+
432
+ .finding h4 {
433
+ margin: 0;
434
+ font-size: 0.95rem;
435
+ }
436
+
437
+ .finding p {
438
+ margin-bottom: 0;
439
+ color: var(--muted);
440
+ font-size: 0.88rem;
441
+ }
442
+
443
+ .snippet {
444
+ padding: 8px;
445
+ border-radius: 6px;
446
+ background: #eef3f2;
447
+ color: #344147;
448
+ font-size: 0.82rem;
449
+ }
450
+
451
+ .comment-form {
452
+ display: grid;
453
+ gap: 10px;
454
+ }
455
+
456
+ textarea {
457
+ width: 100%;
458
+ min-height: 92px;
459
+ resize: vertical;
460
+ border: 1px solid var(--line);
461
+ border-radius: 8px;
462
+ padding: 12px;
463
+ color: var(--ink);
464
+ background: #fbfcfc;
465
+ }
466
+
467
+ textarea:focus {
468
+ outline: 3px solid rgba(15, 118, 110, 0.18);
469
+ border-color: var(--accent);
470
+ }
471
+
472
+ input,
473
+ select {
474
+ width: 100%;
475
+ min-height: 38px;
476
+ border: 1px solid var(--line);
477
+ border-radius: 8px;
478
+ padding: 0 11px;
479
+ color: var(--ink);
480
+ background: #fbfcfc;
481
+ }
482
+
483
+ input:focus,
484
+ select:focus {
485
+ outline: 3px solid rgba(15, 118, 110, 0.18);
486
+ border-color: var(--accent);
487
+ }
488
+
489
+ .comments {
490
+ display: grid;
491
+ gap: 10px;
492
+ }
493
+
494
+ .comment {
495
+ padding: 12px;
496
+ border-radius: 8px;
497
+ background: #f3f7f6;
498
+ }
499
+
500
+ .comment strong {
501
+ display: block;
502
+ margin-bottom: 4px;
503
+ }
504
+
505
+ .comment time {
506
+ color: var(--muted);
507
+ font-size: 0.78rem;
508
+ }
509
+
510
+ .comment p {
511
+ margin: 8px 0 0;
512
+ white-space: pre-wrap;
513
+ }
514
+
515
+ .preview pre {
516
+ max-height: 480px;
517
+ margin: 0;
518
+ overflow: auto;
519
+ border-radius: 8px;
520
+ padding: 16px;
521
+ background: #162126;
522
+ color: #edf7f4;
523
+ font-family: "Cascadia Mono", Consolas, monospace;
524
+ font-size: 0.88rem;
525
+ line-height: 1.55;
526
+ white-space: pre-wrap;
527
+ }
528
+
529
+ .toast {
530
+ position: fixed;
531
+ right: 22px;
532
+ bottom: 22px;
533
+ max-width: min(420px, calc(100vw - 44px));
534
+ padding: 12px 14px;
535
+ border-radius: 8px;
536
+ color: #fff;
537
+ background: #172126;
538
+ box-shadow: var(--shadow);
539
+ font-weight: 700;
540
+ }
541
+
542
+ .toast.error {
543
+ background: var(--danger);
544
+ }
545
+
546
+ .quiet {
547
+ color: var(--muted);
548
+ }
549
+
550
+ .owner-fields,
551
+ .compact-form,
552
+ .assignment-form,
553
+ .reviewer-action-form {
554
+ display: grid;
555
+ gap: 10px;
556
+ }
557
+
558
+ .owner-fields {
559
+ grid-template-columns: 1fr 1fr;
560
+ }
561
+
562
+ .sidebar-tabs {
563
+ display: grid;
564
+ grid-template-columns: repeat(3, minmax(0, 1fr));
565
+ gap: 4px;
566
+ padding: 4px;
567
+ border: 1px solid var(--line);
568
+ border-radius: 8px;
569
+ background: #edf2f1;
570
+ }
571
+
572
+ .side-tab {
573
+ display: inline-flex;
574
+ min-height: 34px;
575
+ align-items: center;
576
+ justify-content: center;
577
+ gap: 6px;
578
+ border-radius: 6px;
579
+ color: var(--muted);
580
+ background: transparent;
581
+ font-size: 0.82rem;
582
+ font-weight: 800;
583
+ }
584
+
585
+ .side-tab.active {
586
+ color: var(--ink);
587
+ background: #fff;
588
+ box-shadow: 0 1px 4px rgba(23, 33, 38, 0.08);
589
+ }
590
+
591
+ .badge {
592
+ display: inline-grid;
593
+ min-width: 20px;
594
+ height: 20px;
595
+ place-items: center;
596
+ border-radius: 999px;
597
+ color: #fff;
598
+ background: var(--danger);
599
+ font-size: 0.72rem;
600
+ font-weight: 900;
601
+ }
602
+
603
+ .side-view {
604
+ display: grid;
605
+ gap: 14px;
606
+ }
607
+
608
+ .form-row {
609
+ display: flex;
610
+ flex-wrap: wrap;
611
+ gap: 10px;
612
+ }
613
+
614
+ .form-row > * {
615
+ flex: 1 1 150px;
616
+ }
617
+
618
+ .people-list,
619
+ .notification-list,
620
+ .assignment-list,
621
+ .timeline {
622
+ display: grid;
623
+ gap: 10px;
624
+ }
625
+
626
+ .person-card,
627
+ .notification-card,
628
+ .assignment-card {
629
+ display: grid;
630
+ gap: 8px;
631
+ padding: 12px;
632
+ border: 1px solid var(--line);
633
+ border-radius: 8px;
634
+ background: rgba(255, 255, 255, 0.86);
635
+ }
636
+
637
+ .notification-card.unread {
638
+ border-color: var(--accent);
639
+ box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.11);
640
+ }
641
+
642
+ .person-card small,
643
+ .notification-card small,
644
+ .assignment-card small {
645
+ display: block;
646
+ margin-top: 3px;
647
+ color: var(--muted);
648
+ font-size: 0.78rem;
649
+ }
650
+
651
+ .notification-card p {
652
+ margin-bottom: 0;
653
+ color: #344147;
654
+ font-size: 0.88rem;
655
+ }
656
+
657
+ .icon-row {
658
+ display: flex;
659
+ flex-wrap: wrap;
660
+ gap: 8px;
661
+ }
662
+
663
+ .tiny {
664
+ min-height: 30px;
665
+ padding: 0 10px;
666
+ font-size: 0.76rem;
667
+ }
668
+
669
+ .tiny-label {
670
+ align-self: center;
671
+ font-size: 0.78rem;
672
+ font-weight: 800;
673
+ }
674
+
675
+ .danger-text {
676
+ color: var(--danger);
677
+ }
678
+
679
+ .owner-line {
680
+ margin: 8px 0 0;
681
+ color: var(--muted);
682
+ font-size: 0.9rem;
683
+ }
684
+
685
+ .assignment-panel {
686
+ box-shadow: none;
687
+ }
688
+
689
+ .check-grid {
690
+ display: grid;
691
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
692
+ gap: 10px;
693
+ }
694
+
695
+ .check-card {
696
+ display: grid;
697
+ grid-template-columns: 22px minmax(0, 1fr);
698
+ gap: 8px;
699
+ align-items: start;
700
+ padding: 10px;
701
+ border: 1px solid var(--line);
702
+ border-radius: 8px;
703
+ background: #fbfcfc;
704
+ }
705
+
706
+ .check-card input {
707
+ width: 18px;
708
+ min-height: 18px;
709
+ margin-top: 2px;
710
+ padding: 0;
711
+ }
712
+
713
+ .check-card small {
714
+ display: block;
715
+ margin-top: 2px;
716
+ color: var(--muted);
717
+ font-size: 0.78rem;
718
+ }
719
+
720
+ .assignment-card {
721
+ grid-template-columns: minmax(0, 1fr) auto;
722
+ align-items: center;
723
+ }
724
+
725
+ .assignment-card > small {
726
+ grid-column: 1 / -1;
727
+ }
728
+
729
+ .status-chip {
730
+ display: inline-flex;
731
+ min-height: 28px;
732
+ align-items: center;
733
+ justify-content: center;
734
+ padding: 0 10px;
735
+ border-radius: 999px;
736
+ color: #44515a;
737
+ background: #e9eeee;
738
+ font-size: 0.76rem;
739
+ font-weight: 900;
740
+ white-space: nowrap;
741
+ }
742
+
743
+ .status-chip.commented,
744
+ .status-chip.pending {
745
+ color: var(--accent-dark);
746
+ background: #dff2ee;
747
+ }
748
+
749
+ .status-chip.changes_requested {
750
+ color: #823b00;
751
+ background: #ffe6c7;
752
+ }
753
+
754
+ .status-chip.approved {
755
+ color: #0d5d36;
756
+ background: #dff6e9;
757
+ }
758
+
759
+ .muted-panel {
760
+ opacity: 0.62;
761
+ }
762
+
763
+ .timeline-item {
764
+ display: grid;
765
+ grid-template-columns: 16px minmax(0, 1fr);
766
+ gap: 10px;
767
+ }
768
+
769
+ .timeline-item > span {
770
+ width: 10px;
771
+ height: 10px;
772
+ margin-top: 7px;
773
+ border-radius: 999px;
774
+ background: var(--accent);
775
+ box-shadow: 0 0 0 4px rgba(15, 118, 110, 0.12);
776
+ }
777
+
778
+ .timeline-item div {
779
+ padding: 10px 12px;
780
+ border: 1px solid var(--line);
781
+ border-radius: 8px;
782
+ background: #fbfcfc;
783
+ }
784
+
785
+ .timeline-item p {
786
+ margin: 4px 0;
787
+ color: #344147;
788
+ font-size: 0.88rem;
789
+ }
790
+
791
+ .timeline-item time {
792
+ color: var(--muted);
793
+ font-size: 0.78rem;
794
+ }
795
+
796
+ @media (max-width: 980px) {
797
+ .app-shell {
798
+ grid-template-columns: 1fr;
799
+ }
800
+
801
+ .sidebar {
802
+ border-right: 0;
803
+ border-bottom: 1px solid var(--line);
804
+ }
805
+
806
+ .queue {
807
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
808
+ max-height: 340px;
809
+ }
810
+
811
+ .review-grid {
812
+ grid-template-columns: 1fr;
813
+ }
814
+ }
815
+
816
+ @media (max-width: 640px) {
817
+ .sidebar,
818
+ .workspace {
819
+ padding: 18px;
820
+ }
821
+
822
+ .filters {
823
+ grid-template-columns: repeat(2, 1fr);
824
+ }
825
+
826
+ .owner-fields {
827
+ grid-template-columns: 1fr;
828
+ }
829
+
830
+ .document-header {
831
+ display: grid;
832
+ }
833
+
834
+ .actions {
835
+ display: grid;
836
+ grid-template-columns: 1fr;
837
+ }
838
+ }
index.html CHANGED
@@ -1,19 +1,171 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
  <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>SimpleDocReview</title>
7
+ <link rel="stylesheet" href="/static/styles.css">
8
+ </head>
9
+ <body>
10
+ <main class="app-shell">
11
+ <aside class="sidebar" aria-label="SimpleDocReview navigation">
12
+ <header class="brand">
13
+ <div>
14
+ <p class="eyebrow">Document Review</p>
15
+ <h1>SimpleDocReview</h1>
16
+ </div>
17
+ <span class="live-dot" title="Local app"></span>
18
+ </header>
19
+
20
+ <section class="upload-zone" id="dropZone">
21
+ <input id="fileInput" type="file" accept=".txt,.md,.docx">
22
+ <div class="owner-fields">
23
+ <input id="ownerName" type="text" placeholder="Owner name">
24
+ <input id="ownerEmail" type="email" placeholder="Owner email">
25
+ <input id="ownerSlack" type="text" placeholder="Owner Slack">
26
+ <input id="ownerTeams" type="text" placeholder="Owner Teams">
27
+ </div>
28
+ <button class="upload-button" id="uploadButton" type="button">
29
+ <span class="button-icon">+</span>
30
+ Upload document
31
+ </button>
32
+ <p>TXT, MD, or DOCX up to 5 MB</p>
33
+ </section>
34
+
35
+ <nav class="sidebar-tabs" aria-label="Workspace views">
36
+ <button class="side-tab active" type="button" data-view="documents">Docs</button>
37
+ <button class="side-tab" type="button" data-view="reviewers">Reviewers</button>
38
+ <button class="side-tab" type="button" data-view="notifications">
39
+ Inbox <span id="notificationBadge" class="badge hidden">0</span>
40
+ </button>
41
+ </nav>
42
+
43
+ <section id="documentsView" class="side-view">
44
+ <div class="filters" role="tablist" aria-label="Document status filters">
45
+ <button class="filter active" type="button" data-filter="all">All</button>
46
+ <button class="filter" type="button" data-filter="in_review">Review</button>
47
+ <button class="filter" type="button" data-filter="changes_requested">Changes</button>
48
+ <button class="filter" type="button" data-filter="approved">Approved</button>
49
+ </div>
50
+ <section class="queue" id="documentList" aria-live="polite"></section>
51
+ </section>
52
+
53
+ <section id="reviewersView" class="side-view hidden">
54
+ <form class="compact-form" id="reviewerForm">
55
+ <input id="reviewerId" type="hidden">
56
+ <input id="reviewerName" type="text" placeholder="Reviewer name" required>
57
+ <input id="reviewerEmail" type="email" placeholder="Email">
58
+ <input id="reviewerSlack" type="text" placeholder="Slack">
59
+ <input id="reviewerTeams" type="text" placeholder="Teams">
60
+ <div class="form-row">
61
+ <button class="primary" id="reviewerSaveButton" type="submit">Save reviewer</button>
62
+ <button class="secondary hidden" id="reviewerCancelButton" type="button">Cancel</button>
63
+ </div>
64
+ </form>
65
+ <div class="people-list" id="reviewerList"></div>
66
+ </section>
67
+
68
+ <section id="notificationsView" class="side-view hidden">
69
+ <div class="notification-list" id="notificationList"></div>
70
+ </section>
71
+ </aside>
72
+
73
+ <section class="workspace" aria-label="Review workspace">
74
+ <div class="empty-state" id="emptyState">
75
+ <div class="empty-mark">RD</div>
76
+ <h2>Select or upload a document</h2>
77
+ <p>Assign reviewers, capture approvals, and keep a local activity trail.</p>
78
+ </div>
79
+
80
+ <article class="document-panel hidden" id="documentPanel">
81
+ <header class="document-header">
82
+ <div>
83
+ <p class="eyebrow" id="documentMeta">Document</p>
84
+ <h2 id="documentTitle"></h2>
85
+ <p class="owner-line" id="ownerLine"></p>
86
+ </div>
87
+ <span class="status-pill" id="statusPill"></span>
88
+ </header>
89
+
90
+ <div class="actions" aria-label="Document actions">
91
+ <button class="secondary" id="downloadButton" type="button">
92
+ <span class="button-icon">v</span>
93
+ Download
94
+ </button>
95
+ <button class="secondary" id="reviewButton" type="button">
96
+ <span class="button-icon">?</span>
97
+ Run review
98
+ </button>
99
+ </div>
100
+
101
+ <section class="review-column assignment-panel">
102
+ <div class="section-heading">
103
+ <h3>Reviewer workflow</h3>
104
+ <span id="assignmentSummary">No reviewers</span>
105
+ </div>
106
+ <form class="assignment-form" id="assignmentForm">
107
+ <div class="check-grid" id="assignmentChoices"></div>
108
+ <button class="secondary" type="submit">Assign selected reviewers</button>
109
+ </form>
110
+ <div class="assignment-list" id="assignmentList"></div>
111
+ <form class="reviewer-action-form" id="reviewerActionForm">
112
+ <div class="form-row">
113
+ <select id="reviewerActionSelect"></select>
114
+ <input id="reviewerSignature" type="text" placeholder="Name or initials">
115
+ </div>
116
+ <textarea id="reviewerNote" rows="3" placeholder="Reviewer note"></textarea>
117
+ <div class="form-row">
118
+ <button class="secondary" type="submit" data-reviewer-action="comment">Add comment</button>
119
+ <button class="warning" type="submit" data-reviewer-action="request">Request changes</button>
120
+ <button class="primary" type="submit" data-reviewer-action="approve">Approve</button>
121
+ </div>
122
+ </form>
123
+ </section>
124
+
125
+ <div class="review-grid">
126
+ <section class="review-column">
127
+ <div class="section-heading">
128
+ <h3>Findings</h3>
129
+ <span id="findingSummary">Not reviewed</span>
130
+ </div>
131
+ <div id="findings"></div>
132
+ </section>
133
+
134
+ <section class="review-column">
135
+ <div class="section-heading">
136
+ <h3>Comments</h3>
137
+ <span id="commentCount">0</span>
138
+ </div>
139
+ <form class="comment-form" id="commentForm">
140
+ <textarea id="commentBody" rows="3" placeholder="Add an owner/general comment"></textarea>
141
+ <button class="secondary" type="submit">Add comment</button>
142
+ </form>
143
+ <div class="comments" id="comments"></div>
144
+ </section>
145
+ </div>
146
+
147
+ <section class="review-column">
148
+ <div class="section-heading">
149
+ <h3>Activity timeline</h3>
150
+ <span id="activityCount">0</span>
151
+ </div>
152
+ <div class="timeline" id="activityTimeline"></div>
153
+ </section>
154
+
155
+ <section class="preview">
156
+ <div class="section-heading">
157
+ <h3>Text preview</h3>
158
+ <span id="wordCount">0 words</span>
159
+ </div>
160
+ <pre id="textPreview"></pre>
161
+ </section>
162
+ </article>
163
+ </section>
164
+ </main>
165
+
166
+ <div class="toast hidden" id="toast" role="status" aria-live="polite"></div>
167
+ <script src="/sdr-api-core.js"></script>
168
+ <script src="/sdr-api-shim.js"></script>
169
+ <script src="/static/app.js"></script>
170
+ </body>
171
  </html>
overlay/ported-from.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_comment": [
3
+ "The upstream files overlay/sdr-api-core.js was ported from, and their",
4
+ "SHA-256 as of that port. scripts/build-static.ps1 refuses to build when a",
5
+ "hash no longer matches app/, because the overlay is a reimplementation:",
6
+ "an upstream change to a route, a rubric rule, or a status transition has to",
7
+ "be carried across by hand or the Space silently diverges from the real app.",
8
+ "",
9
+ "After reading the upstream diff and updating the overlay, record the new",
10
+ "hashes with: .\\scripts\\build-static.ps1 -AcceptUpstreamChanges"
11
+ ],
12
+ "portedAt": "2026-08-20",
13
+ "upstreamCommit": "2c22f4147eddc711ad3be3fa18d2f10150642a2d",
14
+ "sources": {
15
+ "app.py": "008df80aaec9b971e42162328972823a01d6cb85e9ce5013dfe5a2d9949ba939",
16
+ "static/app.js": "3b24215db79c090d3565eb58be4ececd006b96b7605fac474b24daf0dc47c6ef"
17
+ }
18
+ }
overlay/sdr-api-core.js ADDED
@@ -0,0 +1,1717 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * sdr-api-core.js - SimpleDocReview's HTTP API, ported to run without a server.
3
+ *
4
+ * A Hugging Face Static Space has no compute, so `app.py` cannot run. This file
5
+ * is a port of every route upstream's `ReviewHandler` serves and of the logic
6
+ * behind them: the rubric analyzer, the DOCX text extractor, status
7
+ * recalculation, the notification queue, and the record migrations.
8
+ *
9
+ * It contains no DOM and no storage engine. Everything environment-specific
10
+ * arrives through `createApi()`:
11
+ *
12
+ * store persistence (app.py's data/reviews.json + uploads/ pair)
13
+ * now clock (app.py utc_now)
14
+ * uuidHex identity (app.py uuid.uuid4().hex)
15
+ * inflateRaw DEFLATE (app.py zipfile)
16
+ *
17
+ * That separation is what makes it testable: `sdr-api-shim.js` supplies
18
+ * IndexedDB and the browser clock, while `tests/parity/` supplies an in-memory
19
+ * store and a fixed clock so these responses can be diffed against the real
20
+ * Python server's.
21
+ *
22
+ * Comments name the app.py function each part mirrors. When upstream changes
23
+ * that file, change this one - never the other way round.
24
+ */
25
+ (function (root, factory) {
26
+ "use strict";
27
+ var api = factory();
28
+ if (typeof module === "object" && module !== null && module.exports) {
29
+ module.exports = api;
30
+ }
31
+ if (root) {
32
+ root.SdrApiCore = api;
33
+ }
34
+ })(typeof globalThis !== "undefined" ? globalThis : this, function () {
35
+ "use strict";
36
+
37
+ // --------------------------------------------------------------- constants
38
+ // app.py: MAX_UPLOAD_BYTES, ALLOWED_EXTENSIONS, CONTACT_FIELDS, *_LABELS.
39
+
40
+ var MAX_UPLOAD_BYTES = 5 * 1024 * 1024;
41
+ var ALLOWED_EXTENSIONS = [".txt", ".md", ".docx"];
42
+ var CONTACT_FIELDS = ["email", "slack", "teams"];
43
+
44
+ var STATUS_LABELS = {
45
+ uploaded: "Uploaded",
46
+ in_review: "In review",
47
+ changes_requested: "Changes requested",
48
+ approved: "Approved"
49
+ };
50
+
51
+ var ASSIGNMENT_LABELS = {
52
+ pending: "Pending",
53
+ commented: "Commented",
54
+ changes_requested: "Changes requested",
55
+ approved: "Approved"
56
+ };
57
+
58
+ var SEVERITY_ORDER = { high: 0, medium: 1, low: 2 };
59
+
60
+ var DOWNLOAD_TYPES = {
61
+ ".txt": "text/plain",
62
+ ".md": "text/markdown",
63
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
64
+ };
65
+
66
+ // Python's `\w` is Unicode-aware where JavaScript's is ASCII-only, so the
67
+ // port uses Unicode property escapes. `\b[\w'-]+\b` can only begin and end on
68
+ // a word character - an apostrophe or hyphen at either edge fails the word
69
+ // boundary - which is what the outer/inner split below spells out.
70
+ var WORD_PATTERN = /[\p{L}\p{N}_](?:[\p{L}\p{N}_'-]*[\p{L}\p{N}_])?/gu;
71
+
72
+ // ------------------------------------------------------------------ errors
73
+
74
+ /**
75
+ * An error carrying the status app.py would have replied with.
76
+ *
77
+ * app.py maps `ValueError` to 400 and calls `send_error_json(..., NOT_FOUND)`
78
+ * for missing records, so the status has to travel with the message for the
79
+ * responses to stay identical.
80
+ */
81
+ function apiError(message, status) {
82
+ var error = new Error(message);
83
+ error.apiStatus = status || 400;
84
+ return error;
85
+ }
86
+
87
+ function badZip(message) {
88
+ // app.py catches zipfile.BadZipFile in do_POST and replies with this text.
89
+ return apiError(message || "The DOCX file appears to be invalid.", 400);
90
+ }
91
+
92
+ // ----------------------------------------------------------------- helpers
93
+
94
+ function two(value) {
95
+ return value < 10 ? "0" + value : String(value);
96
+ }
97
+
98
+ /** app.py utc_now(): an ISO-8601 UTC stamp truncated to whole seconds. */
99
+ function defaultNow() {
100
+ var when = new Date();
101
+ return (
102
+ when.getUTCFullYear() +
103
+ "-" + two(when.getUTCMonth() + 1) +
104
+ "-" + two(when.getUTCDate()) +
105
+ "T" + two(when.getUTCHours()) +
106
+ ":" + two(when.getUTCMinutes()) +
107
+ ":" + two(when.getUTCSeconds()) +
108
+ "+00:00"
109
+ );
110
+ }
111
+
112
+ /** app.py uuid.uuid4().hex: 32 lowercase hex characters, no dashes. */
113
+ function defaultUuidHex() {
114
+ var bytes = new Uint8Array(16);
115
+ globalThis.crypto.getRandomValues(bytes);
116
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
117
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
118
+ var hex = "";
119
+ for (var index = 0; index < bytes.length; index += 1) {
120
+ hex += (bytes[index] < 16 ? "0" : "") + bytes[index].toString(16);
121
+ }
122
+ return hex;
123
+ }
124
+
125
+ /** DEFLATE with no zlib wrapper - what a ZIP member stores. */
126
+ function defaultInflateRaw(bytes) {
127
+ if (typeof DecompressionStream === "undefined") {
128
+ return Promise.reject(
129
+ badZip("This browser cannot read DOCX files: DecompressionStream is unavailable.")
130
+ );
131
+ }
132
+ var stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
133
+ return new Response(stream).arrayBuffer().then(function (buffer) {
134
+ return new Uint8Array(buffer);
135
+ });
136
+ }
137
+
138
+ /** Python `str(value or "")`: falsy values collapse to the empty string. */
139
+ function pyStr(value) {
140
+ if (value === undefined || value === null || value === false || value === 0 || value === "") {
141
+ return "";
142
+ }
143
+ if (Array.isArray(value) && value.length === 0) {
144
+ return "";
145
+ }
146
+ return String(value);
147
+ }
148
+
149
+ /** app.py clean_text(). */
150
+ function cleanText(value, fallback, maxLength) {
151
+ var limit = maxLength === undefined ? 240 : maxLength;
152
+ var text = pyStr(value).trim();
153
+ return (text || (fallback === undefined ? "" : fallback)).slice(0, limit);
154
+ }
155
+
156
+ /** Python re.escape(), for the characters these patterns actually contain. */
157
+ function escapeRegExp(value) {
158
+ return String(value).replace(/[.*+?^${}()|[\]\\\-]/g, "\\$&");
159
+ }
160
+
161
+ function emptyContact() {
162
+ return { email: "", slack: "", teams: "" };
163
+ }
164
+
165
+ function isPlainObject(value) {
166
+ return typeof value === "object" && value !== null && !Array.isArray(value);
167
+ }
168
+
169
+ function hasOwn(target, key) {
170
+ return Object.prototype.hasOwnProperty.call(target, key);
171
+ }
172
+
173
+ /** app.py normalize_contact(). */
174
+ function normalizeContact(payload) {
175
+ var source = isPlainObject(payload) ? payload : {};
176
+ var contact = {};
177
+ CONTACT_FIELDS.forEach(function (field) {
178
+ contact[field] = cleanText(source[field], "", 240);
179
+ });
180
+ return contact;
181
+ }
182
+
183
+ /** app.py owner_from_payload(). */
184
+ function ownerFromPayload(payload) {
185
+ var source = isPlainObject(payload) ? payload : {};
186
+ var owner = { name: cleanText(source.name || source.owner_name, "Owner", 120) };
187
+ var contact = normalizeContact(source);
188
+ CONTACT_FIELDS.forEach(function (field) {
189
+ owner[field] = contact[field];
190
+ });
191
+ return owner;
192
+ }
193
+
194
+ /**
195
+ * Stable descending sort on one string key.
196
+ *
197
+ * Python's `sorted(..., reverse=True)` keeps equal elements in their original
198
+ * order rather than reversing them. These timestamps have one-second
199
+ * resolution, so ties are routine and a plain `.reverse()` would reorder
200
+ * same-second activity that the Python server leaves alone.
201
+ */
202
+ function sortByDesc(items, key) {
203
+ return items.slice().sort(function (left, right) {
204
+ var a = left[key] || "";
205
+ var b = right[key] || "";
206
+ if (a === b) return 0;
207
+ return a < b ? 1 : -1;
208
+ });
209
+ }
210
+
211
+ function sortByAsc(items, read) {
212
+ return items.slice().sort(function (left, right) {
213
+ var a = read(left);
214
+ var b = read(right);
215
+ if (a === b) return 0;
216
+ return a < b ? -1 : 1;
217
+ });
218
+ }
219
+
220
+ // ----------------------------------------------------- filenames and bytes
221
+
222
+ /** app.py sanitize_filename(). */
223
+ function sanitizeFilename(filename) {
224
+ var name = pyStr(filename) || "document";
225
+ var segments = name.split(/[\\/]/);
226
+ name = segments[segments.length - 1].trim();
227
+
228
+ var dot = name.lastIndexOf(".");
229
+ var stem = name;
230
+ var suffix = "";
231
+ // pathlib keeps a leading dot in the stem ('.env' -> stem '.env') and reads
232
+ // a trailing dot as no suffix at all ('notes.' -> stem 'notes.').
233
+ if (dot > 0 && dot < name.length - 1) {
234
+ stem = name.slice(0, dot);
235
+ suffix = name.slice(dot).toLowerCase();
236
+ }
237
+ if (!stem) stem = "document";
238
+
239
+ var cleaned = stem.replace(/[^A-Za-z0-9._ -]+/g, "-").replace(/^[ .\-_]+|[ .\-_]+$/g, "");
240
+ return (cleaned || "document") + suffix;
241
+ }
242
+
243
+ /** pathlib's Path(name).suffix.lower(). */
244
+ function extensionOf(filename) {
245
+ var name = pyStr(filename);
246
+ var segments = name.split(/[\\/]/);
247
+ name = segments[segments.length - 1];
248
+ var dot = name.lastIndexOf(".");
249
+ if (dot <= 0 || dot === name.length - 1) return "";
250
+ return name.slice(dot).toLowerCase();
251
+ }
252
+
253
+ function tryDecode(bytes, encoding) {
254
+ try {
255
+ return new TextDecoder(encoding, { fatal: true }).decode(bytes);
256
+ } catch (error) {
257
+ return null;
258
+ }
259
+ }
260
+
261
+ /**
262
+ * app.py decode_text_bytes(): utf-8-sig, then utf-16, then cp1252, then utf-8
263
+ * with replacement characters.
264
+ *
265
+ * TextDecoder("utf-8") strips a leading BOM, which is what utf-8-sig does.
266
+ * Python's utf-16 codec consumes a BOM when present and assumes
267
+ * little-endian when it is absent.
268
+ *
269
+ * One knowing divergence: WHATWG windows-1252 maps the five bytes Python's
270
+ * cp1252 rejects (0x81, 0x8D, 0x8F, 0x90, 0x9D) rather than raising, so a
271
+ * file Python would fall through to replacement-character utf-8 decodes here
272
+ * as windows-1252 instead.
273
+ */
274
+ function decodeTextBytes(bytes) {
275
+ var utf8 = tryDecode(bytes, "utf-8");
276
+ if (utf8 !== null) return utf8;
277
+
278
+ if (bytes.length % 2 === 0) {
279
+ var bigEndian = bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff;
280
+ var utf16 = tryDecode(bytes, bigEndian ? "utf-16be" : "utf-16le");
281
+ if (utf16 !== null) return utf16;
282
+ }
283
+
284
+ var cp1252 = tryDecode(bytes, "windows-1252");
285
+ if (cp1252 !== null) return cp1252;
286
+
287
+ return new TextDecoder("utf-8").decode(bytes);
288
+ }
289
+
290
+ // --------------------------------------------------------------- ZIP/DOCX
291
+
292
+ function readUint16(bytes, offset) {
293
+ return bytes[offset] | (bytes[offset + 1] << 8);
294
+ }
295
+
296
+ function readUint32(bytes, offset) {
297
+ return (
298
+ (bytes[offset] |
299
+ (bytes[offset + 1] << 8) |
300
+ (bytes[offset + 2] << 16) |
301
+ (bytes[offset + 3] << 24)) >>> 0
302
+ );
303
+ }
304
+
305
+ function findEndOfCentralDirectory(bytes) {
306
+ // The record is 22 bytes plus a comment of at most 65535, so it lies within
307
+ // the last 65557 bytes. Scan backwards for its signature.
308
+ var earliest = Math.max(0, bytes.length - (22 + 65535));
309
+ for (var offset = bytes.length - 22; offset >= earliest; offset -= 1) {
310
+ if (readUint32(bytes, offset) === 0x06054b50) return offset;
311
+ }
312
+ return -1;
313
+ }
314
+
315
+ /**
316
+ * Locate one member of a ZIP archive and return its stored bytes.
317
+ *
318
+ * Just enough of the format to read a DOCX. Sizes come from the central
319
+ * directory because a local header may defer them to a data descriptor, and
320
+ * Word writes members either stored or deflated. ZIP64 is rejected rather
321
+ * than guessed at; Word does not produce it for a 5 MB document.
322
+ */
323
+ function findZipMember(bytes, wanted) {
324
+ var eocd = findEndOfCentralDirectory(bytes);
325
+ if (eocd < 0) throw badZip();
326
+
327
+ var entryCount = readUint16(bytes, eocd + 10);
328
+ var directoryOffset = readUint32(bytes, eocd + 16);
329
+ if (entryCount === 0xffff || directoryOffset === 0xffffffff) {
330
+ throw badZip("This DOCX file uses ZIP64, which this static build cannot read.");
331
+ }
332
+
333
+ var cursor = directoryOffset;
334
+ var decoder = new TextDecoder("utf-8");
335
+ for (var index = 0; index < entryCount; index += 1) {
336
+ if (cursor + 46 > bytes.length || readUint32(bytes, cursor) !== 0x02014b50) {
337
+ throw badZip();
338
+ }
339
+ var method = readUint16(bytes, cursor + 10);
340
+ var compressedSize = readUint32(bytes, cursor + 20);
341
+ var nameLength = readUint16(bytes, cursor + 28);
342
+ var extraLength = readUint16(bytes, cursor + 30);
343
+ var commentLength = readUint16(bytes, cursor + 32);
344
+ var localOffset = readUint32(bytes, cursor + 42);
345
+ var name = decoder.decode(bytes.subarray(cursor + 46, cursor + 46 + nameLength));
346
+
347
+ if (name === wanted) {
348
+ if (localOffset + 30 > bytes.length || readUint32(bytes, localOffset) !== 0x04034b50) {
349
+ throw badZip();
350
+ }
351
+ var localNameLength = readUint16(bytes, localOffset + 26);
352
+ var localExtraLength = readUint16(bytes, localOffset + 28);
353
+ var dataStart = localOffset + 30 + localNameLength + localExtraLength;
354
+ if (dataStart + compressedSize > bytes.length) throw badZip();
355
+ return {
356
+ method: method,
357
+ data: bytes.subarray(dataStart, dataStart + compressedSize)
358
+ };
359
+ }
360
+
361
+ cursor += 46 + nameLength + extraLength + commentLength;
362
+ }
363
+ return null;
364
+ }
365
+
366
+ /** Python html.unescape(), narrowed to what WordprocessingML emits. */
367
+ function unescapeXml(value) {
368
+ return String(value).replace(
369
+ /&(?:#(\d+)|#[xX]([0-9a-fA-F]+)|(amp|lt|gt|quot|apos|nbsp));/g,
370
+ function (match, decimal, hex, named) {
371
+ if (decimal) return String.fromCodePoint(parseInt(decimal, 10));
372
+ if (hex) return String.fromCodePoint(parseInt(hex, 16));
373
+ return {
374
+ amp: "&",
375
+ lt: "<",
376
+ gt: ">",
377
+ quot: '"',
378
+ apos: "'",
379
+ nbsp: " "
380
+ }[named];
381
+ }
382
+ );
383
+ }
384
+
385
+ /** app.py extract_docx_text(). */
386
+ function extractDocxText(bytes, inflateRaw) {
387
+ var member = findZipMember(bytes, "word/document.xml");
388
+ if (!member) {
389
+ // app.py turns zipfile's KeyError into this ValueError.
390
+ throw apiError("The DOCX file does not contain document text.", 400);
391
+ }
392
+
393
+ var raw;
394
+ if (member.method === 0) {
395
+ raw = Promise.resolve(member.data);
396
+ } else if (member.method === 8) {
397
+ raw = inflateRaw(member.data);
398
+ } else {
399
+ raw = Promise.reject(badZip("This DOCX file uses an unsupported compression method."));
400
+ }
401
+
402
+ return raw.then(function (xmlBytes) {
403
+ var xmlText = new TextDecoder("utf-8").decode(xmlBytes);
404
+ var paragraphPattern = /<w:p\b[^>]*>([\s\S]*?)<\/w:p>/g;
405
+ var lines = [];
406
+ var paragraph;
407
+ while ((paragraph = paragraphPattern.exec(xmlText)) !== null) {
408
+ var runPattern = /<w:t\b[^>]*>([\s\S]*?)<\/w:t>/g;
409
+ var runs = [];
410
+ var run;
411
+ while ((run = runPattern.exec(paragraph[1])) !== null) {
412
+ runs.push(unescapeXml(run[1]));
413
+ }
414
+ if (runs.length) lines.push(runs.join(""));
415
+ }
416
+ return lines
417
+ .map(function (line) { return line.trim(); })
418
+ .filter(function (line) { return line.length > 0; })
419
+ .join("\n");
420
+ });
421
+ }
422
+
423
+ /** app.py extract_text(). */
424
+ function extractText(filename, bytes, inflateRaw) {
425
+ var extension = extensionOf(filename);
426
+ if (extension === ".txt" || extension === ".md") {
427
+ return Promise.resolve(decodeTextBytes(bytes).trim());
428
+ }
429
+ if (extension === ".docx") {
430
+ return Promise.resolve()
431
+ .then(function () {
432
+ return extractDocxText(bytes, inflateRaw);
433
+ })
434
+ .then(function (text) {
435
+ return text.trim();
436
+ });
437
+ }
438
+ return Promise.reject(apiError("Unsupported document type.", 400));
439
+ }
440
+
441
+ // --------------------------------------------------------------- analyzer
442
+
443
+ function countWords(text) {
444
+ var matches = text.match(WORD_PATTERN);
445
+ return matches ? matches.length : 0;
446
+ }
447
+
448
+ /** app.py snippet_for(). */
449
+ function snippetFor(text, pattern) {
450
+ var search = new RegExp(pattern.source, pattern.flags.replace("g", ""));
451
+ var match = search.exec(text);
452
+ if (!match) return "";
453
+ var start = Math.max(0, match.index - 70);
454
+ var end = Math.min(text.length, match.index + match[0].length + 70);
455
+ return text.slice(start, end).replace(/\s+/g, " ").trim();
456
+ }
457
+
458
+ /** app.py has_section(). */
459
+ function hasSection(text, terms) {
460
+ for (var index = 0; index < terms.length; index += 1) {
461
+ var term = escapeRegExp(terms[index]);
462
+ if (new RegExp("^\\s*(?:#+\\s*)?" + term + "\\b", "im").test(text)) return true;
463
+ if (new RegExp("\\b" + term + "\\s*:", "i").test(text)) return true;
464
+ }
465
+ return false;
466
+ }
467
+
468
+ var SECTION_CHECKS = [
469
+ ["purpose", ["purpose", "objective"], "Purpose or objective"],
470
+ ["scope", ["scope", "applicability"], "Scope"],
471
+ ["owner", ["owner", "document owner", "responsible party"], "Owner"],
472
+ ["date", ["date", "effective date", "review date"], "Date or review date"],
473
+ ["risk", ["risk", "risks", "risk assessment"], "Risk section"],
474
+ ["approval", ["approval", "approved by", "signature", "sign-off"], "Approval or signature"]
475
+ ];
476
+
477
+ var PLACEHOLDER_CHECKS = [
478
+ ["todo", /\bTODO\b|\bTBD\b|\bTBA\b/i],
479
+ ["insert", /\[(?:insert|add|fill in)[^\]]*\]|<\s*(?:insert|add|fill in)[^>]*>/i],
480
+ ["blank", /_{4,}|\{\{[^}]+\}\}/]
481
+ ];
482
+
483
+ var VAGUE_LANGUAGE = [
484
+ "best effort",
485
+ "as needed",
486
+ "reasonable",
487
+ "as appropriate",
488
+ "when possible",
489
+ "from time to time"
490
+ ];
491
+
492
+ var LONG_SENTENCE_PATTERN = /[^.!?]{260,}[.!?]/;
493
+
494
+ /** app.py analyze_document(). */
495
+ function analyzeDocument(text, now) {
496
+ var findings = [];
497
+ var normalized = pyStr(text).trim();
498
+ var wordCount = countWords(normalized);
499
+
500
+ SECTION_CHECKS.forEach(function (check) {
501
+ var key = check[0];
502
+ var label = check[2];
503
+ if (!hasSection(normalized, check[1])) {
504
+ findings.push({
505
+ id: "missing-" + key,
506
+ severity: key === "approval" ? "high" : "medium",
507
+ title: "Missing " + label.toLowerCase(),
508
+ detail: "Add a clear " + label.toLowerCase() + " section or label before approval.",
509
+ snippet: ""
510
+ });
511
+ }
512
+ });
513
+
514
+ PLACEHOLDER_CHECKS.forEach(function (check) {
515
+ var pattern = check[1];
516
+ if (pattern.test(normalized)) {
517
+ findings.push({
518
+ id: "placeholder-" + check[0],
519
+ severity: "high",
520
+ title: "Unresolved placeholder",
521
+ detail: "Replace template placeholders before the document can be considered final.",
522
+ snippet: snippetFor(normalized, pattern)
523
+ });
524
+ }
525
+ });
526
+
527
+ VAGUE_LANGUAGE.forEach(function (phrase) {
528
+ var pattern = new RegExp("\\b" + escapeRegExp(phrase) + "\\b", "i");
529
+ if (pattern.test(normalized)) {
530
+ findings.push({
531
+ id: "vague-" + phrase.split(" ").join("-"),
532
+ severity: "medium",
533
+ title: 'Vague language: "' + phrase + '"',
534
+ detail: "Make the requirement measurable, accountable, or time-bound.",
535
+ snippet: snippetFor(normalized, pattern)
536
+ });
537
+ }
538
+ });
539
+
540
+ if (wordCount < 80) {
541
+ findings.push({
542
+ id: "short-document",
543
+ severity: "low",
544
+ title: "Very short document",
545
+ detail: "Confirm the document has enough context for reviewers and approvers.",
546
+ snippet: ""
547
+ });
548
+ }
549
+
550
+ if (LONG_SENTENCE_PATTERN.test(normalized)) {
551
+ findings.push({
552
+ id: "long-sentence",
553
+ severity: "low",
554
+ title: "Long sentence",
555
+ detail: "Break long sentences into shorter reviewable statements.",
556
+ snippet: snippetFor(normalized, LONG_SENTENCE_PATTERN)
557
+ });
558
+ }
559
+
560
+ // app.py sorts on (severity rank, title). Compare code units rather than
561
+ // locale: Python compares strings by code point, and these titles contain
562
+ // quote marks that a locale-aware comparison orders differently.
563
+ findings.sort(function (left, right) {
564
+ if (SEVERITY_ORDER[left.severity] !== SEVERITY_ORDER[right.severity]) {
565
+ return SEVERITY_ORDER[left.severity] - SEVERITY_ORDER[right.severity];
566
+ }
567
+ if (left.title === right.title) return 0;
568
+ return left.title < right.title ? -1 : 1;
569
+ });
570
+
571
+ return {
572
+ reviewed_at: now(),
573
+ word_count: wordCount,
574
+ findings: findings,
575
+ counts: {
576
+ high: findings.filter(function (item) { return item.severity === "high"; }).length,
577
+ medium: findings.filter(function (item) { return item.severity === "medium"; }).length,
578
+ low: findings.filter(function (item) { return item.severity === "low"; }).length
579
+ }
580
+ };
581
+ }
582
+
583
+ // ------------------------------------------------------------------ the API
584
+
585
+ /**
586
+ * Build an API instance over one storage backend.
587
+ *
588
+ * @param {object} options
589
+ * @param {object} options.store load/save the record store and uploads
590
+ * @param {function} [options.now] app.py utc_now
591
+ * @param {function} [options.uuidHex] app.py uuid.uuid4().hex
592
+ * @param {function} [options.inflateRaw] raw DEFLATE, for DOCX
593
+ */
594
+ function createApi(options) {
595
+ var settings = options || {};
596
+ var store = settings.store;
597
+ var now = settings.now || defaultNow;
598
+ var uuidHex = settings.uuidHex || defaultUuidHex;
599
+ var inflateRaw = settings.inflateRaw || defaultInflateRaw;
600
+
601
+ if (!store) throw new Error("createApi requires a store.");
602
+
603
+ // ------------------------------------------------------------ migrations
604
+ // Ported from app.py's migrate_* family. The default objects are built
605
+ // eagerly, exactly as Python builds its `defaults` dict, so each call
606
+ // consumes one id from `uuidHex` whether or not the id is used. The parity
607
+ // tests depend on that: they run both implementations off the same
608
+ // deterministic id sequence.
609
+
610
+ function migrateReviewer(reviewer) {
611
+ var changed = false;
612
+ var timestamp = now();
613
+ var defaults = {
614
+ id: uuidHex(),
615
+ name: "Reviewer",
616
+ created_at: timestamp,
617
+ updated_at: timestamp
618
+ };
619
+ Object.keys(defaults).forEach(function (key) {
620
+ if (!reviewer[key]) {
621
+ reviewer[key] = defaults[key];
622
+ changed = true;
623
+ }
624
+ });
625
+ CONTACT_FIELDS.forEach(function (field) {
626
+ if (!hasOwn(reviewer, field)) {
627
+ reviewer[field] = "";
628
+ changed = true;
629
+ }
630
+ });
631
+ return changed;
632
+ }
633
+
634
+ function migrateNotification(notification) {
635
+ var changed = false;
636
+ var defaults = {
637
+ id: uuidHex(),
638
+ recipient_type: "owner",
639
+ recipient_name: "Owner",
640
+ recipient_contact: emptyContact(),
641
+ document_id: "",
642
+ document_title: "",
643
+ event: "notice",
644
+ message: "",
645
+ created_at: now(),
646
+ read_at: null
647
+ };
648
+ Object.keys(defaults).forEach(function (key) {
649
+ if (!hasOwn(notification, key)) {
650
+ notification[key] = defaults[key];
651
+ changed = true;
652
+ }
653
+ });
654
+ if (!isPlainObject(notification.recipient_contact)) {
655
+ notification.recipient_contact = emptyContact();
656
+ changed = true;
657
+ } else {
658
+ CONTACT_FIELDS.forEach(function (field) {
659
+ if (!hasOwn(notification.recipient_contact, field)) {
660
+ notification.recipient_contact[field] = "";
661
+ changed = true;
662
+ }
663
+ });
664
+ }
665
+ return changed;
666
+ }
667
+
668
+ function migrateAssignment(assignment) {
669
+ var changed = false;
670
+ var timestamp = now();
671
+ var defaults = {
672
+ id: uuidHex(),
673
+ reviewer_id: "",
674
+ reviewer_name: "Reviewer",
675
+ reviewer_contact: emptyContact(),
676
+ status: "pending",
677
+ status_label: "Pending",
678
+ assigned_at: timestamp,
679
+ updated_at: timestamp,
680
+ approved_at: null,
681
+ approval_name: "",
682
+ approval_initials: "",
683
+ comments: []
684
+ };
685
+ Object.keys(defaults).forEach(function (key) {
686
+ if (!hasOwn(assignment, key)) {
687
+ assignment[key] = defaults[key];
688
+ changed = true;
689
+ }
690
+ });
691
+ var label = hasOwn(ASSIGNMENT_LABELS, assignment.status)
692
+ ? ASSIGNMENT_LABELS[assignment.status]
693
+ : assignment.status;
694
+ if (assignment.status_label !== label) {
695
+ assignment.status_label = label;
696
+ changed = true;
697
+ }
698
+ if (!isPlainObject(assignment.reviewer_contact)) {
699
+ assignment.reviewer_contact = emptyContact();
700
+ changed = true;
701
+ } else {
702
+ CONTACT_FIELDS.forEach(function (field) {
703
+ if (!hasOwn(assignment.reviewer_contact, field)) {
704
+ assignment.reviewer_contact[field] = "";
705
+ changed = true;
706
+ }
707
+ });
708
+ }
709
+ if (!Array.isArray(assignment.comments)) {
710
+ assignment.comments = [];
711
+ changed = true;
712
+ }
713
+ return changed;
714
+ }
715
+
716
+ /** app.py build_legacy_activity(). */
717
+ function buildLegacyActivity(record) {
718
+ var owner = isPlainObject(record.owner) ? record.owner : {};
719
+ var activity = [
720
+ {
721
+ id: uuidHex(),
722
+ type: "uploaded",
723
+ actor: owner.name || "Owner",
724
+ message: "Uploaded " + (record.filename || "document") + ".",
725
+ created_at: record.created_at || now()
726
+ }
727
+ ];
728
+ if (record.reviewed_at) {
729
+ activity.push({
730
+ id: uuidHex(),
731
+ type: "review_run",
732
+ actor: "System",
733
+ message: "Ran the local rubric review.",
734
+ created_at: record.reviewed_at
735
+ });
736
+ }
737
+ (Array.isArray(record.comments) ? record.comments : []).forEach(function (comment) {
738
+ activity.push({
739
+ id: uuidHex(),
740
+ type: "comment_added",
741
+ actor: comment.author || "Reviewer",
742
+ message: "Commented: " + pyStr(comment.body).slice(0, 120),
743
+ created_at: comment.created_at || now()
744
+ });
745
+ });
746
+ if (record.approved_at) {
747
+ activity.push({
748
+ id: uuidHex(),
749
+ type: "approved",
750
+ actor: "Reviewer",
751
+ message: "Approved the document.",
752
+ created_at: record.approved_at
753
+ });
754
+ }
755
+ return sortByAsc(activity, function (item) { return item.created_at; });
756
+ }
757
+
758
+ function migrateDocument(record) {
759
+ var changed = false;
760
+ var timestamp = now();
761
+ var defaults = {
762
+ id: uuidHex(),
763
+ filename: "document",
764
+ extension: ".txt",
765
+ status: "uploaded",
766
+ created_at: timestamp,
767
+ updated_at: timestamp,
768
+ reviewed_at: null,
769
+ approved_at: null,
770
+ word_count: 0,
771
+ findings: [],
772
+ comments: []
773
+ };
774
+ Object.keys(defaults).forEach(function (key) {
775
+ if (!hasOwn(record, key)) {
776
+ record[key] = defaults[key];
777
+ changed = true;
778
+ }
779
+ });
780
+
781
+ if (!isPlainObject(record.owner)) {
782
+ record.owner = ownerFromPayload({});
783
+ changed = true;
784
+ } else {
785
+ var owner = ownerFromPayload(record.owner);
786
+ if (JSON.stringify(owner) !== JSON.stringify(record.owner)) {
787
+ record.owner = owner;
788
+ changed = true;
789
+ }
790
+ }
791
+
792
+ if (!Array.isArray(record.assignments)) {
793
+ record.assignments = [];
794
+ changed = true;
795
+ }
796
+ record.assignments.forEach(function (assignment) {
797
+ changed = migrateAssignment(assignment) || changed;
798
+ });
799
+
800
+ if (!Array.isArray(record.activity) || record.activity.length === 0) {
801
+ record.activity = buildLegacyActivity(record);
802
+ changed = true;
803
+ }
804
+
805
+ return changed;
806
+ }
807
+
808
+ function migrateDb(data) {
809
+ var changed = false;
810
+ if (!Array.isArray(data.documents)) {
811
+ data.documents = [];
812
+ changed = true;
813
+ }
814
+ if (!Array.isArray(data.reviewers)) {
815
+ data.reviewers = [];
816
+ changed = true;
817
+ }
818
+ if (!Array.isArray(data.notifications)) {
819
+ data.notifications = [];
820
+ changed = true;
821
+ }
822
+ data.reviewers.forEach(function (reviewer) {
823
+ changed = migrateReviewer(reviewer) || changed;
824
+ });
825
+ data.notifications.forEach(function (notification) {
826
+ changed = migrateNotification(notification) || changed;
827
+ });
828
+ data.documents.forEach(function (record) {
829
+ changed = migrateDocument(record) || changed;
830
+ });
831
+ return changed;
832
+ }
833
+
834
+ /** app.py load_db(): read, migrate, and write back when migration ran. */
835
+ function loadDb() {
836
+ return Promise.resolve(store.load()).then(function (loaded) {
837
+ var data = isPlainObject(loaded)
838
+ ? loaded
839
+ : { documents: [], reviewers: [], notifications: [] };
840
+ if (migrateDb(data)) {
841
+ return Promise.resolve(store.save(data)).then(function () {
842
+ return data;
843
+ });
844
+ }
845
+ return data;
846
+ });
847
+ }
848
+
849
+ function saveDb(data) {
850
+ return Promise.resolve(store.save(data));
851
+ }
852
+
853
+ // --------------------------------------------------------- record shapes
854
+
855
+ /** app.py add_activity(). */
856
+ function addActivity(record, eventType, actor, message, timestamp) {
857
+ if (!Array.isArray(record.activity)) record.activity = [];
858
+ record.activity.push({
859
+ id: uuidHex(),
860
+ type: eventType,
861
+ actor: cleanText(actor, "System", 120),
862
+ message: cleanText(message, "", 500),
863
+ created_at: timestamp || now()
864
+ });
865
+ }
866
+
867
+ /** app.py assignment_counts(). */
868
+ function assignmentCounts(record) {
869
+ var counts = { pending: 0, commented: 0, changes_requested: 0, approved: 0 };
870
+ (record.assignments || []).forEach(function (assignment) {
871
+ var status = assignment.status || "pending";
872
+ counts[status] = (hasOwn(counts, status) ? counts[status] : 0) + 1;
873
+ });
874
+ return counts;
875
+ }
876
+
877
+ /** app.py recalculate_document_status(). */
878
+ function recalculateDocumentStatus(record) {
879
+ var assignments = record.assignments || [];
880
+ if (!assignments.length) return;
881
+
882
+ var statuses = assignments.map(function (assignment) {
883
+ return assignment.status || "pending";
884
+ });
885
+ if (statuses.indexOf("changes_requested") !== -1) {
886
+ record.status = "changes_requested";
887
+ record.approved_at = null;
888
+ return;
889
+ }
890
+ var allApproved = statuses.every(function (status) { return status === "approved"; });
891
+ if (allApproved) {
892
+ record.status = "approved";
893
+ record.approved_at = record.approved_at || now();
894
+ return;
895
+ }
896
+ record.status = "in_review";
897
+ record.approved_at = null;
898
+ }
899
+
900
+ /** app.py public_assignment(). */
901
+ function publicAssignment(assignment) {
902
+ return {
903
+ id: assignment.id,
904
+ reviewer_id: assignment.reviewer_id,
905
+ reviewer_name: assignment.reviewer_name,
906
+ reviewer_contact: assignment.reviewer_contact || emptyContact(),
907
+ status: assignment.status,
908
+ status_label: hasOwn(ASSIGNMENT_LABELS, assignment.status)
909
+ ? ASSIGNMENT_LABELS[assignment.status]
910
+ : assignment.status,
911
+ assigned_at: assignment.assigned_at,
912
+ updated_at: assignment.updated_at,
913
+ approved_at: assignment.approved_at === undefined ? null : assignment.approved_at,
914
+ approval_name: assignment.approval_name || "",
915
+ approval_initials: assignment.approval_initials || "",
916
+ comments: assignment.comments || []
917
+ };
918
+ }
919
+
920
+ /** app.py public_document(). */
921
+ function publicDocument(record, includeText) {
922
+ var view = {
923
+ id: record.id,
924
+ filename: record.filename,
925
+ extension: record.extension,
926
+ status: record.status,
927
+ status_label: hasOwn(STATUS_LABELS, record.status)
928
+ ? STATUS_LABELS[record.status]
929
+ : record.status,
930
+ created_at: record.created_at,
931
+ updated_at: record.updated_at,
932
+ reviewed_at: record.reviewed_at === undefined ? null : record.reviewed_at,
933
+ approved_at: record.approved_at === undefined ? null : record.approved_at,
934
+ word_count: record.word_count === undefined ? 0 : record.word_count,
935
+ findings: record.findings || [],
936
+ comments: record.comments || [],
937
+ owner: isPlainObject(record.owner) ? record.owner : ownerFromPayload({}),
938
+ assignments: (record.assignments || []).map(publicAssignment),
939
+ assignment_counts: assignmentCounts(record),
940
+ activity: sortByDesc(record.activity || [], "created_at")
941
+ };
942
+ if (includeText) {
943
+ view.text = record.text || "";
944
+ }
945
+ return view;
946
+ }
947
+
948
+ /** app.py public_reviewer(). */
949
+ function publicReviewer(reviewer) {
950
+ return {
951
+ id: reviewer.id,
952
+ name: reviewer.name,
953
+ email: reviewer.email || "",
954
+ slack: reviewer.slack || "",
955
+ teams: reviewer.teams || "",
956
+ created_at: reviewer.created_at,
957
+ updated_at: reviewer.updated_at
958
+ };
959
+ }
960
+
961
+ /** app.py public_notification(). */
962
+ function publicNotification(notification) {
963
+ return {
964
+ id: notification.id,
965
+ recipient_type: notification.recipient_type,
966
+ recipient_name: notification.recipient_name,
967
+ recipient_contact: notification.recipient_contact || emptyContact(),
968
+ document_id: notification.document_id,
969
+ document_title: notification.document_title,
970
+ event: notification.event,
971
+ message: notification.message,
972
+ created_at: notification.created_at,
973
+ read_at: notification.read_at === undefined ? null : notification.read_at
974
+ };
975
+ }
976
+
977
+ function findDocument(data, documentId) {
978
+ return data.documents.filter(function (record) {
979
+ return record.id === documentId;
980
+ })[0] || null;
981
+ }
982
+
983
+ function findReviewer(data, reviewerId) {
984
+ return data.reviewers.filter(function (reviewer) {
985
+ return reviewer.id === reviewerId;
986
+ })[0] || null;
987
+ }
988
+
989
+ function findAssignment(record, reviewerId) {
990
+ return (record.assignments || []).filter(function (assignment) {
991
+ return assignment.reviewer_id === reviewerId;
992
+ })[0] || null;
993
+ }
994
+
995
+ /** app.py reviewer_payload(). */
996
+ function reviewerPayload(payload, existing) {
997
+ var reviewer = {};
998
+ if (existing) {
999
+ Object.keys(existing).forEach(function (key) {
1000
+ reviewer[key] = existing[key];
1001
+ });
1002
+ }
1003
+ reviewer.name = cleanText(payload.name, "", 120);
1004
+ if (!reviewer.name) throw apiError("Reviewer name is required.", 400);
1005
+ var contact = normalizeContact(payload);
1006
+ CONTACT_FIELDS.forEach(function (field) {
1007
+ reviewer[field] = contact[field];
1008
+ });
1009
+ return reviewer;
1010
+ }
1011
+
1012
+ /** app.py build_assignment(). */
1013
+ function buildAssignment(reviewer) {
1014
+ var timestamp = now();
1015
+ var assignment = {
1016
+ id: uuidHex(),
1017
+ reviewer_id: reviewer.id,
1018
+ reviewer_name: reviewer.name,
1019
+ reviewer_contact: normalizeContact(reviewer),
1020
+ status: "pending",
1021
+ status_label: "Pending",
1022
+ assigned_at: timestamp,
1023
+ updated_at: timestamp,
1024
+ approved_at: null,
1025
+ approval_name: "",
1026
+ approval_initials: "",
1027
+ comments: []
1028
+ };
1029
+ migrateAssignment(assignment);
1030
+ return assignment;
1031
+ }
1032
+
1033
+ /** app.py create_notification(). */
1034
+ function createNotification(data, record, recipientType, recipientName, recipientContact, event, message) {
1035
+ var notification = {
1036
+ id: uuidHex(),
1037
+ recipient_type: recipientType,
1038
+ recipient_name: cleanText(recipientName, "Recipient", 120),
1039
+ recipient_contact: normalizeContact(recipientContact),
1040
+ document_id: record.id,
1041
+ document_title: record.filename,
1042
+ event: event,
1043
+ message: cleanText(message, "", 1000),
1044
+ created_at: now(),
1045
+ read_at: null
1046
+ };
1047
+ if (!Array.isArray(data.notifications)) data.notifications = [];
1048
+ data.notifications.push(notification);
1049
+ addActivity(
1050
+ record,
1051
+ "notification",
1052
+ "System",
1053
+ "Queued notification for " + notification.recipient_name + ": " + notification.message,
1054
+ notification.created_at
1055
+ );
1056
+ return notification;
1057
+ }
1058
+
1059
+ // ------------------------------------------------------------- responses
1060
+
1061
+ function jsonResponse(payload, status) {
1062
+ return {
1063
+ status: status || 200,
1064
+ headers: { "Content-Type": "application/json; charset=utf-8" },
1065
+ body: JSON.stringify(payload)
1066
+ };
1067
+ }
1068
+
1069
+ function errorResponse(message, status) {
1070
+ return jsonResponse({ error: message }, status || 400);
1071
+ }
1072
+
1073
+ function notFound(message) {
1074
+ return errorResponse(message || "Not found.", 404);
1075
+ }
1076
+
1077
+ function parseJsonBody(body) {
1078
+ // app.py read_json_body(): an empty body is {}, malformed JSON is a 400.
1079
+ if (body === null || body === undefined || body === "") return {};
1080
+ if (isPlainObject(body)) return body;
1081
+ try {
1082
+ var parsed = JSON.parse(body);
1083
+ return isPlainObject(parsed) ? parsed : {};
1084
+ } catch (error) {
1085
+ throw apiError("Request body must be valid JSON.", 400);
1086
+ }
1087
+ }
1088
+
1089
+ // -------------------------------------------------------------- handlers
1090
+
1091
+ function handleDocumentsIndex() {
1092
+ return loadDb().then(function (data) {
1093
+ var documents = data.documents.map(function (record) {
1094
+ return publicDocument(record, false);
1095
+ });
1096
+ return jsonResponse({ documents: sortByDesc(documents, "updated_at") });
1097
+ });
1098
+ }
1099
+
1100
+ function handleReviewersIndex() {
1101
+ return loadDb().then(function (data) {
1102
+ var reviewers = data.reviewers.map(publicReviewer);
1103
+ return jsonResponse({
1104
+ reviewers: sortByAsc(reviewers, function (reviewer) {
1105
+ return String(reviewer.name).toLowerCase();
1106
+ })
1107
+ });
1108
+ });
1109
+ }
1110
+
1111
+ function handleNotificationsIndex() {
1112
+ return loadDb().then(function (data) {
1113
+ var notifications = sortByDesc(data.notifications.map(publicNotification), "created_at");
1114
+ var unread = notifications.filter(function (item) { return !item.read_at; }).length;
1115
+ return jsonResponse({ notifications: notifications, unread_count: unread });
1116
+ });
1117
+ }
1118
+
1119
+ function handleDocumentDetail(documentId) {
1120
+ return loadDb().then(function (data) {
1121
+ var record = findDocument(data, documentId);
1122
+ if (!record) return notFound("Document not found.");
1123
+ return jsonResponse(publicDocument(record, true));
1124
+ });
1125
+ }
1126
+
1127
+ function handleDownload(documentId) {
1128
+ return loadDb().then(function (data) {
1129
+ var record = findDocument(data, documentId);
1130
+ if (!record) return notFound("Document not found.");
1131
+ return Promise.resolve(store.getUpload(record.stored_name)).then(function (bytes) {
1132
+ if (!bytes) return notFound("Original upload is missing.");
1133
+ var extension = extensionOf(record.filename);
1134
+ return {
1135
+ status: 200,
1136
+ headers: {
1137
+ "Content-Type": DOWNLOAD_TYPES[extension] || "application/octet-stream",
1138
+ "Content-Disposition": 'attachment; filename="' + record.filename + '"'
1139
+ },
1140
+ bytes: bytes,
1141
+ filename: record.filename
1142
+ };
1143
+ });
1144
+ });
1145
+ }
1146
+
1147
+ /** app.py handle_upload(). */
1148
+ function handleUpload(upload) {
1149
+ if (!upload || !upload.bytes) throw apiError("Upload cannot be empty.", 400);
1150
+ // app.py measures Content-Length, so its 5 MB ceiling covers the whole
1151
+ // multipart request - the file plus a few hundred bytes of part headers.
1152
+ // There is no request here, so the file itself is what gets measured,
1153
+ // which makes this marginally more permissive for a file within a few
1154
+ // hundred bytes of the limit.
1155
+ if (upload.bytes.length > MAX_UPLOAD_BYTES) {
1156
+ throw apiError("Upload is too large. Maximum size is 5 MB.", 400);
1157
+ }
1158
+
1159
+ var fields = upload.fields || {};
1160
+ var filename = sanitizeFilename(upload.filename);
1161
+ var extension = extensionOf(filename);
1162
+ if (ALLOWED_EXTENSIONS.indexOf(extension) === -1) {
1163
+ return Promise.resolve(
1164
+ errorResponse("Unsupported file type. Upload TXT, MD, or DOCX.", 415)
1165
+ );
1166
+ }
1167
+ if (upload.bytes.length === 0) throw apiError("Uploaded file is empty.", 400);
1168
+
1169
+ return extractText(filename, upload.bytes, inflateRaw).then(function (text) {
1170
+ if (!text) throw apiError("No readable text was found in the document.", 400);
1171
+
1172
+ var documentId = uuidHex();
1173
+ var storedName = documentId + extension;
1174
+
1175
+ return Promise.resolve(store.putUpload(storedName, upload.bytes)).then(function () {
1176
+ var timestamp = now();
1177
+ var owner = ownerFromPayload({
1178
+ name: fields.owner_name || fields.owner,
1179
+ email: fields.owner_email,
1180
+ slack: fields.owner_slack,
1181
+ teams: fields.owner_teams
1182
+ });
1183
+ var record = {
1184
+ id: documentId,
1185
+ filename: filename,
1186
+ stored_name: storedName,
1187
+ extension: extension,
1188
+ status: "uploaded",
1189
+ created_at: timestamp,
1190
+ updated_at: timestamp,
1191
+ reviewed_at: null,
1192
+ approved_at: null,
1193
+ word_count: countWords(text),
1194
+ text: text,
1195
+ findings: [],
1196
+ comments: [],
1197
+ owner: owner,
1198
+ assignments: [],
1199
+ activity: []
1200
+ };
1201
+ addActivity(record, "uploaded", owner.name, "Uploaded " + filename + ".", timestamp);
1202
+
1203
+ return loadDb().then(function (data) {
1204
+ data.documents.push(record);
1205
+ return saveDb(data).then(function () {
1206
+ return jsonResponse(publicDocument(record, true), 201);
1207
+ });
1208
+ });
1209
+ });
1210
+ });
1211
+ }
1212
+
1213
+ /** app.py handle_review(). */
1214
+ function handleReview(documentId) {
1215
+ return loadDb().then(function (data) {
1216
+ var record = findDocument(data, documentId);
1217
+ if (!record) return notFound("Document not found.");
1218
+ var result = analyzeDocument(record.text || "", now);
1219
+ record.findings = result.findings;
1220
+ record.reviewed_at = result.reviewed_at;
1221
+ record.word_count = result.word_count;
1222
+ if (record.status !== "approved") record.status = "in_review";
1223
+ record.updated_at = now();
1224
+ addActivity(record, "review_run", "System", "Ran the local rubric review.", result.reviewed_at);
1225
+ return saveDb(data).then(function () {
1226
+ return jsonResponse(publicDocument(record, true));
1227
+ });
1228
+ });
1229
+ }
1230
+
1231
+ /** app.py handle_comment(). */
1232
+ function handleComment(documentId, body) {
1233
+ var payload = parseJsonBody(body);
1234
+ var text = cleanText(payload.body, "", 2000);
1235
+ var author = cleanText(payload.author, "Reviewer", 80);
1236
+ if (!text) throw apiError("Comment body is required.", 400);
1237
+
1238
+ return loadDb().then(function (data) {
1239
+ var record = findDocument(data, documentId);
1240
+ if (!record) return notFound("Document not found.");
1241
+
1242
+ var timestamp = now();
1243
+ if (!Array.isArray(record.comments)) record.comments = [];
1244
+ record.comments.push({
1245
+ id: uuidHex(),
1246
+ author: author,
1247
+ body: text,
1248
+ created_at: timestamp
1249
+ });
1250
+ record.updated_at = timestamp;
1251
+ addActivity(record, "comment_added", author, "Commented: " + text.slice(0, 120), timestamp);
1252
+ return saveDb(data).then(function () {
1253
+ return jsonResponse(publicDocument(record, true));
1254
+ });
1255
+ });
1256
+ }
1257
+
1258
+ /** app.py handle_status(). */
1259
+ function handleStatus(documentId, status) {
1260
+ return loadDb().then(function (data) {
1261
+ var record = findDocument(data, documentId);
1262
+ if (!record) return notFound("Document not found.");
1263
+
1264
+ var owner = isPlainObject(record.owner) ? record.owner : {};
1265
+ record.status = status;
1266
+ record.updated_at = now();
1267
+ if (status === "approved") {
1268
+ record.approved_at = now();
1269
+ addActivity(record, "approved", owner.name || "Owner", "Owner approved the document.");
1270
+ } else {
1271
+ record.approved_at = null;
1272
+ addActivity(record, "changes_requested", owner.name || "Owner", "Owner requested changes.");
1273
+ }
1274
+ return saveDb(data).then(function () {
1275
+ return jsonResponse(publicDocument(record, true));
1276
+ });
1277
+ });
1278
+ }
1279
+
1280
+ /** app.py handle_create_reviewer(). */
1281
+ function handleCreateReviewer(body) {
1282
+ var payload = parseJsonBody(body);
1283
+ var timestamp = now();
1284
+ var reviewer = reviewerPayload(payload, null);
1285
+ reviewer.id = uuidHex();
1286
+ reviewer.created_at = timestamp;
1287
+ reviewer.updated_at = timestamp;
1288
+ return loadDb().then(function (data) {
1289
+ data.reviewers.push(reviewer);
1290
+ return saveDb(data).then(function () {
1291
+ return jsonResponse(publicReviewer(reviewer), 201);
1292
+ });
1293
+ });
1294
+ }
1295
+
1296
+ /** app.py handle_update_reviewer(). */
1297
+ function handleUpdateReviewer(reviewerId, body) {
1298
+ return loadDb().then(function (data) {
1299
+ var reviewer = findReviewer(data, reviewerId);
1300
+ if (!reviewer) return notFound("Reviewer not found.");
1301
+ var updated = reviewerPayload(parseJsonBody(body), reviewer);
1302
+ Object.keys(updated).forEach(function (key) {
1303
+ reviewer[key] = updated[key];
1304
+ });
1305
+ reviewer.updated_at = now();
1306
+ return saveDb(data).then(function () {
1307
+ return jsonResponse(publicReviewer(reviewer));
1308
+ });
1309
+ });
1310
+ }
1311
+
1312
+ /** app.py handle_delete_reviewer(). */
1313
+ function handleDeleteReviewer(reviewerId) {
1314
+ return loadDb().then(function (data) {
1315
+ var before = data.reviewers.length;
1316
+ data.reviewers = data.reviewers.filter(function (reviewer) {
1317
+ return reviewer.id !== reviewerId;
1318
+ });
1319
+ if (data.reviewers.length === before) return notFound("Reviewer not found.");
1320
+ return saveDb(data).then(function () {
1321
+ return jsonResponse({ ok: true });
1322
+ });
1323
+ });
1324
+ }
1325
+
1326
+ /** app.py handle_assign_reviewers(). */
1327
+ function handleAssignReviewers(documentId, body) {
1328
+ var payload = parseJsonBody(body);
1329
+ var requested = payload.reviewer_ids === undefined ? [] : payload.reviewer_ids;
1330
+ if (!Array.isArray(requested)) throw apiError("reviewer_ids must be a list.", 400);
1331
+
1332
+ var reviewerIds = [];
1333
+ requested.forEach(function (item) {
1334
+ var id = pyStr(item);
1335
+ if (!id.trim()) return;
1336
+ if (reviewerIds.indexOf(id) === -1) reviewerIds.push(id);
1337
+ });
1338
+
1339
+ return loadDb().then(function (data) {
1340
+ var record = findDocument(data, documentId);
1341
+ if (!record) return notFound("Document not found.");
1342
+
1343
+ var reviewersById = {};
1344
+ data.reviewers.forEach(function (reviewer) {
1345
+ reviewersById[reviewer.id] = reviewer;
1346
+ });
1347
+ var missing = reviewerIds.filter(function (id) {
1348
+ return !hasOwn(reviewersById, id);
1349
+ });
1350
+ if (missing.length) {
1351
+ throw apiError("One or more selected reviewers no longer exists.", 400);
1352
+ }
1353
+
1354
+ var existingById = {};
1355
+ (record.assignments || []).forEach(function (assignment) {
1356
+ existingById[assignment.reviewer_id] = assignment;
1357
+ });
1358
+
1359
+ var assignments = [];
1360
+ var created = [];
1361
+ reviewerIds.forEach(function (id) {
1362
+ if (hasOwn(existingById, id)) {
1363
+ assignments.push(existingById[id]);
1364
+ } else {
1365
+ var assignment = buildAssignment(reviewersById[id]);
1366
+ assignments.push(assignment);
1367
+ created.push(assignment);
1368
+ }
1369
+ });
1370
+ record.assignments = assignments;
1371
+
1372
+ var timestamp = now();
1373
+ record.updated_at = timestamp;
1374
+ if (reviewerIds.length) {
1375
+ record.status = "in_review";
1376
+ var names = assignments.map(function (assignment) {
1377
+ return assignment.reviewer_name;
1378
+ }).join(", ");
1379
+ addActivity(record, "reviewers_assigned", record.owner.name, "Assigned reviewers: " + names + ".", timestamp);
1380
+ } else {
1381
+ record.status = record.reviewed_at ? "in_review" : "uploaded";
1382
+ record.approved_at = null;
1383
+ addActivity(record, "reviewers_assigned", record.owner.name, "Cleared reviewer assignments.", timestamp);
1384
+ }
1385
+
1386
+ created.forEach(function (assignment) {
1387
+ var message =
1388
+ "Please review " + record.filename + " in SimpleDocReview. " +
1389
+ "Open the local app, select the document, and respond as " + assignment.reviewer_name + ".";
1390
+ createNotification(
1391
+ data,
1392
+ record,
1393
+ "reviewer",
1394
+ assignment.reviewer_name,
1395
+ assignment.reviewer_contact,
1396
+ "review_assigned",
1397
+ message
1398
+ );
1399
+ });
1400
+
1401
+ recalculateDocumentStatus(record);
1402
+ return saveDb(data).then(function () {
1403
+ return jsonResponse(publicDocument(record, true));
1404
+ });
1405
+ });
1406
+ }
1407
+
1408
+ /**
1409
+ * app.py require_assignment().
1410
+ *
1411
+ * Note the status quirk this preserves: a missing document reaches the
1412
+ * client as a 400 here, not the 404 that GET /api/documents/<id> returns,
1413
+ * because upstream raises ValueError rather than replying directly.
1414
+ */
1415
+ function requireAssignment(documentId, payload) {
1416
+ var reviewerId = cleanText(payload.reviewer_id, "", 80);
1417
+ if (!reviewerId) throw apiError("Reviewer is required.", 400);
1418
+ return loadDb().then(function (data) {
1419
+ var record = findDocument(data, documentId);
1420
+ if (!record) throw apiError("Document not found.", 400);
1421
+ var assignment = findAssignment(record, reviewerId);
1422
+ if (!assignment) throw apiError("Reviewer is not assigned to this document.", 400);
1423
+ return { data: data, record: record, assignment: assignment };
1424
+ });
1425
+ }
1426
+
1427
+ /** app.py handle_reviewer_comment(). */
1428
+ function handleReviewerComment(documentId, body) {
1429
+ var payload = parseJsonBody(body);
1430
+ return requireAssignment(documentId, payload).then(function (context) {
1431
+ var data = context.data;
1432
+ var record = context.record;
1433
+ var assignment = context.assignment;
1434
+ var text = cleanText(payload.body, "", 2000);
1435
+ var signature = cleanText(payload.signature, assignment.reviewer_name, 120);
1436
+ if (!text) throw apiError("Comment body is required.", 400);
1437
+
1438
+ var timestamp = now();
1439
+ var comment = {
1440
+ id: uuidHex(),
1441
+ author: signature,
1442
+ reviewer_id: assignment.reviewer_id,
1443
+ body: text,
1444
+ created_at: timestamp
1445
+ };
1446
+ if (!Array.isArray(assignment.comments)) assignment.comments = [];
1447
+ assignment.comments.push(comment);
1448
+ if (assignment.status !== "approved" && assignment.status !== "changes_requested") {
1449
+ assignment.status = "commented";
1450
+ }
1451
+ assignment.updated_at = timestamp;
1452
+ migrateAssignment(assignment);
1453
+ if (!Array.isArray(record.comments)) record.comments = [];
1454
+ record.comments.push(comment);
1455
+ record.updated_at = timestamp;
1456
+ addActivity(record, "reviewer_comment", signature, "Commented: " + text.slice(0, 120), timestamp);
1457
+ createNotification(
1458
+ data,
1459
+ record,
1460
+ "owner",
1461
+ record.owner.name,
1462
+ record.owner,
1463
+ "reviewer_comment",
1464
+ signature + " commented on " + record.filename + ": " + text.slice(0, 180)
1465
+ );
1466
+ recalculateDocumentStatus(record);
1467
+ return saveDb(data).then(function () {
1468
+ return jsonResponse(publicDocument(record, true));
1469
+ });
1470
+ });
1471
+ }
1472
+
1473
+ /** app.py handle_reviewer_approve(). */
1474
+ function handleReviewerApprove(documentId, body) {
1475
+ var payload = parseJsonBody(body);
1476
+ return requireAssignment(documentId, payload).then(function (context) {
1477
+ var data = context.data;
1478
+ var record = context.record;
1479
+ var assignment = context.assignment;
1480
+ var signature = cleanText(payload.signature, "", 120);
1481
+ if (!signature) throw apiError("Approval name or initials are required.", 400);
1482
+
1483
+ var wasFinal = record.status === "approved";
1484
+ var timestamp = now();
1485
+ assignment.status = "approved";
1486
+ assignment.approval_name = signature;
1487
+ assignment.approval_initials = cleanText(payload.initials || signature, "", 24);
1488
+ assignment.approved_at = timestamp;
1489
+ assignment.updated_at = timestamp;
1490
+ migrateAssignment(assignment);
1491
+ record.updated_at = timestamp;
1492
+ addActivity(record, "reviewer_approved", signature, "Approved as " + signature + ".", timestamp);
1493
+ recalculateDocumentStatus(record);
1494
+ if (record.status === "approved" && !wasFinal) {
1495
+ addActivity(
1496
+ record,
1497
+ "approved",
1498
+ "System",
1499
+ "All assigned reviewers approved the document.",
1500
+ record.approved_at
1501
+ );
1502
+ }
1503
+ createNotification(
1504
+ data,
1505
+ record,
1506
+ "owner",
1507
+ record.owner.name,
1508
+ record.owner,
1509
+ "reviewer_approved",
1510
+ signature + " approved " + record.filename + "."
1511
+ );
1512
+ return saveDb(data).then(function () {
1513
+ return jsonResponse(publicDocument(record, true));
1514
+ });
1515
+ });
1516
+ }
1517
+
1518
+ /** app.py handle_reviewer_request_changes(). */
1519
+ function handleReviewerRequestChanges(documentId, body) {
1520
+ var payload = parseJsonBody(body);
1521
+ return requireAssignment(documentId, payload).then(function (context) {
1522
+ var data = context.data;
1523
+ var record = context.record;
1524
+ var assignment = context.assignment;
1525
+ var text = cleanText(payload.body, "", 2000);
1526
+ var signature = cleanText(payload.signature, assignment.reviewer_name, 120);
1527
+ if (!text) throw apiError("A change request note is required.", 400);
1528
+
1529
+ var timestamp = now();
1530
+ assignment.status = "changes_requested";
1531
+ assignment.approved_at = null;
1532
+ assignment.approval_name = "";
1533
+ assignment.approval_initials = "";
1534
+ assignment.updated_at = timestamp;
1535
+ var comment = {
1536
+ id: uuidHex(),
1537
+ author: signature,
1538
+ reviewer_id: assignment.reviewer_id,
1539
+ body: text,
1540
+ created_at: timestamp
1541
+ };
1542
+ if (!Array.isArray(assignment.comments)) assignment.comments = [];
1543
+ assignment.comments.push(comment);
1544
+ migrateAssignment(assignment);
1545
+ if (!Array.isArray(record.comments)) record.comments = [];
1546
+ record.comments.push(comment);
1547
+ record.updated_at = timestamp;
1548
+ recalculateDocumentStatus(record);
1549
+ addActivity(
1550
+ record,
1551
+ "reviewer_changes_requested",
1552
+ signature,
1553
+ "Requested changes: " + text.slice(0, 120),
1554
+ timestamp
1555
+ );
1556
+ createNotification(
1557
+ data,
1558
+ record,
1559
+ "owner",
1560
+ record.owner.name,
1561
+ record.owner,
1562
+ "reviewer_changes_requested",
1563
+ signature + " requested changes on " + record.filename + ": " + text.slice(0, 180)
1564
+ );
1565
+ return saveDb(data).then(function () {
1566
+ return jsonResponse(publicDocument(record, true));
1567
+ });
1568
+ });
1569
+ }
1570
+
1571
+ /** app.py handle_notification_read(). */
1572
+ function handleNotificationRead(notificationId) {
1573
+ return loadDb().then(function (data) {
1574
+ var notification = data.notifications.filter(function (item) {
1575
+ return item.id === notificationId;
1576
+ })[0];
1577
+ if (!notification) return notFound("Notification not found.");
1578
+ notification.read_at = notification.read_at || now();
1579
+ return saveDb(data).then(function () {
1580
+ return jsonResponse(publicNotification(notification));
1581
+ });
1582
+ });
1583
+ }
1584
+
1585
+ // ----------------------------------------------------------------- router
1586
+ // Mirrors app.py's do_GET / do_POST / do_PUT / do_DELETE dispatch, in the
1587
+ // same order, so an unmatched path produces the same 404 body.
1588
+
1589
+ function pathParts(pathname) {
1590
+ return String(pathname)
1591
+ .split("?")[0]
1592
+ .split("#")[0]
1593
+ .split("/")
1594
+ .filter(function (part) { return part.length > 0; })
1595
+ .map(function (part) { return decodeURIComponent(part); });
1596
+ }
1597
+
1598
+ function route(method, pathname, body) {
1599
+ var parts = pathParts(pathname);
1600
+ var verb = String(method || "GET").toUpperCase();
1601
+
1602
+ if (verb === "GET") {
1603
+ if (parts.length === 2 && parts[0] === "api") {
1604
+ if (parts[1] === "documents") return handleDocumentsIndex();
1605
+ if (parts[1] === "reviewers") return handleReviewersIndex();
1606
+ if (parts[1] === "notifications") return handleNotificationsIndex();
1607
+ }
1608
+ if (parts.length === 3 && parts[0] === "api" && parts[1] === "documents") {
1609
+ return handleDocumentDetail(parts[2]);
1610
+ }
1611
+ if (parts.length === 4 && parts[0] === "api" && parts[1] === "documents" && parts[3] === "download") {
1612
+ return handleDownload(parts[2]);
1613
+ }
1614
+ return Promise.resolve(notFound());
1615
+ }
1616
+
1617
+ if (verb === "POST") {
1618
+ if (parts.length === 2 && parts[0] === "api" && parts[1] === "upload") {
1619
+ return handleUpload(body);
1620
+ }
1621
+ if (parts.length === 2 && parts[0] === "api" && parts[1] === "reviewers") {
1622
+ return handleCreateReviewer(body);
1623
+ }
1624
+ if (parts.length === 4 && parts[0] === "api" && parts[1] === "notifications" && parts[3] === "read") {
1625
+ return handleNotificationRead(parts[2]);
1626
+ }
1627
+ if (parts.length === 4 && parts[0] === "api" && parts[1] === "documents") {
1628
+ var documentId = parts[2];
1629
+ var action = parts[3];
1630
+ if (action === "review") return handleReview(documentId);
1631
+ if (action === "comments") return handleComment(documentId, body);
1632
+ if (action === "approve") return handleStatus(documentId, "approved");
1633
+ if (action === "request-changes") return handleStatus(documentId, "changes_requested");
1634
+ if (action === "assign-reviewers") return handleAssignReviewers(documentId, body);
1635
+ if (action === "reviewer-comment") return handleReviewerComment(documentId, body);
1636
+ if (action === "reviewer-approve") return handleReviewerApprove(documentId, body);
1637
+ if (action === "reviewer-request-changes") return handleReviewerRequestChanges(documentId, body);
1638
+ }
1639
+ return Promise.resolve(notFound());
1640
+ }
1641
+
1642
+ if (verb === "PUT") {
1643
+ if (parts.length === 3 && parts[0] === "api" && parts[1] === "reviewers") {
1644
+ return handleUpdateReviewer(parts[2], body);
1645
+ }
1646
+ return Promise.resolve(notFound());
1647
+ }
1648
+
1649
+ if (verb === "DELETE") {
1650
+ if (parts.length === 3 && parts[0] === "api" && parts[1] === "reviewers") {
1651
+ return handleDeleteReviewer(parts[2]);
1652
+ }
1653
+ return Promise.resolve(notFound());
1654
+ }
1655
+
1656
+ return Promise.resolve(notFound());
1657
+ }
1658
+
1659
+ // One request at a time. app.py serializes on the file it rewrites; here
1660
+ // every handler is a read-modify-write against the same store, and the app
1661
+ // fires three GETs in parallel on load, so interleaving them would let one
1662
+ // response overwrite another's changes.
1663
+ var queue = Promise.resolve();
1664
+
1665
+ function handle(method, pathname, body) {
1666
+ var result = queue.then(function () {
1667
+ return Promise.resolve()
1668
+ .then(function () {
1669
+ return route(method, pathname, body);
1670
+ })
1671
+ .catch(function (error) {
1672
+ if (error && error.apiStatus) {
1673
+ return errorResponse(error.message, error.apiStatus);
1674
+ }
1675
+ throw error;
1676
+ });
1677
+ });
1678
+ // Keep the chain alive even when a request rejects, and never let a
1679
+ // rejection here surface as an unhandled promise.
1680
+ queue = result.then(function () { return undefined; }, function () { return undefined; });
1681
+ return result;
1682
+ }
1683
+
1684
+ return {
1685
+ handle: handle,
1686
+ isApiPath: function (pathname) {
1687
+ var parts = pathParts(pathname);
1688
+ return parts[0] === "api";
1689
+ },
1690
+ // Exposed for the parity tests and for debugging in the browser console.
1691
+ internals: {
1692
+ analyzeDocument: function (text) { return analyzeDocument(text, now); },
1693
+ extractText: function (filename, bytes) { return extractText(filename, bytes, inflateRaw); },
1694
+ sanitizeFilename: sanitizeFilename,
1695
+ decodeTextBytes: decodeTextBytes,
1696
+ cleanText: cleanText,
1697
+ countWords: countWords,
1698
+ publicDocument: publicDocument,
1699
+ loadDb: loadDb
1700
+ }
1701
+ };
1702
+ }
1703
+
1704
+ return {
1705
+ createApi: createApi,
1706
+ MAX_UPLOAD_BYTES: MAX_UPLOAD_BYTES,
1707
+ ALLOWED_EXTENSIONS: ALLOWED_EXTENSIONS,
1708
+ STATUS_LABELS: STATUS_LABELS,
1709
+ ASSIGNMENT_LABELS: ASSIGNMENT_LABELS,
1710
+ defaultNow: defaultNow,
1711
+ defaultUuidHex: defaultUuidHex,
1712
+ defaultInflateRaw: defaultInflateRaw,
1713
+ sanitizeFilename: sanitizeFilename,
1714
+ decodeTextBytes: decodeTextBytes,
1715
+ cleanText: cleanText
1716
+ };
1717
+ });
overlay/sdr-api-shim.js ADDED
@@ -0,0 +1,689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * sdr-api-shim.js - wires sdr-api-core.js into the page in place of app.py.
3
+ *
4
+ * A Static Space serves files and nothing else, so the `http://127.0.0.1:4173`
5
+ * server upstream's `static/app.js` talks to does not exist. This file answers
6
+ * those requests in the browser:
7
+ *
8
+ * 1. an IndexedDB store standing in for data/reviews.json and uploads/,
9
+ * 2. an XMLHttpRequest (and fetch) interceptor for every /api/ path,
10
+ * 3. a click interceptor for the Download button, which upstream implements
11
+ * as a navigation rather than a request,
12
+ * 4. a one-line notice, because on a public URL "your documents stay in this
13
+ * browser" is not what a visitor would assume.
14
+ *
15
+ * Nothing here reimplements review logic - that all lives in sdr-api-core.js.
16
+ * This file is only the environment.
17
+ *
18
+ * Loaded by a <script> tag that scripts/build-static.ps1 inserts ahead of
19
+ * upstream's static/app.js. Upstream's files are never edited.
20
+ */
21
+ (function () {
22
+ "use strict";
23
+
24
+ if (typeof window === "undefined" || window.__sdrApiShimInstalled) return;
25
+ window.__sdrApiShimInstalled = true;
26
+
27
+ var Core = window.SdrApiCore;
28
+ if (!Core) {
29
+ console.error("[SimpleDocReview] sdr-api-core.js did not load; the app cannot run.");
30
+ return;
31
+ }
32
+
33
+ var DB_NAME = "simpledocreview";
34
+ var DB_VERSION = 1;
35
+ var RECORD_STORE = "records";
36
+ var UPLOAD_STORE = "uploads";
37
+ var RECORD_KEY = "db";
38
+
39
+ // ------------------------------------------------------------------- store
40
+
41
+ function openDatabase() {
42
+ return new Promise(function (resolve, reject) {
43
+ if (!window.indexedDB) {
44
+ reject(new Error("IndexedDB is unavailable."));
45
+ return;
46
+ }
47
+ var request = window.indexedDB.open(DB_NAME, DB_VERSION);
48
+ request.onupgradeneeded = function () {
49
+ var database = request.result;
50
+ if (!database.objectStoreNames.contains(RECORD_STORE)) {
51
+ database.createObjectStore(RECORD_STORE);
52
+ }
53
+ if (!database.objectStoreNames.contains(UPLOAD_STORE)) {
54
+ database.createObjectStore(UPLOAD_STORE);
55
+ }
56
+ };
57
+ request.onsuccess = function () { resolve(request.result); };
58
+ request.onerror = function () { reject(request.error || new Error("IndexedDB open failed.")); };
59
+ request.onblocked = function () { reject(new Error("IndexedDB is blocked by another tab.")); };
60
+ });
61
+ }
62
+
63
+ function transact(storeName, mode, work) {
64
+ return openDatabase().then(function (database) {
65
+ return new Promise(function (resolve, reject) {
66
+ var transaction = database.transaction(storeName, mode);
67
+ var request = work(transaction.objectStore(storeName));
68
+ transaction.oncomplete = function () {
69
+ database.close();
70
+ resolve(request ? request.result : undefined);
71
+ };
72
+ transaction.onerror = function () {
73
+ database.close();
74
+ reject(transaction.error || new Error("IndexedDB transaction failed."));
75
+ };
76
+ transaction.onabort = function () {
77
+ database.close();
78
+ reject(transaction.error || new Error("IndexedDB transaction aborted."));
79
+ };
80
+ });
81
+ });
82
+ }
83
+
84
+ var indexedDbStore = {
85
+ load: function () {
86
+ return transact(RECORD_STORE, "readonly", function (store) {
87
+ return store.get(RECORD_KEY);
88
+ }).then(function (value) {
89
+ return value || null;
90
+ });
91
+ },
92
+ save: function (data) {
93
+ return transact(RECORD_STORE, "readwrite", function (store) {
94
+ return store.put(data, RECORD_KEY);
95
+ });
96
+ },
97
+ putUpload: function (name, bytes) {
98
+ return transact(UPLOAD_STORE, "readwrite", function (store) {
99
+ return store.put(bytes, name);
100
+ });
101
+ },
102
+ getUpload: function (name) {
103
+ if (!name) return Promise.resolve(null);
104
+ return transact(UPLOAD_STORE, "readonly", function (store) {
105
+ return store.get(name);
106
+ }).then(function (value) {
107
+ if (!value) return null;
108
+ return value instanceof Uint8Array ? value : new Uint8Array(value);
109
+ });
110
+ },
111
+ clear: function () {
112
+ return transact(RECORD_STORE, "readwrite", function (store) {
113
+ return store.clear();
114
+ }).then(function () {
115
+ return transact(UPLOAD_STORE, "readwrite", function (store) {
116
+ return store.clear();
117
+ });
118
+ });
119
+ }
120
+ };
121
+
122
+ /**
123
+ * Fallback for browsers that refuse storage.
124
+ *
125
+ * The Space renders inside an iframe on huggingface.co, and some browsers
126
+ * partition or block storage for embedded third-party origins. Losing
127
+ * persistence is better than a dead page, so the app still works for the
128
+ * length of the visit and the notice says so.
129
+ */
130
+ function createMemoryStore() {
131
+ var records = null;
132
+ var uploads = {};
133
+ return {
134
+ volatile: true,
135
+ load: function () { return Promise.resolve(records); },
136
+ save: function (data) { records = data; return Promise.resolve(); },
137
+ putUpload: function (name, bytes) { uploads[name] = bytes; return Promise.resolve(); },
138
+ getUpload: function (name) { return Promise.resolve(uploads[name] || null); },
139
+ clear: function () { records = null; uploads = {}; return Promise.resolve(); }
140
+ };
141
+ }
142
+
143
+ /**
144
+ * Probe storage once, then keep using whichever backend answered.
145
+ *
146
+ * The probe result is cached rather than retried per request, so a page that
147
+ * starts in memory stays consistent instead of writing half its records to
148
+ * one backend and half to the other.
149
+ */
150
+ var activeStore = null;
151
+ var storeProbe = null;
152
+
153
+ function resolveStore() {
154
+ if (activeStore) return Promise.resolve(activeStore);
155
+ if (!storeProbe) {
156
+ storeProbe = indexedDbStore
157
+ .load()
158
+ .then(function () {
159
+ activeStore = indexedDbStore;
160
+ return activeStore;
161
+ })
162
+ .catch(function (error) {
163
+ console.warn(
164
+ "[SimpleDocReview] IndexedDB unavailable (" + error.message + "); " +
165
+ "documents will be kept in memory for this visit only."
166
+ );
167
+ activeStore = createMemoryStore();
168
+ return activeStore;
169
+ });
170
+ }
171
+ return storeProbe;
172
+ }
173
+
174
+ var store = {
175
+ load: function () { return resolveStore().then(function (s) { return s.load(); }); },
176
+ save: function (data) { return resolveStore().then(function (s) { return s.save(data); }); },
177
+ putUpload: function (n, b) { return resolveStore().then(function (s) { return s.putUpload(n, b); }); },
178
+ getUpload: function (n) { return resolveStore().then(function (s) { return s.getUpload(n); }); },
179
+ clear: function () { return resolveStore().then(function (s) { return s.clear(); }); }
180
+ };
181
+
182
+ var api = Core.createApi({ store: store });
183
+
184
+ // ------------------------------------------------------------ request body
185
+
186
+ function apiError(message, status) {
187
+ var error = new Error(message);
188
+ error.apiStatus = status || 400;
189
+ return error;
190
+ }
191
+
192
+ /**
193
+ * Turn an XHR/fetch body into what the core API expects.
194
+ *
195
+ * Upload is the only interesting case: upstream posts multipart/form-data,
196
+ * which app.py parses back apart. Here the FormData object is already
197
+ * structured, so the parse step is just reading the parts out - the file as
198
+ * bytes, everything else as a text field.
199
+ */
200
+ function normalizeBody(body) {
201
+ if (body === null || body === undefined) return Promise.resolve(null);
202
+ if (typeof body === "string") return Promise.resolve(body);
203
+
204
+ if (typeof FormData !== "undefined" && body instanceof FormData) {
205
+ var file = body.get("file");
206
+ if (!file || typeof file === "string") {
207
+ return Promise.reject(apiError("No file part was found in the upload.", 400));
208
+ }
209
+ var fields = {};
210
+ body.forEach(function (value, key) {
211
+ if (typeof value === "string") fields[key] = value.trim();
212
+ });
213
+ return file.arrayBuffer().then(function (buffer) {
214
+ return {
215
+ filename: file.name,
216
+ bytes: new Uint8Array(buffer),
217
+ fields: fields
218
+ };
219
+ });
220
+ }
221
+
222
+ if (typeof Blob !== "undefined" && body instanceof Blob) return body.text();
223
+ if (body instanceof ArrayBuffer) return Promise.resolve(new TextDecoder().decode(body));
224
+ if (body && body.buffer instanceof ArrayBuffer) {
225
+ return Promise.resolve(new TextDecoder().decode(body));
226
+ }
227
+ return Promise.resolve(String(body));
228
+ }
229
+
230
+ function toPathname(url) {
231
+ try {
232
+ return new URL(String(url), window.location.href).pathname;
233
+ } catch (error) {
234
+ return String(url);
235
+ }
236
+ }
237
+
238
+ function isApiUrl(url) {
239
+ return api.isApiPath(toPathname(url));
240
+ }
241
+
242
+ // ----------------------------------------------------- selected document id
243
+
244
+ /**
245
+ * The id of the document currently on screen.
246
+ *
247
+ * Upstream's Download button navigates to /api/documents/<id>/download rather
248
+ * than requesting it, and a page cannot cancel an assignment to
249
+ * window.location.href. The click is intercepted instead (see below), which
250
+ * means the id has to come from somewhere other than the event.
251
+ *
252
+ * Every render of the document panel is driven by a response for that
253
+ * document - selectDocument() and refreshSelected() both fetch it by id, and
254
+ * the reviewer actions post to it - so the last /api/documents/<id> path to
255
+ * pass through here names what the panel is showing.
256
+ */
257
+ var lastDocumentId = null;
258
+
259
+ function rememberDocumentId(pathname) {
260
+ var match = /^\/api\/documents\/([^/]+)/.exec(pathname);
261
+ if (match && match[1] !== "download") lastDocumentId = decodeURIComponent(match[1]);
262
+ }
263
+
264
+ function dispatchToCore(method, url, body) {
265
+ var pathname = toPathname(url);
266
+ rememberDocumentId(pathname);
267
+ return normalizeBody(body).then(function (payload) {
268
+ return api.handle(method, pathname, payload);
269
+ });
270
+ }
271
+
272
+ // ------------------------------------------------- XMLHttpRequest override
273
+
274
+ var RealXMLHttpRequest = window.XMLHttpRequest;
275
+
276
+ var SIMULATED_PROPERTIES = {
277
+ readyState: true,
278
+ status: true,
279
+ statusText: true,
280
+ response: true,
281
+ responseText: true,
282
+ responseURL: true
283
+ };
284
+
285
+ var HANDLER_PROPERTIES = {
286
+ onreadystatechange: true,
287
+ onload: true,
288
+ onloadstart: true,
289
+ onloadend: true,
290
+ onerror: true,
291
+ onabort: true,
292
+ ontimeout: true,
293
+ onprogress: true
294
+ };
295
+
296
+ /**
297
+ * An XMLHttpRequest that answers /api/ locally and forwards everything else.
298
+ *
299
+ * A Proxy over a real XMLHttpRequest rather than a hand-written stand-in: any
300
+ * member this shim does not simulate still reaches the genuine object, so a
301
+ * future upstream change that uses more of the XHR surface keeps working
302
+ * instead of hitting a gap in a fake.
303
+ */
304
+ function createInterceptingXhr() {
305
+ var real = new RealXMLHttpRequest();
306
+ var state = {
307
+ intercepted: false,
308
+ method: "GET",
309
+ url: "",
310
+ overrides: {},
311
+ handlers: {},
312
+ listeners: {},
313
+ sent: false
314
+ };
315
+ var proxy;
316
+
317
+ function dispatch(type) {
318
+ var event = {
319
+ type: type,
320
+ target: proxy,
321
+ currentTarget: proxy,
322
+ lengthComputable: false,
323
+ loaded: 0,
324
+ total: 0
325
+ };
326
+ var handler = state.handlers["on" + type];
327
+ if (typeof handler === "function") handler.call(proxy, event);
328
+ (state.listeners[type] || []).forEach(function (listener) {
329
+ if (typeof listener === "function") listener.call(proxy, event);
330
+ else if (listener && typeof listener.handleEvent === "function") listener.handleEvent(event);
331
+ });
332
+ }
333
+
334
+ function settle(response) {
335
+ state.overrides.readyState = 4;
336
+ state.overrides.status = response.status;
337
+ state.overrides.statusText = response.status === 200 ? "OK" : "";
338
+ state.overrides.responseURL = new URL(state.url, window.location.href).href;
339
+ // A download reply carries bytes, not text. Upstream never reads one
340
+ // through XHR (it navigates instead), so the body is left empty rather
341
+ // than lossily decoded.
342
+ state.overrides.responseText = response.body || "";
343
+ state.overrides.response = response.body || "";
344
+ state.overrides.__headers = response.headers || {};
345
+ state.overrides.__bytes = response.bytes || null;
346
+ dispatch("readystatechange");
347
+ dispatch("load");
348
+ dispatch("loadend");
349
+ }
350
+
351
+ function failed(error) {
352
+ if (error && error.apiStatus) {
353
+ settle({
354
+ status: error.apiStatus,
355
+ headers: { "Content-Type": "application/json; charset=utf-8" },
356
+ body: JSON.stringify({ error: error.message })
357
+ });
358
+ return;
359
+ }
360
+ console.error("[SimpleDocReview] local API failed:", error);
361
+ state.overrides.readyState = 4;
362
+ state.overrides.status = 0;
363
+ state.overrides.responseText = "";
364
+ state.overrides.response = "";
365
+ dispatch("readystatechange");
366
+ dispatch("error");
367
+ dispatch("loadend");
368
+ }
369
+
370
+ var members = {
371
+ open: function (method, url) {
372
+ state.method = String(method || "GET");
373
+ state.url = String(url);
374
+ state.intercepted = isApiUrl(state.url);
375
+ state.overrides = {};
376
+ state.sent = false;
377
+ if (state.intercepted) {
378
+ state.overrides.readyState = 1;
379
+ dispatch("readystatechange");
380
+ return undefined;
381
+ }
382
+ return real.open.apply(real, arguments);
383
+ },
384
+
385
+ send: function (body) {
386
+ if (!state.intercepted) return real.send.apply(real, arguments);
387
+ if (state.sent) throw new Error("InvalidStateError: send() already called.");
388
+ state.sent = true;
389
+ dispatch("loadstart");
390
+ dispatchToCore(state.method, state.url, body).then(settle, failed);
391
+ return undefined;
392
+ },
393
+
394
+ setRequestHeader: function () {
395
+ if (state.intercepted) return undefined;
396
+ return real.setRequestHeader.apply(real, arguments);
397
+ },
398
+
399
+ getResponseHeader: function (name) {
400
+ if (!state.intercepted) return real.getResponseHeader.apply(real, arguments);
401
+ var headers = state.overrides.__headers || {};
402
+ var wanted = String(name).toLowerCase();
403
+ var found = Object.keys(headers).filter(function (key) {
404
+ return key.toLowerCase() === wanted;
405
+ })[0];
406
+ return found ? headers[found] : null;
407
+ },
408
+
409
+ getAllResponseHeaders: function () {
410
+ if (!state.intercepted) return real.getAllResponseHeaders.apply(real, arguments);
411
+ var headers = state.overrides.__headers || {};
412
+ return Object.keys(headers)
413
+ .map(function (key) { return key.toLowerCase() + ": " + headers[key] + "\r\n"; })
414
+ .join("");
415
+ },
416
+
417
+ abort: function () {
418
+ if (!state.intercepted) return real.abort.apply(real, arguments);
419
+ // The work is already running locally and has nothing to cancel; report
420
+ // the aborted state so callers waiting on it are not left hanging.
421
+ state.overrides.readyState = 4;
422
+ state.overrides.status = 0;
423
+ dispatch("readystatechange");
424
+ dispatch("abort");
425
+ dispatch("loadend");
426
+ return undefined;
427
+ },
428
+
429
+ addEventListener: function (type, listener) {
430
+ if (!state.listeners[type]) state.listeners[type] = [];
431
+ state.listeners[type].push(listener);
432
+ return real.addEventListener.apply(real, arguments);
433
+ },
434
+
435
+ removeEventListener: function (type, listener) {
436
+ state.listeners[type] = (state.listeners[type] || []).filter(function (item) {
437
+ return item !== listener;
438
+ });
439
+ return real.removeEventListener.apply(real, arguments);
440
+ }
441
+ };
442
+
443
+ proxy = new Proxy(real, {
444
+ get: function (target, property) {
445
+ if (Object.prototype.hasOwnProperty.call(members, property)) return members[property];
446
+ if (Object.prototype.hasOwnProperty.call(HANDLER_PROPERTIES, property)) {
447
+ return state.handlers[property] === undefined ? null : state.handlers[property];
448
+ }
449
+ if (state.intercepted && Object.prototype.hasOwnProperty.call(SIMULATED_PROPERTIES, property)) {
450
+ var override = state.overrides[property];
451
+ if (override !== undefined) return override;
452
+ if (property === "readyState" || property === "status") return 0;
453
+ return "";
454
+ }
455
+ var value = target[property];
456
+ return typeof value === "function" ? value.bind(target) : value;
457
+ },
458
+ set: function (target, property, value) {
459
+ if (Object.prototype.hasOwnProperty.call(HANDLER_PROPERTIES, property)) {
460
+ state.handlers[property] = value;
461
+ return true;
462
+ }
463
+ target[property] = value;
464
+ return true;
465
+ }
466
+ });
467
+
468
+ return proxy;
469
+ }
470
+
471
+ function ShimXMLHttpRequest() {
472
+ return createInterceptingXhr();
473
+ }
474
+ ShimXMLHttpRequest.prototype = RealXMLHttpRequest.prototype;
475
+ ["UNSENT", "OPENED", "HEADERS_RECEIVED", "LOADING", "DONE"].forEach(function (name) {
476
+ ShimXMLHttpRequest[name] = RealXMLHttpRequest[name];
477
+ });
478
+ window.XMLHttpRequest = ShimXMLHttpRequest;
479
+
480
+ // ------------------------------------------------------------ fetch override
481
+
482
+ // Upstream uses XHR throughout. This covers /api/ requests made with fetch so
483
+ // that a future upstream rewrite does not silently start 404ing.
484
+ if (typeof window.fetch === "function") {
485
+ var realFetch = window.fetch.bind(window);
486
+ window.fetch = function (input, init) {
487
+ var url = typeof input === "string"
488
+ ? input
489
+ : input instanceof URL ? input.toString() : input && input.url;
490
+
491
+ if (!url || !isApiUrl(url)) return realFetch(input, init);
492
+
493
+ var method = ((init && init.method) || (input && input.method) || "GET").toUpperCase();
494
+ var body = init ? init.body : null;
495
+
496
+ return dispatchToCore(method, url, body).then(function (response) {
497
+ var payload = response.bytes ? response.bytes : response.body;
498
+ return new Response(payload, { status: response.status, headers: response.headers });
499
+ }, function (error) {
500
+ if (error && error.apiStatus) {
501
+ return new Response(JSON.stringify({ error: error.message }), {
502
+ status: error.apiStatus,
503
+ headers: { "Content-Type": "application/json; charset=utf-8" }
504
+ });
505
+ }
506
+ throw error;
507
+ });
508
+ };
509
+ }
510
+
511
+ // --------------------------------------------------------------- downloads
512
+
513
+ /**
514
+ * Serve the Download button from IndexedDB.
515
+ *
516
+ * upstream: els.downloadButton.onclick = () => {
517
+ * window.location.href = `/api/documents/${document.id}/download`;
518
+ * }
519
+ *
520
+ * A navigation cannot be intercepted, so the click is caught in the capture
521
+ * phase at the document level - before the target phase, which is what stops
522
+ * upstream's own handler from running - and the file is handed over as a blob
523
+ * URL instead.
524
+ */
525
+ document.addEventListener(
526
+ "click",
527
+ function (event) {
528
+ var target = event.target;
529
+ if (!target || typeof target.closest !== "function") return;
530
+ if (!target.closest("#downloadButton")) return;
531
+
532
+ event.preventDefault();
533
+ event.stopPropagation();
534
+ if (typeof event.stopImmediatePropagation === "function") event.stopImmediatePropagation();
535
+
536
+ if (!lastDocumentId) {
537
+ console.warn("[SimpleDocReview] No document is selected, so there is nothing to download.");
538
+ return;
539
+ }
540
+
541
+ api.handle("GET", "/api/documents/" + encodeURIComponent(lastDocumentId) + "/download", null)
542
+ .then(function (response) {
543
+ if (response.status !== 200 || !response.bytes) {
544
+ var message = "The original upload could not be found.";
545
+ try {
546
+ message = JSON.parse(response.body).error || message;
547
+ } catch (error) { /* keep the default */ }
548
+ console.warn("[SimpleDocReview] " + message);
549
+ return;
550
+ }
551
+ var blob = new Blob([response.bytes], {
552
+ type: response.headers["Content-Type"] || "application/octet-stream"
553
+ });
554
+ var url = URL.createObjectURL(blob);
555
+ var link = document.createElement("a");
556
+ link.href = url;
557
+ link.download = response.filename || "document";
558
+ link.rel = "noopener";
559
+ document.body.appendChild(link);
560
+ link.click();
561
+ document.body.removeChild(link);
562
+ // Revoke on a later turn: Firefox cancels an in-flight download if the
563
+ // object URL disappears in the same task as the click.
564
+ setTimeout(function () { URL.revokeObjectURL(url); }, 30000);
565
+ })
566
+ .catch(function (error) {
567
+ console.error("[SimpleDocReview] Download failed:", error);
568
+ });
569
+ },
570
+ true
571
+ );
572
+
573
+ // ------------------------------------------------------------------ notice
574
+
575
+ var UPSTREAM_URL = "https://github.com/eputnam77/SimpleDocReview";
576
+
577
+ /**
578
+ * Say what this is.
579
+ *
580
+ * Upstream's README can leave storage unexplained, because you started the
581
+ * server yourself and the files are on your disk. A public URL cannot: a
582
+ * visitor's default assumption is a shared service that keeps their records,
583
+ * and this deployment keeps nothing. Somebody who ran a real approval round
584
+ * here and then cleared their browser would lose it with no warning.
585
+ *
586
+ * So the page says so twice: a badge that never goes away, and one notice
587
+ * explaining where the data lives. Both are injected rather than edited into
588
+ * upstream's markup, and both are styled inline so they do not depend on
589
+ * upstream's stylesheet.
590
+ */
591
+ function addDemoBadge() {
592
+ var heading = document.querySelector(".brand h1");
593
+ if (!heading || heading.querySelector(".sdr-demo-badge")) return;
594
+
595
+ var badge = document.createElement("span");
596
+ badge.className = "sdr-demo-badge";
597
+ badge.textContent = "Demo";
598
+ badge.title = "Runs entirely in your browser. Records are not stored on a server.";
599
+ // Upstream's palette tokens, so the badge retints with the app rather than
600
+ // sitting on it in a colour of its own.
601
+ badge.style.cssText = [
602
+ "margin-left:8px", "vertical-align:middle", "white-space:nowrap",
603
+ "padding:2px 6px", "border-radius:5px",
604
+ "border:1px solid var(--line, #d9e1e4)",
605
+ "color:var(--muted, #64737c)",
606
+ "font-size:.6em", "font-weight:700",
607
+ "letter-spacing:.08em", "text-transform:uppercase"
608
+ ].join(";");
609
+ heading.appendChild(badge);
610
+
611
+ var dot = document.querySelector(".brand .live-dot");
612
+ if (dot) dot.title = "Demo build - no server";
613
+ }
614
+
615
+ function showStorageNotice() {
616
+ if (window.sessionStorage && window.sessionStorage.getItem("sdrNoticeDismissed")) return;
617
+
618
+ // Borrowed from upstream's own .toast rule so the notice reads as part of
619
+ // the app: same ink, same radius, same shadow, same right margin. It sits
620
+ // one toast-height higher so an actual toast still has its usual corner.
621
+ var bar = document.createElement("aside");
622
+ bar.setAttribute("role", "note");
623
+ bar.style.cssText = [
624
+ "position:fixed", "right:22px", "bottom:84px", "z-index:60",
625
+ "max-width:min(460px, calc(100vw - 44px))",
626
+ "display:flex", "gap:12px", "align-items:flex-start",
627
+ "padding:12px 14px", "border-radius:8px",
628
+ "background:#172126", "color:#fff",
629
+ "box-shadow:0 18px 45px rgba(23, 33, 38, 0.28)",
630
+ "font-size:13px", "line-height:1.5"
631
+ ].join(";");
632
+
633
+ var text = document.createElement("p");
634
+ text.style.cssText = "margin:0";
635
+ text.innerHTML =
636
+ "<strong>Demo, not a review system.</strong> " +
637
+ (activeStore && activeStore.volatile
638
+ ? "This browser blocks storage for embedded pages, so anything you add lasts only until you close the tab. "
639
+ : "Documents and review records live only in this browser, and clearing site data deletes them. ") +
640
+ 'Nothing is sent to a server. For real reviews, <a href="' + UPSTREAM_URL +
641
+ '" target="_blank" rel="noopener" style="color:inherit;text-decoration:underline">run it locally</a>.';
642
+
643
+ var dismiss = document.createElement("button");
644
+ dismiss.type = "button";
645
+ dismiss.textContent = "Got it";
646
+ dismiss.style.cssText = [
647
+ "flex:0 0 auto", "cursor:pointer", "border-radius:6px", "border:0",
648
+ "background:rgba(255,255,255,0.14)", "color:inherit",
649
+ "padding:5px 10px", "font-size:inherit", "font-weight:600"
650
+ ].join(";");
651
+ dismiss.addEventListener("click", function () {
652
+ bar.remove();
653
+ if (window.sessionStorage) window.sessionStorage.setItem("sdrNoticeDismissed", "1");
654
+ });
655
+
656
+ bar.appendChild(text);
657
+ bar.appendChild(dismiss);
658
+ document.body.appendChild(bar);
659
+ }
660
+
661
+ // Wait for the store probe so the notice can tell the truth about persistence.
662
+ function whenReady(callback) {
663
+ if (document.readyState === "loading") {
664
+ document.addEventListener("DOMContentLoaded", callback, { once: true });
665
+ } else {
666
+ callback();
667
+ }
668
+ }
669
+ whenReady(function () {
670
+ addDemoBadge();
671
+ resolveStore().then(showStorageNotice, showStorageNotice);
672
+ });
673
+
674
+ // ------------------------------------------------------------------ console
675
+
676
+ /**
677
+ * Debug surface. `__sdrStaticApi.reset()` clears the workspace, which is the
678
+ * only way to start over other than clearing site data in the browser.
679
+ */
680
+ window.__sdrStaticApi = {
681
+ api: api,
682
+ store: store,
683
+ reset: function () {
684
+ return store.clear().then(function () {
685
+ window.location.reload();
686
+ });
687
+ }
688
+ };
689
+ })();
references.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # References
2
+
3
+ ## SimpleDocReview
4
+ Codebase for SimpleDocReview. Any update we make in SimpleDocReview codebase, should be easily flowing to `sdr-streamlit`. See `dep-streamlit` for how we made that possible.
5
+
6
+ C:\dev\SimpleDocReview
7
+
8
+
9
+ ## DocEditorPlayground
10
+ This is my HuggingFace Space page for DocEditorPlayground. Review it and follow the overall codebase for reference. Note, mirror the UI design (if itmakes sense), but look at the files and needs within this project repo for how to build out this new HuggingFace Space project. Static space on HuggingFace--not Docker.
11
+
12
+ C:\dev\dep-streamlit
scripts/build-static.ps1 ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <#
2
+ .SYNOPSIS
3
+ Build the static site that the Hugging Face Static Space serves.
4
+
5
+ .DESCRIPTION
6
+ Pipeline:
7
+
8
+ app/ (clean upstream mirror)
9
+ + overlay/ (the browser-side API and its wiring)
10
+ -> .build/out/
11
+ -> copied to the repository root
12
+
13
+ There is no compiler and no package manager here: upstream's front end is
14
+ plain HTML, CSS, and JavaScript. The build is a copy, one HTML edit that
15
+ inserts the overlay's <script> tags ahead of upstream's app.js, and the
16
+ bookkeeping that keeps the repository root free of stale output.
17
+
18
+ Hugging Face Static Spaces serve the repository root, so the generated files
19
+ have to sit there next to README.md. Everything the build emits is recorded
20
+ in .space-build-manifest and removed before the next copy.
21
+
22
+ .PARAMETER AcceptUpstreamChanges
23
+ Re-record the upstream hashes in overlay/ported-from.json. Use this only
24
+ after reading the upstream diff and carrying any behavior change into
25
+ overlay/sdr-api-core.js - it is an acknowledgement, not a fix.
26
+
27
+ .EXAMPLE
28
+ .\scripts\build-static.ps1
29
+ #>
30
+ [CmdletBinding()]
31
+ param(
32
+ [switch] $AcceptUpstreamChanges
33
+ )
34
+
35
+ $ErrorActionPreference = 'Stop'
36
+
37
+ $repoRoot = Split-Path -Parent $PSScriptRoot
38
+ $appDir = Join-Path $repoRoot 'app'
39
+ $overlayDir = Join-Path $repoRoot 'overlay'
40
+ $buildDir = Join-Path $repoRoot '.build'
41
+ $outDir = Join-Path $buildDir 'out'
42
+ $manifestPath = Join-Path $repoRoot '.space-build-manifest'
43
+ $portedFromPath = Join-Path $overlayDir 'ported-from.json'
44
+
45
+ # Repository files that are never build output. The cleanup step refuses to
46
+ # touch these even if the manifest somehow names one.
47
+ $protected = @(
48
+ '.git', '.github', '.claude', '.build',
49
+ '.gitignore', '.gitattributes', '.dockerignore', '.space-build-manifest',
50
+ 'app', 'overlay', 'scripts', 'tests',
51
+ 'README.md', 'DEPLOY.md', 'CLAUDE.md', 'Dockerfile', 'UPSTREAM.json',
52
+ 'references.md'
53
+ )
54
+
55
+ # The overlay files copied to the site root, in the order the page loads them.
56
+ $overlayScripts = @('sdr-api-core.js', 'sdr-api-shim.js')
57
+
58
+ if (-not (Test-Path -LiteralPath (Join-Path $appDir 'app.py'))) {
59
+ throw 'app/ is empty or missing. Run .\scripts\sync-upstream.ps1 first.'
60
+ }
61
+
62
+ function Get-Sha256([string] $path) {
63
+ return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()
64
+ }
65
+
66
+ # --- Guard: the port must still match what it was ported from -------------
67
+
68
+ # overlay/sdr-api-core.js reimplements app.py in JavaScript. Nothing about a
69
+ # copy-and-inject build would fail if upstream changed a rubric rule or a status
70
+ # transition, so the only protection is refusing to ship until someone has
71
+ # looked at the diff.
72
+
73
+ $ported = Get-Content -LiteralPath $portedFromPath -Raw | ConvertFrom-Json
74
+ $actual = [ordered]@{}
75
+ foreach ($name in $ported.sources.PSObject.Properties.Name) {
76
+ $sourcePath = Join-Path $appDir $name
77
+ if (-not (Test-Path -LiteralPath $sourcePath -PathType Leaf)) {
78
+ throw "overlay/ported-from.json names $name, which is not in app/. Re-run sync-upstream.ps1."
79
+ }
80
+ $actual[$name] = Get-Sha256 $sourcePath
81
+ }
82
+
83
+ $drifted = $actual.Keys | Where-Object { $actual[$_] -ne $ported.sources.$_ }
84
+
85
+ if ($AcceptUpstreamChanges) {
86
+ if ($drifted.Count -eq 0) {
87
+ Write-Host 'Upstream hashes already current; nothing to accept.' -ForegroundColor Yellow
88
+ }
89
+ else {
90
+ $upstreamJsonPath = Join-Path $repoRoot 'UPSTREAM.json'
91
+ $commit = if (Test-Path -LiteralPath $upstreamJsonPath) {
92
+ (Get-Content -LiteralPath $upstreamJsonPath -Raw | ConvertFrom-Json).commit
93
+ } else { 'unknown' }
94
+
95
+ $ported.portedAt = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd')
96
+ $ported.upstreamCommit = $commit
97
+ foreach ($name in $drifted) { $ported.sources.$name = $actual[$name] }
98
+
99
+ $json = ($ported | ConvertTo-Json -Depth 5) + [Environment]::NewLine
100
+ [System.IO.File]::WriteAllText($portedFromPath, $json, (New-Object System.Text.UTF8Encoding $false))
101
+ Write-Host "Recorded new upstream hashes for: $($drifted -join ', ')" -ForegroundColor Green
102
+ }
103
+ }
104
+ elseif ($drifted.Count -gt 0) {
105
+ throw @"
106
+ Upstream changed in files the overlay reimplements: $($drifted -join ', ')
107
+
108
+ overlay/sdr-api-core.js is a hand-written port of app.py's API, so an upstream
109
+ change to a route, a rubric rule, a status transition, or the front end's
110
+ request shapes will not reach the Space on its own.
111
+
112
+ 1. Read the diff:
113
+ git -C C:\dev\SimpleDocReview diff $($ported.upstreamCommit) -- $($drifted -join ' ')
114
+ 2. Carry any behavior change into overlay/sdr-api-core.js.
115
+ 3. Re-check the port: node tests\parity\run-parity.mjs
116
+ 4. Acknowledge it: .\scripts\build-static.ps1 -AcceptUpstreamChanges
117
+ "@
118
+ }
119
+
120
+ # --- Guard: the overlay must stay additive -------------------------------
121
+
122
+ # Upstream's files are copied verbatim. If the overlay ever contained a file
123
+ # that lands on the same path, the copy order would decide which one shipped -
124
+ # and a silently shadowed upstream file is exactly the drift app/ exists to
125
+ # prevent.
126
+ $upstreamTargets = @{ 'index.html' = $true }
127
+ Get-ChildItem -LiteralPath (Join-Path $appDir 'static') -File |
128
+ ForEach-Object { $upstreamTargets["static/$($_.Name)"] = $true }
129
+
130
+ foreach ($script in $overlayScripts) {
131
+ if ($upstreamTargets.ContainsKey($script)) {
132
+ throw "overlay/$script would overwrite an upstream file of the same name. Rename it."
133
+ }
134
+ if (-not (Test-Path -LiteralPath (Join-Path $overlayDir $script) -PathType Leaf)) {
135
+ throw "overlay/$script is missing."
136
+ }
137
+ }
138
+
139
+ # --- Stage ---------------------------------------------------------------
140
+
141
+ if (Test-Path -LiteralPath $buildDir) {
142
+ Remove-Item -LiteralPath $buildDir -Recurse -Force
143
+ }
144
+ New-Item -ItemType Directory -Force -Path (Join-Path $outDir 'static') | Out-Null
145
+
146
+ Write-Host 'Staging app/static -> .build/out' -ForegroundColor Cyan
147
+
148
+ # index.html moves to the site root: Hugging Face serves the repository root as
149
+ # the web root, and README.md's front matter names index.html as the app file.
150
+ Copy-Item -LiteralPath (Join-Path $appDir 'static/index.html') -Destination (Join-Path $outDir 'index.html')
151
+
152
+ # Everything else keeps its /static/ path, which is what index.html asks for.
153
+ Get-ChildItem -LiteralPath (Join-Path $appDir 'static') -File |
154
+ Where-Object { $_.Name -ne 'index.html' } |
155
+ ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $outDir 'static') }
156
+
157
+ Write-Host 'Applying overlay/ -> .build/out' -ForegroundColor Cyan
158
+ foreach ($script in $overlayScripts) {
159
+ Copy-Item -LiteralPath (Join-Path $overlayDir $script) -Destination $outDir
160
+ }
161
+
162
+ # --- Insert the overlay's script tags ------------------------------------
163
+
164
+ # The shim has to be installed before upstream's app.js runs, because app.js
165
+ # fires its first three requests at import time. Inserting the tags is a
166
+ # transform of upstream's HTML rather than a copy of it, so there is no second
167
+ # index.html in this repo to drift from upstream's.
168
+
169
+ $indexPath = Join-Path $outDir 'index.html'
170
+ $html = [System.IO.File]::ReadAllText($indexPath)
171
+
172
+ $anchor = '<script src="/static/app.js"></script>'
173
+ if ($html -notlike "*$anchor*") {
174
+ throw @"
175
+ Could not find upstream's app.js script tag in static/index.html.
176
+
177
+ Expected: $anchor
178
+
179
+ The overlay has to load before app.js does. Update the anchor in
180
+ scripts/build-static.ps1 to match upstream's markup.
181
+ "@
182
+ }
183
+
184
+ $injected = (($overlayScripts | ForEach-Object { "<script src=`"/$_`"></script>" }) -join "`n ")
185
+ $html = $html.Replace($anchor, "$injected`n $anchor")
186
+ [System.IO.File]::WriteAllText($indexPath, $html, (New-Object System.Text.UTF8Encoding $false))
187
+
188
+ Write-Host " inserted $($overlayScripts.Count) overlay script tag(s) before app.js"
189
+
190
+ # --- Remove the previous build's output from the repository root ----------
191
+
192
+ if (Test-Path -LiteralPath $manifestPath) {
193
+ $stale = Get-Content -LiteralPath $manifestPath |
194
+ Where-Object { $_.Trim() -and -not $_.StartsWith('#') }
195
+ foreach ($entry in $stale) {
196
+ $name = $entry.Trim()
197
+ if ($protected -contains $name) {
198
+ Write-Warning "Manifest names a protected path ('$name'); refusing to delete it."
199
+ continue
200
+ }
201
+ # Reject anything that is not a plain top-level name.
202
+ if ($name -match '[\\/]' -or $name -eq '.' -or $name -eq '..') {
203
+ Write-Warning "Manifest entry '$name' is not a top-level name; skipping."
204
+ continue
205
+ }
206
+ $target = Join-Path $repoRoot $name
207
+ if (Test-Path -LiteralPath $target) {
208
+ Remove-Item -LiteralPath $target -Recurse -Force
209
+ }
210
+ }
211
+ }
212
+
213
+ # --- Copy the new output to the repository root ---------------------------
214
+
215
+ Write-Host 'Copying build output to the repository root' -ForegroundColor Cyan
216
+ $generated = @()
217
+ foreach ($item in Get-ChildItem -LiteralPath $outDir -Force) {
218
+ if ($protected -contains $item.Name) {
219
+ throw "Build output contains '$($item.Name)', which collides with a repository file. Resolve before deploying."
220
+ }
221
+ Copy-Item -LiteralPath $item.FullName -Destination $repoRoot -Recurse -Force
222
+ $generated += $item.Name
223
+ }
224
+
225
+ $manifestLines = @(
226
+ '# Generated by scripts/build-static.ps1 - do not edit.',
227
+ '# Top-level repository paths that are build output, deleted and rewritten',
228
+ '# on each build.'
229
+ ) + ($generated | Sort-Object)
230
+ Set-Content -LiteralPath $manifestPath -Value $manifestLines -Encoding ascii
231
+
232
+ # --- Summary --------------------------------------------------------------
233
+
234
+ $outFiles = Get-ChildItem -LiteralPath $outDir -Recurse -File
235
+ $sizeKb = [math]::Round((($outFiles | Measure-Object -Property Length -Sum).Sum / 1KB), 1)
236
+
237
+ Write-Host ''
238
+ Write-Host "Static site built: $($outFiles.Count) files, $sizeKb KB" -ForegroundColor Green
239
+ Write-Host "Generated at repo root: $($generated -join ', ')"
240
+ Write-Host ''
241
+ Write-Host 'Preview it locally with:' -ForegroundColor Cyan
242
+ Write-Host " python -m http.server 8000 --directory `"$repoRoot`""
243
+ Write-Host ' then open http://localhost:8000'
scripts/deploy.ps1 ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <#
2
+ .SYNOPSIS
3
+ Sync upstream, build the static site, verify it, commit, and push to Hugging Face.
4
+
5
+ .DESCRIPTION
6
+ The one command to run after updating SimpleDocReview:
7
+
8
+ .\scripts\deploy.ps1
9
+
10
+ It re-mirrors app/ from the local upstream checkout, builds the site into the
11
+ repository root, runs the parity and browser checks, commits with the
12
+ upstream commit in the message, and pushes to the Hugging Face Space remote.
13
+
14
+ The Space serves files directly with no build step of its own, so what you
15
+ push is exactly what visitors get - which is also why the checks run before
16
+ the push rather than after it. A broken deploy is live immediately.
17
+
18
+ .PARAMETER UpstreamPath
19
+ Local SimpleDocReview checkout. Defaults to C:\dev\SimpleDocReview.
20
+
21
+ .PARAMETER Message
22
+ Commit message. Defaults to "chore: sync simpledocreview @ <sha>".
23
+
24
+ .PARAMETER Remote
25
+ Git remote to push to. Defaults to 'hf' (the Hugging Face Space).
26
+
27
+ .PARAMETER AlsoPushOrigin
28
+ Additionally push to 'origin' (the GitHub mirror of this deployment repo).
29
+
30
+ .PARAMETER SkipSync
31
+ Do not re-mirror app/; build and deploy what is already there.
32
+
33
+ .PARAMETER SkipBuild
34
+ Do not rebuild; verify, commit, and push the site already at the repo root.
35
+
36
+ .PARAMETER SkipTests
37
+ Do not run the parity and browser checks. They are the only thing standing
38
+ between an upstream change and a Space that quietly behaves differently, so
39
+ skip them only when you have just run them by hand.
40
+
41
+ .PARAMETER AllowDirty
42
+ Pass through to sync-upstream.ps1: allow a dirty upstream working tree.
43
+
44
+ .PARAMETER DryRun
45
+ Sync, build, and verify, show what would be committed, but do not commit or push.
46
+
47
+ .EXAMPLE
48
+ .\scripts\deploy.ps1
49
+ .EXAMPLE
50
+ .\scripts\deploy.ps1 -Message "fix: correct the vague-language snippet" -AlsoPushOrigin
51
+ #>
52
+ [CmdletBinding()]
53
+ param(
54
+ [string] $UpstreamPath = 'C:\dev\SimpleDocReview',
55
+ [string] $Message,
56
+ [string] $Remote = 'hf',
57
+ [switch] $AlsoPushOrigin,
58
+ [switch] $SkipSync,
59
+ [switch] $SkipBuild,
60
+ [switch] $SkipTests,
61
+ [switch] $AllowDirty,
62
+ [switch] $DryRun
63
+ )
64
+
65
+ $ErrorActionPreference = 'Stop'
66
+
67
+ $repoRoot = Split-Path -Parent $PSScriptRoot
68
+
69
+ if (-not $SkipSync) {
70
+ $syncArgs = @{ UpstreamPath = $UpstreamPath }
71
+ if ($AllowDirty) { $syncArgs['AllowDirty'] = $true }
72
+ & (Join-Path $PSScriptRoot 'sync-upstream.ps1') @syncArgs
73
+ Write-Host ''
74
+ }
75
+
76
+ if (-not $SkipBuild) {
77
+ & (Join-Path $PSScriptRoot 'build-static.ps1')
78
+ Write-Host ''
79
+ }
80
+
81
+ if (-not $SkipTests) {
82
+ Push-Location $repoRoot
83
+ try {
84
+ Write-Host 'Checking the browser API against the real app.py' -ForegroundColor Cyan
85
+ & node (Join-Path $repoRoot 'tests\parity\run-parity.mjs')
86
+ if ($LASTEXITCODE -ne 0) {
87
+ throw 'Parity check failed: the browser API no longer matches app.py. Nothing was deployed.'
88
+ }
89
+ Write-Host ''
90
+ Write-Host 'Checking the built site in a browser' -ForegroundColor Cyan
91
+ & node (Join-Path $repoRoot 'tests\browser\run-browser-check.mjs')
92
+ if ($LASTEXITCODE -ne 0) {
93
+ throw 'Browser check failed. Nothing was deployed.'
94
+ }
95
+ Write-Host ''
96
+ }
97
+ finally { Pop-Location }
98
+ }
99
+
100
+ Push-Location $repoRoot
101
+ try {
102
+ # Verify the target remote exists before doing anything that needs undoing.
103
+ $remotes = & git remote
104
+ if ($remotes -notcontains $Remote) {
105
+ $missingRemoteMessage = @"
106
+ Git remote '$Remote' is not configured.
107
+
108
+ Create the Space at https://huggingface.co/new-space (choose the Static SDK,
109
+ Blank template), then wire it up:
110
+
111
+ git remote add $Remote https://huggingface.co/spaces/<user>/<space-name>
112
+
113
+ See DEPLOY.md for the full first-time setup.
114
+ "@
115
+ # A dry run only reports, so a missing remote is a warning there and a
116
+ # hard stop for a real deploy.
117
+ if ($DryRun) { Write-Warning $missingRemoteMessage } else { throw $missingRemoteMessage }
118
+ }
119
+
120
+ $changes = & git status --porcelain
121
+ if ([string]::IsNullOrWhiteSpace(($changes -join ''))) {
122
+ Write-Host 'Nothing to deploy - working tree is clean.' -ForegroundColor Yellow
123
+ return
124
+ }
125
+
126
+ if (-not $Message) {
127
+ $upstreamJsonPath = Join-Path $repoRoot 'UPSTREAM.json'
128
+ if (Test-Path -LiteralPath $upstreamJsonPath) {
129
+ $u = Get-Content -LiteralPath $upstreamJsonPath -Raw | ConvertFrom-Json
130
+ $short = if ($u.commit.Length -ge 7) { $u.commit.Substring(0, 7) } else { $u.commit }
131
+ $Message = "chore: sync simpledocreview @ $short"
132
+ }
133
+ else {
134
+ $Message = 'chore: sync simpledocreview'
135
+ }
136
+ }
137
+
138
+ if ($DryRun) {
139
+ Write-Host '--- dry run, nothing committed or pushed ---' -ForegroundColor Yellow
140
+ Write-Host "Would commit: $Message"
141
+ Write-Host "Would push to: $Remote$(if ($AlsoPushOrigin) { ' and origin' })"
142
+ Write-Host ''
143
+ $changed = (& git status --porcelain).Count
144
+ Write-Host "$changed path(s) changed. Summary by top-level entry:"
145
+ & git status --porcelain |
146
+ ForEach-Object { ($_.Substring(3) -split '[/\\]')[0].Trim('"') } |
147
+ Group-Object |
148
+ Sort-Object -Property Count -Descending |
149
+ ForEach-Object { Write-Host (" {0,5} {1}" -f $_.Count, $_.Name) }
150
+ return
151
+ }
152
+
153
+ & git add -A
154
+ if ($LASTEXITCODE -ne 0) { throw 'git add failed' }
155
+
156
+ & git commit -m $Message
157
+ if ($LASTEXITCODE -ne 0) { throw 'git commit failed' }
158
+
159
+ $branch = (& git rev-parse --abbrev-ref HEAD).Trim()
160
+
161
+ Write-Host ''
162
+ Write-Host "Pushing $branch -> $Remote" -ForegroundColor Cyan
163
+ & git push $Remote $branch
164
+ if ($LASTEXITCODE -ne 0) {
165
+ throw "Push to '$Remote' failed. If the Space has commits this repo lacks, run: git pull --rebase $Remote $branch"
166
+ }
167
+
168
+ if ($AlsoPushOrigin) {
169
+ Write-Host "Pushing $branch -> origin" -ForegroundColor Cyan
170
+ & git push origin $branch
171
+ if ($LASTEXITCODE -ne 0) { throw 'Push to origin failed.' }
172
+ }
173
+
174
+ Write-Host ''
175
+ Write-Host 'Deployed. A Static Space serves files directly, so the update is live' -ForegroundColor Green
176
+ Write-Host 'as soon as the push lands - no build wait.' -ForegroundColor Green
177
+ }
178
+ finally { Pop-Location }
scripts/sync-upstream.ps1 ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <#
2
+ .SYNOPSIS
3
+ Mirror the upstream SimpleDocReview checkout into ./app.
4
+
5
+ .DESCRIPTION
6
+ ./app is a vendored copy of upstream, trimmed to what the deployment needs:
7
+ the server (app.py, kept for the Dockerfile escape hatch) and the front end
8
+ (static/) that the Static Space actually serves.
9
+
10
+ This script wipes and re-mirrors it, then records the upstream commit in
11
+ UPSTREAM.json so the Space can always be traced back to a revision.
12
+
13
+ Anything you edit under ./app is destroyed by the next run. Fix upstream
14
+ instead, then re-sync.
15
+
16
+ .PARAMETER UpstreamPath
17
+ The local SimpleDocReview checkout. Defaults to C:\dev\SimpleDocReview.
18
+
19
+ .PARAMETER AllowDirty
20
+ Sync even when the upstream checkout has uncommitted changes. Without this,
21
+ a dirty upstream is an error, because the recorded commit would not describe
22
+ what actually got deployed.
23
+
24
+ .EXAMPLE
25
+ .\scripts\sync-upstream.ps1
26
+ #>
27
+ [CmdletBinding()]
28
+ param(
29
+ [string] $UpstreamPath = 'C:\dev\SimpleDocReview',
30
+ [switch] $AllowDirty
31
+ )
32
+
33
+ $ErrorActionPreference = 'Stop'
34
+
35
+ $repoRoot = Split-Path -Parent $PSScriptRoot
36
+ $appDir = Join-Path $repoRoot 'app'
37
+
38
+ # --- Validate upstream -----------------------------------------------------
39
+
40
+ if (-not (Test-Path -LiteralPath $UpstreamPath -PathType Container)) {
41
+ throw "Upstream path not found: $UpstreamPath"
42
+ }
43
+
44
+ $upstreamAppPy = Join-Path $UpstreamPath 'app.py'
45
+ if (-not (Test-Path -LiteralPath $upstreamAppPy -PathType Leaf)) {
46
+ throw "No app.py at $UpstreamPath - is that really the SimpleDocReview checkout?"
47
+ }
48
+
49
+ $appPySource = Get-Content -LiteralPath $upstreamAppPy -Raw
50
+ if ($appPySource -notmatch 'server_version\s*=\s*"SimpleDocReview/') {
51
+ throw "app.py at $UpstreamPath does not identify itself as SimpleDocReview."
52
+ }
53
+
54
+ $serverVersion = ([regex]'server_version\s*=\s*"(SimpleDocReview/[^"]+)"').Match($appPySource).Groups[1].Value
55
+
56
+ # --- Read upstream git provenance -----------------------------------------
57
+
58
+ $commit = 'unknown'
59
+ $branch = 'unknown'
60
+ $isDirty = $false
61
+ $originUrl = 'unknown'
62
+
63
+ if (Test-Path -LiteralPath (Join-Path $UpstreamPath '.git')) {
64
+ Push-Location $UpstreamPath
65
+ try {
66
+ $commit = (& git rev-parse HEAD).Trim()
67
+ $branch = (& git rev-parse --abbrev-ref HEAD).Trim()
68
+ $status = & git status --porcelain
69
+ $isDirty = -not [string]::IsNullOrWhiteSpace(($status -join ''))
70
+ try { $originUrl = (& git remote get-url origin).Trim() } catch { $originUrl = 'none' }
71
+ }
72
+ finally { Pop-Location }
73
+ }
74
+ else {
75
+ Write-Warning "$UpstreamPath is not a git repo - provenance will be recorded as 'unknown'."
76
+ }
77
+
78
+ if ($isDirty -and -not $AllowDirty) {
79
+ throw @"
80
+ Upstream checkout has uncommitted changes.
81
+
82
+ Commit them in $UpstreamPath first so the deployed Space maps to a real revision,
83
+ or re-run with -AllowDirty to deploy the working tree as-is.
84
+ "@
85
+ }
86
+
87
+ # --- Mirror upstream -> ./app ---------------------------------------------
88
+
89
+ # Local review data is a user's documents, not source. It must never be copied
90
+ # into a repo that gets pushed to a public Space.
91
+ $excludeDirs = @(
92
+ (Join-Path $UpstreamPath '.git'),
93
+ (Join-Path $UpstreamPath '.github'),
94
+ (Join-Path $UpstreamPath '.claude'),
95
+ (Join-Path $UpstreamPath '.vscode'),
96
+ (Join-Path $UpstreamPath '.idea'),
97
+ (Join-Path $UpstreamPath 'tests'),
98
+ (Join-Path $UpstreamPath 'docs'),
99
+ (Join-Path $UpstreamPath 'scripts'),
100
+ (Join-Path $UpstreamPath 'data'),
101
+ (Join-Path $UpstreamPath 'uploads'),
102
+ '__pycache__', '.pytest_cache', '.ruff_cache', '.mypy_cache'
103
+ )
104
+
105
+ # Repo-hygiene files the deployment does not read. README.md in particular must
106
+ # not land in app/, because the Space card at the repository root is the README
107
+ # Hugging Face renders.
108
+ $excludeFiles = @(
109
+ 'README.md', 'CLAUDE.md', 'CHANGELOG.md',
110
+ '.gitignore', '.gitattributes',
111
+ '*.pyc', '*.log', '.env', '.env.local'
112
+ )
113
+
114
+ Write-Host "Syncing $UpstreamPath -> $appDir" -ForegroundColor Cyan
115
+
116
+ New-Item -ItemType Directory -Force -Path $appDir | Out-Null
117
+
118
+ $robocopyArgs = @(
119
+ $UpstreamPath, $appDir,
120
+ '/MIR', # mirror: also deletes files removed upstream
121
+ '/NFL', '/NDL', # quiet: no per-file or per-directory listing
122
+ '/NJH', '/NP',
123
+ '/R:2', '/W:1'
124
+ ) + @('/XD') + $excludeDirs + @('/XF') + $excludeFiles
125
+
126
+ & robocopy @robocopyArgs | Out-Null
127
+
128
+ # Robocopy exit codes 0-7 are success (8+ means copy failures).
129
+ if ($LASTEXITCODE -ge 8) {
130
+ throw "robocopy failed with exit code $LASTEXITCODE"
131
+ }
132
+
133
+ # --- Sanity-check what landed --------------------------------------------
134
+
135
+ $required = @('app.py', 'static/index.html', 'static/app.js', 'static/styles.css')
136
+ $missing = $required | Where-Object { -not (Test-Path -LiteralPath (Join-Path $appDir $_)) }
137
+ if ($missing.Count -gt 0) {
138
+ throw "Sync incomplete - missing from app/: $($missing -join ', ')"
139
+ }
140
+
141
+ # --- Warn if the Dockerfile's entry point no longer fits app.py ----------
142
+
143
+ # The container calls app.run('0.0.0.0', 7860) positionally, so a change to that
144
+ # signature breaks the escape hatch without breaking the static build - exactly
145
+ # the kind of drift nobody notices until they need the container.
146
+ if ($appPySource -notmatch 'def\s+run\s*\(\s*host[^)]*port') {
147
+ Write-Warning "app.py's run() signature changed. Check the CMD line in Dockerfile still matches."
148
+ }
149
+
150
+ # --- Record provenance ---------------------------------------------------
151
+
152
+ function Get-Sha256([string] $path) {
153
+ return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()
154
+ }
155
+
156
+ $upstream = [ordered]@{
157
+ upstreamRepo = $originUrl
158
+ upstreamPath = $UpstreamPath
159
+ commit = $commit
160
+ branch = $branch
161
+ dirtyWorkingTree = $isDirty
162
+ serverVersion = $serverVersion
163
+ portedSources = [ordered]@{
164
+ 'app.py' = Get-Sha256 (Join-Path $appDir 'app.py')
165
+ 'static/app.js' = Get-Sha256 (Join-Path $appDir 'static/app.js')
166
+ }
167
+ syncedAtUtc = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')
168
+ }
169
+ # Written without a BOM: Windows PowerShell 5.1's -Encoding utf8 emits one, and
170
+ # a BOM breaks strict JSON parsers that may read this file later.
171
+ $upstreamJson = ($upstream | ConvertTo-Json -Depth 4) + [Environment]::NewLine
172
+ [System.IO.File]::WriteAllText(
173
+ (Join-Path $repoRoot 'UPSTREAM.json'),
174
+ $upstreamJson,
175
+ (New-Object System.Text.UTF8Encoding $false)
176
+ )
177
+
178
+ # --- Summary -------------------------------------------------------------
179
+
180
+ $shortCommit = if ($commit.Length -ge 7) { $commit.Substring(0, 7) } else { $commit }
181
+ Write-Host ''
182
+ Write-Host "Synced $serverVersion @ $shortCommit ($branch)" -ForegroundColor Green
183
+ if ($isDirty) { Write-Warning 'Synced from a dirty upstream working tree.' }
184
+ Write-Host ''
185
+
186
+ Push-Location $repoRoot
187
+ try {
188
+ $changes = & git status --porcelain
189
+ if ([string]::IsNullOrWhiteSpace(($changes -join ''))) {
190
+ Write-Host 'No changes - the Space already matches upstream.' -ForegroundColor Yellow
191
+ }
192
+ else {
193
+ Write-Host 'Pending changes:'
194
+ & git status --short
195
+ Write-Host ''
196
+ Write-Host 'Deploy with: .\scripts\deploy.ps1' -ForegroundColor Cyan
197
+ }
198
+ }
199
+ finally { Pop-Location }
sdr-api-core.js ADDED
@@ -0,0 +1,1717 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * sdr-api-core.js - SimpleDocReview's HTTP API, ported to run without a server.
3
+ *
4
+ * A Hugging Face Static Space has no compute, so `app.py` cannot run. This file
5
+ * is a port of every route upstream's `ReviewHandler` serves and of the logic
6
+ * behind them: the rubric analyzer, the DOCX text extractor, status
7
+ * recalculation, the notification queue, and the record migrations.
8
+ *
9
+ * It contains no DOM and no storage engine. Everything environment-specific
10
+ * arrives through `createApi()`:
11
+ *
12
+ * store persistence (app.py's data/reviews.json + uploads/ pair)
13
+ * now clock (app.py utc_now)
14
+ * uuidHex identity (app.py uuid.uuid4().hex)
15
+ * inflateRaw DEFLATE (app.py zipfile)
16
+ *
17
+ * That separation is what makes it testable: `sdr-api-shim.js` supplies
18
+ * IndexedDB and the browser clock, while `tests/parity/` supplies an in-memory
19
+ * store and a fixed clock so these responses can be diffed against the real
20
+ * Python server's.
21
+ *
22
+ * Comments name the app.py function each part mirrors. When upstream changes
23
+ * that file, change this one - never the other way round.
24
+ */
25
+ (function (root, factory) {
26
+ "use strict";
27
+ var api = factory();
28
+ if (typeof module === "object" && module !== null && module.exports) {
29
+ module.exports = api;
30
+ }
31
+ if (root) {
32
+ root.SdrApiCore = api;
33
+ }
34
+ })(typeof globalThis !== "undefined" ? globalThis : this, function () {
35
+ "use strict";
36
+
37
+ // --------------------------------------------------------------- constants
38
+ // app.py: MAX_UPLOAD_BYTES, ALLOWED_EXTENSIONS, CONTACT_FIELDS, *_LABELS.
39
+
40
+ var MAX_UPLOAD_BYTES = 5 * 1024 * 1024;
41
+ var ALLOWED_EXTENSIONS = [".txt", ".md", ".docx"];
42
+ var CONTACT_FIELDS = ["email", "slack", "teams"];
43
+
44
+ var STATUS_LABELS = {
45
+ uploaded: "Uploaded",
46
+ in_review: "In review",
47
+ changes_requested: "Changes requested",
48
+ approved: "Approved"
49
+ };
50
+
51
+ var ASSIGNMENT_LABELS = {
52
+ pending: "Pending",
53
+ commented: "Commented",
54
+ changes_requested: "Changes requested",
55
+ approved: "Approved"
56
+ };
57
+
58
+ var SEVERITY_ORDER = { high: 0, medium: 1, low: 2 };
59
+
60
+ var DOWNLOAD_TYPES = {
61
+ ".txt": "text/plain",
62
+ ".md": "text/markdown",
63
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
64
+ };
65
+
66
+ // Python's `\w` is Unicode-aware where JavaScript's is ASCII-only, so the
67
+ // port uses Unicode property escapes. `\b[\w'-]+\b` can only begin and end on
68
+ // a word character - an apostrophe or hyphen at either edge fails the word
69
+ // boundary - which is what the outer/inner split below spells out.
70
+ var WORD_PATTERN = /[\p{L}\p{N}_](?:[\p{L}\p{N}_'-]*[\p{L}\p{N}_])?/gu;
71
+
72
+ // ------------------------------------------------------------------ errors
73
+
74
+ /**
75
+ * An error carrying the status app.py would have replied with.
76
+ *
77
+ * app.py maps `ValueError` to 400 and calls `send_error_json(..., NOT_FOUND)`
78
+ * for missing records, so the status has to travel with the message for the
79
+ * responses to stay identical.
80
+ */
81
+ function apiError(message, status) {
82
+ var error = new Error(message);
83
+ error.apiStatus = status || 400;
84
+ return error;
85
+ }
86
+
87
+ function badZip(message) {
88
+ // app.py catches zipfile.BadZipFile in do_POST and replies with this text.
89
+ return apiError(message || "The DOCX file appears to be invalid.", 400);
90
+ }
91
+
92
+ // ----------------------------------------------------------------- helpers
93
+
94
+ function two(value) {
95
+ return value < 10 ? "0" + value : String(value);
96
+ }
97
+
98
+ /** app.py utc_now(): an ISO-8601 UTC stamp truncated to whole seconds. */
99
+ function defaultNow() {
100
+ var when = new Date();
101
+ return (
102
+ when.getUTCFullYear() +
103
+ "-" + two(when.getUTCMonth() + 1) +
104
+ "-" + two(when.getUTCDate()) +
105
+ "T" + two(when.getUTCHours()) +
106
+ ":" + two(when.getUTCMinutes()) +
107
+ ":" + two(when.getUTCSeconds()) +
108
+ "+00:00"
109
+ );
110
+ }
111
+
112
+ /** app.py uuid.uuid4().hex: 32 lowercase hex characters, no dashes. */
113
+ function defaultUuidHex() {
114
+ var bytes = new Uint8Array(16);
115
+ globalThis.crypto.getRandomValues(bytes);
116
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
117
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
118
+ var hex = "";
119
+ for (var index = 0; index < bytes.length; index += 1) {
120
+ hex += (bytes[index] < 16 ? "0" : "") + bytes[index].toString(16);
121
+ }
122
+ return hex;
123
+ }
124
+
125
+ /** DEFLATE with no zlib wrapper - what a ZIP member stores. */
126
+ function defaultInflateRaw(bytes) {
127
+ if (typeof DecompressionStream === "undefined") {
128
+ return Promise.reject(
129
+ badZip("This browser cannot read DOCX files: DecompressionStream is unavailable.")
130
+ );
131
+ }
132
+ var stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
133
+ return new Response(stream).arrayBuffer().then(function (buffer) {
134
+ return new Uint8Array(buffer);
135
+ });
136
+ }
137
+
138
+ /** Python `str(value or "")`: falsy values collapse to the empty string. */
139
+ function pyStr(value) {
140
+ if (value === undefined || value === null || value === false || value === 0 || value === "") {
141
+ return "";
142
+ }
143
+ if (Array.isArray(value) && value.length === 0) {
144
+ return "";
145
+ }
146
+ return String(value);
147
+ }
148
+
149
+ /** app.py clean_text(). */
150
+ function cleanText(value, fallback, maxLength) {
151
+ var limit = maxLength === undefined ? 240 : maxLength;
152
+ var text = pyStr(value).trim();
153
+ return (text || (fallback === undefined ? "" : fallback)).slice(0, limit);
154
+ }
155
+
156
+ /** Python re.escape(), for the characters these patterns actually contain. */
157
+ function escapeRegExp(value) {
158
+ return String(value).replace(/[.*+?^${}()|[\]\\\-]/g, "\\$&");
159
+ }
160
+
161
+ function emptyContact() {
162
+ return { email: "", slack: "", teams: "" };
163
+ }
164
+
165
+ function isPlainObject(value) {
166
+ return typeof value === "object" && value !== null && !Array.isArray(value);
167
+ }
168
+
169
+ function hasOwn(target, key) {
170
+ return Object.prototype.hasOwnProperty.call(target, key);
171
+ }
172
+
173
+ /** app.py normalize_contact(). */
174
+ function normalizeContact(payload) {
175
+ var source = isPlainObject(payload) ? payload : {};
176
+ var contact = {};
177
+ CONTACT_FIELDS.forEach(function (field) {
178
+ contact[field] = cleanText(source[field], "", 240);
179
+ });
180
+ return contact;
181
+ }
182
+
183
+ /** app.py owner_from_payload(). */
184
+ function ownerFromPayload(payload) {
185
+ var source = isPlainObject(payload) ? payload : {};
186
+ var owner = { name: cleanText(source.name || source.owner_name, "Owner", 120) };
187
+ var contact = normalizeContact(source);
188
+ CONTACT_FIELDS.forEach(function (field) {
189
+ owner[field] = contact[field];
190
+ });
191
+ return owner;
192
+ }
193
+
194
+ /**
195
+ * Stable descending sort on one string key.
196
+ *
197
+ * Python's `sorted(..., reverse=True)` keeps equal elements in their original
198
+ * order rather than reversing them. These timestamps have one-second
199
+ * resolution, so ties are routine and a plain `.reverse()` would reorder
200
+ * same-second activity that the Python server leaves alone.
201
+ */
202
+ function sortByDesc(items, key) {
203
+ return items.slice().sort(function (left, right) {
204
+ var a = left[key] || "";
205
+ var b = right[key] || "";
206
+ if (a === b) return 0;
207
+ return a < b ? 1 : -1;
208
+ });
209
+ }
210
+
211
+ function sortByAsc(items, read) {
212
+ return items.slice().sort(function (left, right) {
213
+ var a = read(left);
214
+ var b = read(right);
215
+ if (a === b) return 0;
216
+ return a < b ? -1 : 1;
217
+ });
218
+ }
219
+
220
+ // ----------------------------------------------------- filenames and bytes
221
+
222
+ /** app.py sanitize_filename(). */
223
+ function sanitizeFilename(filename) {
224
+ var name = pyStr(filename) || "document";
225
+ var segments = name.split(/[\\/]/);
226
+ name = segments[segments.length - 1].trim();
227
+
228
+ var dot = name.lastIndexOf(".");
229
+ var stem = name;
230
+ var suffix = "";
231
+ // pathlib keeps a leading dot in the stem ('.env' -> stem '.env') and reads
232
+ // a trailing dot as no suffix at all ('notes.' -> stem 'notes.').
233
+ if (dot > 0 && dot < name.length - 1) {
234
+ stem = name.slice(0, dot);
235
+ suffix = name.slice(dot).toLowerCase();
236
+ }
237
+ if (!stem) stem = "document";
238
+
239
+ var cleaned = stem.replace(/[^A-Za-z0-9._ -]+/g, "-").replace(/^[ .\-_]+|[ .\-_]+$/g, "");
240
+ return (cleaned || "document") + suffix;
241
+ }
242
+
243
+ /** pathlib's Path(name).suffix.lower(). */
244
+ function extensionOf(filename) {
245
+ var name = pyStr(filename);
246
+ var segments = name.split(/[\\/]/);
247
+ name = segments[segments.length - 1];
248
+ var dot = name.lastIndexOf(".");
249
+ if (dot <= 0 || dot === name.length - 1) return "";
250
+ return name.slice(dot).toLowerCase();
251
+ }
252
+
253
+ function tryDecode(bytes, encoding) {
254
+ try {
255
+ return new TextDecoder(encoding, { fatal: true }).decode(bytes);
256
+ } catch (error) {
257
+ return null;
258
+ }
259
+ }
260
+
261
+ /**
262
+ * app.py decode_text_bytes(): utf-8-sig, then utf-16, then cp1252, then utf-8
263
+ * with replacement characters.
264
+ *
265
+ * TextDecoder("utf-8") strips a leading BOM, which is what utf-8-sig does.
266
+ * Python's utf-16 codec consumes a BOM when present and assumes
267
+ * little-endian when it is absent.
268
+ *
269
+ * One knowing divergence: WHATWG windows-1252 maps the five bytes Python's
270
+ * cp1252 rejects (0x81, 0x8D, 0x8F, 0x90, 0x9D) rather than raising, so a
271
+ * file Python would fall through to replacement-character utf-8 decodes here
272
+ * as windows-1252 instead.
273
+ */
274
+ function decodeTextBytes(bytes) {
275
+ var utf8 = tryDecode(bytes, "utf-8");
276
+ if (utf8 !== null) return utf8;
277
+
278
+ if (bytes.length % 2 === 0) {
279
+ var bigEndian = bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff;
280
+ var utf16 = tryDecode(bytes, bigEndian ? "utf-16be" : "utf-16le");
281
+ if (utf16 !== null) return utf16;
282
+ }
283
+
284
+ var cp1252 = tryDecode(bytes, "windows-1252");
285
+ if (cp1252 !== null) return cp1252;
286
+
287
+ return new TextDecoder("utf-8").decode(bytes);
288
+ }
289
+
290
+ // --------------------------------------------------------------- ZIP/DOCX
291
+
292
+ function readUint16(bytes, offset) {
293
+ return bytes[offset] | (bytes[offset + 1] << 8);
294
+ }
295
+
296
+ function readUint32(bytes, offset) {
297
+ return (
298
+ (bytes[offset] |
299
+ (bytes[offset + 1] << 8) |
300
+ (bytes[offset + 2] << 16) |
301
+ (bytes[offset + 3] << 24)) >>> 0
302
+ );
303
+ }
304
+
305
+ function findEndOfCentralDirectory(bytes) {
306
+ // The record is 22 bytes plus a comment of at most 65535, so it lies within
307
+ // the last 65557 bytes. Scan backwards for its signature.
308
+ var earliest = Math.max(0, bytes.length - (22 + 65535));
309
+ for (var offset = bytes.length - 22; offset >= earliest; offset -= 1) {
310
+ if (readUint32(bytes, offset) === 0x06054b50) return offset;
311
+ }
312
+ return -1;
313
+ }
314
+
315
+ /**
316
+ * Locate one member of a ZIP archive and return its stored bytes.
317
+ *
318
+ * Just enough of the format to read a DOCX. Sizes come from the central
319
+ * directory because a local header may defer them to a data descriptor, and
320
+ * Word writes members either stored or deflated. ZIP64 is rejected rather
321
+ * than guessed at; Word does not produce it for a 5 MB document.
322
+ */
323
+ function findZipMember(bytes, wanted) {
324
+ var eocd = findEndOfCentralDirectory(bytes);
325
+ if (eocd < 0) throw badZip();
326
+
327
+ var entryCount = readUint16(bytes, eocd + 10);
328
+ var directoryOffset = readUint32(bytes, eocd + 16);
329
+ if (entryCount === 0xffff || directoryOffset === 0xffffffff) {
330
+ throw badZip("This DOCX file uses ZIP64, which this static build cannot read.");
331
+ }
332
+
333
+ var cursor = directoryOffset;
334
+ var decoder = new TextDecoder("utf-8");
335
+ for (var index = 0; index < entryCount; index += 1) {
336
+ if (cursor + 46 > bytes.length || readUint32(bytes, cursor) !== 0x02014b50) {
337
+ throw badZip();
338
+ }
339
+ var method = readUint16(bytes, cursor + 10);
340
+ var compressedSize = readUint32(bytes, cursor + 20);
341
+ var nameLength = readUint16(bytes, cursor + 28);
342
+ var extraLength = readUint16(bytes, cursor + 30);
343
+ var commentLength = readUint16(bytes, cursor + 32);
344
+ var localOffset = readUint32(bytes, cursor + 42);
345
+ var name = decoder.decode(bytes.subarray(cursor + 46, cursor + 46 + nameLength));
346
+
347
+ if (name === wanted) {
348
+ if (localOffset + 30 > bytes.length || readUint32(bytes, localOffset) !== 0x04034b50) {
349
+ throw badZip();
350
+ }
351
+ var localNameLength = readUint16(bytes, localOffset + 26);
352
+ var localExtraLength = readUint16(bytes, localOffset + 28);
353
+ var dataStart = localOffset + 30 + localNameLength + localExtraLength;
354
+ if (dataStart + compressedSize > bytes.length) throw badZip();
355
+ return {
356
+ method: method,
357
+ data: bytes.subarray(dataStart, dataStart + compressedSize)
358
+ };
359
+ }
360
+
361
+ cursor += 46 + nameLength + extraLength + commentLength;
362
+ }
363
+ return null;
364
+ }
365
+
366
+ /** Python html.unescape(), narrowed to what WordprocessingML emits. */
367
+ function unescapeXml(value) {
368
+ return String(value).replace(
369
+ /&(?:#(\d+)|#[xX]([0-9a-fA-F]+)|(amp|lt|gt|quot|apos|nbsp));/g,
370
+ function (match, decimal, hex, named) {
371
+ if (decimal) return String.fromCodePoint(parseInt(decimal, 10));
372
+ if (hex) return String.fromCodePoint(parseInt(hex, 16));
373
+ return {
374
+ amp: "&",
375
+ lt: "<",
376
+ gt: ">",
377
+ quot: '"',
378
+ apos: "'",
379
+ nbsp: " "
380
+ }[named];
381
+ }
382
+ );
383
+ }
384
+
385
+ /** app.py extract_docx_text(). */
386
+ function extractDocxText(bytes, inflateRaw) {
387
+ var member = findZipMember(bytes, "word/document.xml");
388
+ if (!member) {
389
+ // app.py turns zipfile's KeyError into this ValueError.
390
+ throw apiError("The DOCX file does not contain document text.", 400);
391
+ }
392
+
393
+ var raw;
394
+ if (member.method === 0) {
395
+ raw = Promise.resolve(member.data);
396
+ } else if (member.method === 8) {
397
+ raw = inflateRaw(member.data);
398
+ } else {
399
+ raw = Promise.reject(badZip("This DOCX file uses an unsupported compression method."));
400
+ }
401
+
402
+ return raw.then(function (xmlBytes) {
403
+ var xmlText = new TextDecoder("utf-8").decode(xmlBytes);
404
+ var paragraphPattern = /<w:p\b[^>]*>([\s\S]*?)<\/w:p>/g;
405
+ var lines = [];
406
+ var paragraph;
407
+ while ((paragraph = paragraphPattern.exec(xmlText)) !== null) {
408
+ var runPattern = /<w:t\b[^>]*>([\s\S]*?)<\/w:t>/g;
409
+ var runs = [];
410
+ var run;
411
+ while ((run = runPattern.exec(paragraph[1])) !== null) {
412
+ runs.push(unescapeXml(run[1]));
413
+ }
414
+ if (runs.length) lines.push(runs.join(""));
415
+ }
416
+ return lines
417
+ .map(function (line) { return line.trim(); })
418
+ .filter(function (line) { return line.length > 0; })
419
+ .join("\n");
420
+ });
421
+ }
422
+
423
+ /** app.py extract_text(). */
424
+ function extractText(filename, bytes, inflateRaw) {
425
+ var extension = extensionOf(filename);
426
+ if (extension === ".txt" || extension === ".md") {
427
+ return Promise.resolve(decodeTextBytes(bytes).trim());
428
+ }
429
+ if (extension === ".docx") {
430
+ return Promise.resolve()
431
+ .then(function () {
432
+ return extractDocxText(bytes, inflateRaw);
433
+ })
434
+ .then(function (text) {
435
+ return text.trim();
436
+ });
437
+ }
438
+ return Promise.reject(apiError("Unsupported document type.", 400));
439
+ }
440
+
441
+ // --------------------------------------------------------------- analyzer
442
+
443
+ function countWords(text) {
444
+ var matches = text.match(WORD_PATTERN);
445
+ return matches ? matches.length : 0;
446
+ }
447
+
448
+ /** app.py snippet_for(). */
449
+ function snippetFor(text, pattern) {
450
+ var search = new RegExp(pattern.source, pattern.flags.replace("g", ""));
451
+ var match = search.exec(text);
452
+ if (!match) return "";
453
+ var start = Math.max(0, match.index - 70);
454
+ var end = Math.min(text.length, match.index + match[0].length + 70);
455
+ return text.slice(start, end).replace(/\s+/g, " ").trim();
456
+ }
457
+
458
+ /** app.py has_section(). */
459
+ function hasSection(text, terms) {
460
+ for (var index = 0; index < terms.length; index += 1) {
461
+ var term = escapeRegExp(terms[index]);
462
+ if (new RegExp("^\\s*(?:#+\\s*)?" + term + "\\b", "im").test(text)) return true;
463
+ if (new RegExp("\\b" + term + "\\s*:", "i").test(text)) return true;
464
+ }
465
+ return false;
466
+ }
467
+
468
+ var SECTION_CHECKS = [
469
+ ["purpose", ["purpose", "objective"], "Purpose or objective"],
470
+ ["scope", ["scope", "applicability"], "Scope"],
471
+ ["owner", ["owner", "document owner", "responsible party"], "Owner"],
472
+ ["date", ["date", "effective date", "review date"], "Date or review date"],
473
+ ["risk", ["risk", "risks", "risk assessment"], "Risk section"],
474
+ ["approval", ["approval", "approved by", "signature", "sign-off"], "Approval or signature"]
475
+ ];
476
+
477
+ var PLACEHOLDER_CHECKS = [
478
+ ["todo", /\bTODO\b|\bTBD\b|\bTBA\b/i],
479
+ ["insert", /\[(?:insert|add|fill in)[^\]]*\]|<\s*(?:insert|add|fill in)[^>]*>/i],
480
+ ["blank", /_{4,}|\{\{[^}]+\}\}/]
481
+ ];
482
+
483
+ var VAGUE_LANGUAGE = [
484
+ "best effort",
485
+ "as needed",
486
+ "reasonable",
487
+ "as appropriate",
488
+ "when possible",
489
+ "from time to time"
490
+ ];
491
+
492
+ var LONG_SENTENCE_PATTERN = /[^.!?]{260,}[.!?]/;
493
+
494
+ /** app.py analyze_document(). */
495
+ function analyzeDocument(text, now) {
496
+ var findings = [];
497
+ var normalized = pyStr(text).trim();
498
+ var wordCount = countWords(normalized);
499
+
500
+ SECTION_CHECKS.forEach(function (check) {
501
+ var key = check[0];
502
+ var label = check[2];
503
+ if (!hasSection(normalized, check[1])) {
504
+ findings.push({
505
+ id: "missing-" + key,
506
+ severity: key === "approval" ? "high" : "medium",
507
+ title: "Missing " + label.toLowerCase(),
508
+ detail: "Add a clear " + label.toLowerCase() + " section or label before approval.",
509
+ snippet: ""
510
+ });
511
+ }
512
+ });
513
+
514
+ PLACEHOLDER_CHECKS.forEach(function (check) {
515
+ var pattern = check[1];
516
+ if (pattern.test(normalized)) {
517
+ findings.push({
518
+ id: "placeholder-" + check[0],
519
+ severity: "high",
520
+ title: "Unresolved placeholder",
521
+ detail: "Replace template placeholders before the document can be considered final.",
522
+ snippet: snippetFor(normalized, pattern)
523
+ });
524
+ }
525
+ });
526
+
527
+ VAGUE_LANGUAGE.forEach(function (phrase) {
528
+ var pattern = new RegExp("\\b" + escapeRegExp(phrase) + "\\b", "i");
529
+ if (pattern.test(normalized)) {
530
+ findings.push({
531
+ id: "vague-" + phrase.split(" ").join("-"),
532
+ severity: "medium",
533
+ title: 'Vague language: "' + phrase + '"',
534
+ detail: "Make the requirement measurable, accountable, or time-bound.",
535
+ snippet: snippetFor(normalized, pattern)
536
+ });
537
+ }
538
+ });
539
+
540
+ if (wordCount < 80) {
541
+ findings.push({
542
+ id: "short-document",
543
+ severity: "low",
544
+ title: "Very short document",
545
+ detail: "Confirm the document has enough context for reviewers and approvers.",
546
+ snippet: ""
547
+ });
548
+ }
549
+
550
+ if (LONG_SENTENCE_PATTERN.test(normalized)) {
551
+ findings.push({
552
+ id: "long-sentence",
553
+ severity: "low",
554
+ title: "Long sentence",
555
+ detail: "Break long sentences into shorter reviewable statements.",
556
+ snippet: snippetFor(normalized, LONG_SENTENCE_PATTERN)
557
+ });
558
+ }
559
+
560
+ // app.py sorts on (severity rank, title). Compare code units rather than
561
+ // locale: Python compares strings by code point, and these titles contain
562
+ // quote marks that a locale-aware comparison orders differently.
563
+ findings.sort(function (left, right) {
564
+ if (SEVERITY_ORDER[left.severity] !== SEVERITY_ORDER[right.severity]) {
565
+ return SEVERITY_ORDER[left.severity] - SEVERITY_ORDER[right.severity];
566
+ }
567
+ if (left.title === right.title) return 0;
568
+ return left.title < right.title ? -1 : 1;
569
+ });
570
+
571
+ return {
572
+ reviewed_at: now(),
573
+ word_count: wordCount,
574
+ findings: findings,
575
+ counts: {
576
+ high: findings.filter(function (item) { return item.severity === "high"; }).length,
577
+ medium: findings.filter(function (item) { return item.severity === "medium"; }).length,
578
+ low: findings.filter(function (item) { return item.severity === "low"; }).length
579
+ }
580
+ };
581
+ }
582
+
583
+ // ------------------------------------------------------------------ the API
584
+
585
+ /**
586
+ * Build an API instance over one storage backend.
587
+ *
588
+ * @param {object} options
589
+ * @param {object} options.store load/save the record store and uploads
590
+ * @param {function} [options.now] app.py utc_now
591
+ * @param {function} [options.uuidHex] app.py uuid.uuid4().hex
592
+ * @param {function} [options.inflateRaw] raw DEFLATE, for DOCX
593
+ */
594
+ function createApi(options) {
595
+ var settings = options || {};
596
+ var store = settings.store;
597
+ var now = settings.now || defaultNow;
598
+ var uuidHex = settings.uuidHex || defaultUuidHex;
599
+ var inflateRaw = settings.inflateRaw || defaultInflateRaw;
600
+
601
+ if (!store) throw new Error("createApi requires a store.");
602
+
603
+ // ------------------------------------------------------------ migrations
604
+ // Ported from app.py's migrate_* family. The default objects are built
605
+ // eagerly, exactly as Python builds its `defaults` dict, so each call
606
+ // consumes one id from `uuidHex` whether or not the id is used. The parity
607
+ // tests depend on that: they run both implementations off the same
608
+ // deterministic id sequence.
609
+
610
+ function migrateReviewer(reviewer) {
611
+ var changed = false;
612
+ var timestamp = now();
613
+ var defaults = {
614
+ id: uuidHex(),
615
+ name: "Reviewer",
616
+ created_at: timestamp,
617
+ updated_at: timestamp
618
+ };
619
+ Object.keys(defaults).forEach(function (key) {
620
+ if (!reviewer[key]) {
621
+ reviewer[key] = defaults[key];
622
+ changed = true;
623
+ }
624
+ });
625
+ CONTACT_FIELDS.forEach(function (field) {
626
+ if (!hasOwn(reviewer, field)) {
627
+ reviewer[field] = "";
628
+ changed = true;
629
+ }
630
+ });
631
+ return changed;
632
+ }
633
+
634
+ function migrateNotification(notification) {
635
+ var changed = false;
636
+ var defaults = {
637
+ id: uuidHex(),
638
+ recipient_type: "owner",
639
+ recipient_name: "Owner",
640
+ recipient_contact: emptyContact(),
641
+ document_id: "",
642
+ document_title: "",
643
+ event: "notice",
644
+ message: "",
645
+ created_at: now(),
646
+ read_at: null
647
+ };
648
+ Object.keys(defaults).forEach(function (key) {
649
+ if (!hasOwn(notification, key)) {
650
+ notification[key] = defaults[key];
651
+ changed = true;
652
+ }
653
+ });
654
+ if (!isPlainObject(notification.recipient_contact)) {
655
+ notification.recipient_contact = emptyContact();
656
+ changed = true;
657
+ } else {
658
+ CONTACT_FIELDS.forEach(function (field) {
659
+ if (!hasOwn(notification.recipient_contact, field)) {
660
+ notification.recipient_contact[field] = "";
661
+ changed = true;
662
+ }
663
+ });
664
+ }
665
+ return changed;
666
+ }
667
+
668
+ function migrateAssignment(assignment) {
669
+ var changed = false;
670
+ var timestamp = now();
671
+ var defaults = {
672
+ id: uuidHex(),
673
+ reviewer_id: "",
674
+ reviewer_name: "Reviewer",
675
+ reviewer_contact: emptyContact(),
676
+ status: "pending",
677
+ status_label: "Pending",
678
+ assigned_at: timestamp,
679
+ updated_at: timestamp,
680
+ approved_at: null,
681
+ approval_name: "",
682
+ approval_initials: "",
683
+ comments: []
684
+ };
685
+ Object.keys(defaults).forEach(function (key) {
686
+ if (!hasOwn(assignment, key)) {
687
+ assignment[key] = defaults[key];
688
+ changed = true;
689
+ }
690
+ });
691
+ var label = hasOwn(ASSIGNMENT_LABELS, assignment.status)
692
+ ? ASSIGNMENT_LABELS[assignment.status]
693
+ : assignment.status;
694
+ if (assignment.status_label !== label) {
695
+ assignment.status_label = label;
696
+ changed = true;
697
+ }
698
+ if (!isPlainObject(assignment.reviewer_contact)) {
699
+ assignment.reviewer_contact = emptyContact();
700
+ changed = true;
701
+ } else {
702
+ CONTACT_FIELDS.forEach(function (field) {
703
+ if (!hasOwn(assignment.reviewer_contact, field)) {
704
+ assignment.reviewer_contact[field] = "";
705
+ changed = true;
706
+ }
707
+ });
708
+ }
709
+ if (!Array.isArray(assignment.comments)) {
710
+ assignment.comments = [];
711
+ changed = true;
712
+ }
713
+ return changed;
714
+ }
715
+
716
+ /** app.py build_legacy_activity(). */
717
+ function buildLegacyActivity(record) {
718
+ var owner = isPlainObject(record.owner) ? record.owner : {};
719
+ var activity = [
720
+ {
721
+ id: uuidHex(),
722
+ type: "uploaded",
723
+ actor: owner.name || "Owner",
724
+ message: "Uploaded " + (record.filename || "document") + ".",
725
+ created_at: record.created_at || now()
726
+ }
727
+ ];
728
+ if (record.reviewed_at) {
729
+ activity.push({
730
+ id: uuidHex(),
731
+ type: "review_run",
732
+ actor: "System",
733
+ message: "Ran the local rubric review.",
734
+ created_at: record.reviewed_at
735
+ });
736
+ }
737
+ (Array.isArray(record.comments) ? record.comments : []).forEach(function (comment) {
738
+ activity.push({
739
+ id: uuidHex(),
740
+ type: "comment_added",
741
+ actor: comment.author || "Reviewer",
742
+ message: "Commented: " + pyStr(comment.body).slice(0, 120),
743
+ created_at: comment.created_at || now()
744
+ });
745
+ });
746
+ if (record.approved_at) {
747
+ activity.push({
748
+ id: uuidHex(),
749
+ type: "approved",
750
+ actor: "Reviewer",
751
+ message: "Approved the document.",
752
+ created_at: record.approved_at
753
+ });
754
+ }
755
+ return sortByAsc(activity, function (item) { return item.created_at; });
756
+ }
757
+
758
+ function migrateDocument(record) {
759
+ var changed = false;
760
+ var timestamp = now();
761
+ var defaults = {
762
+ id: uuidHex(),
763
+ filename: "document",
764
+ extension: ".txt",
765
+ status: "uploaded",
766
+ created_at: timestamp,
767
+ updated_at: timestamp,
768
+ reviewed_at: null,
769
+ approved_at: null,
770
+ word_count: 0,
771
+ findings: [],
772
+ comments: []
773
+ };
774
+ Object.keys(defaults).forEach(function (key) {
775
+ if (!hasOwn(record, key)) {
776
+ record[key] = defaults[key];
777
+ changed = true;
778
+ }
779
+ });
780
+
781
+ if (!isPlainObject(record.owner)) {
782
+ record.owner = ownerFromPayload({});
783
+ changed = true;
784
+ } else {
785
+ var owner = ownerFromPayload(record.owner);
786
+ if (JSON.stringify(owner) !== JSON.stringify(record.owner)) {
787
+ record.owner = owner;
788
+ changed = true;
789
+ }
790
+ }
791
+
792
+ if (!Array.isArray(record.assignments)) {
793
+ record.assignments = [];
794
+ changed = true;
795
+ }
796
+ record.assignments.forEach(function (assignment) {
797
+ changed = migrateAssignment(assignment) || changed;
798
+ });
799
+
800
+ if (!Array.isArray(record.activity) || record.activity.length === 0) {
801
+ record.activity = buildLegacyActivity(record);
802
+ changed = true;
803
+ }
804
+
805
+ return changed;
806
+ }
807
+
808
+ function migrateDb(data) {
809
+ var changed = false;
810
+ if (!Array.isArray(data.documents)) {
811
+ data.documents = [];
812
+ changed = true;
813
+ }
814
+ if (!Array.isArray(data.reviewers)) {
815
+ data.reviewers = [];
816
+ changed = true;
817
+ }
818
+ if (!Array.isArray(data.notifications)) {
819
+ data.notifications = [];
820
+ changed = true;
821
+ }
822
+ data.reviewers.forEach(function (reviewer) {
823
+ changed = migrateReviewer(reviewer) || changed;
824
+ });
825
+ data.notifications.forEach(function (notification) {
826
+ changed = migrateNotification(notification) || changed;
827
+ });
828
+ data.documents.forEach(function (record) {
829
+ changed = migrateDocument(record) || changed;
830
+ });
831
+ return changed;
832
+ }
833
+
834
+ /** app.py load_db(): read, migrate, and write back when migration ran. */
835
+ function loadDb() {
836
+ return Promise.resolve(store.load()).then(function (loaded) {
837
+ var data = isPlainObject(loaded)
838
+ ? loaded
839
+ : { documents: [], reviewers: [], notifications: [] };
840
+ if (migrateDb(data)) {
841
+ return Promise.resolve(store.save(data)).then(function () {
842
+ return data;
843
+ });
844
+ }
845
+ return data;
846
+ });
847
+ }
848
+
849
+ function saveDb(data) {
850
+ return Promise.resolve(store.save(data));
851
+ }
852
+
853
+ // --------------------------------------------------------- record shapes
854
+
855
+ /** app.py add_activity(). */
856
+ function addActivity(record, eventType, actor, message, timestamp) {
857
+ if (!Array.isArray(record.activity)) record.activity = [];
858
+ record.activity.push({
859
+ id: uuidHex(),
860
+ type: eventType,
861
+ actor: cleanText(actor, "System", 120),
862
+ message: cleanText(message, "", 500),
863
+ created_at: timestamp || now()
864
+ });
865
+ }
866
+
867
+ /** app.py assignment_counts(). */
868
+ function assignmentCounts(record) {
869
+ var counts = { pending: 0, commented: 0, changes_requested: 0, approved: 0 };
870
+ (record.assignments || []).forEach(function (assignment) {
871
+ var status = assignment.status || "pending";
872
+ counts[status] = (hasOwn(counts, status) ? counts[status] : 0) + 1;
873
+ });
874
+ return counts;
875
+ }
876
+
877
+ /** app.py recalculate_document_status(). */
878
+ function recalculateDocumentStatus(record) {
879
+ var assignments = record.assignments || [];
880
+ if (!assignments.length) return;
881
+
882
+ var statuses = assignments.map(function (assignment) {
883
+ return assignment.status || "pending";
884
+ });
885
+ if (statuses.indexOf("changes_requested") !== -1) {
886
+ record.status = "changes_requested";
887
+ record.approved_at = null;
888
+ return;
889
+ }
890
+ var allApproved = statuses.every(function (status) { return status === "approved"; });
891
+ if (allApproved) {
892
+ record.status = "approved";
893
+ record.approved_at = record.approved_at || now();
894
+ return;
895
+ }
896
+ record.status = "in_review";
897
+ record.approved_at = null;
898
+ }
899
+
900
+ /** app.py public_assignment(). */
901
+ function publicAssignment(assignment) {
902
+ return {
903
+ id: assignment.id,
904
+ reviewer_id: assignment.reviewer_id,
905
+ reviewer_name: assignment.reviewer_name,
906
+ reviewer_contact: assignment.reviewer_contact || emptyContact(),
907
+ status: assignment.status,
908
+ status_label: hasOwn(ASSIGNMENT_LABELS, assignment.status)
909
+ ? ASSIGNMENT_LABELS[assignment.status]
910
+ : assignment.status,
911
+ assigned_at: assignment.assigned_at,
912
+ updated_at: assignment.updated_at,
913
+ approved_at: assignment.approved_at === undefined ? null : assignment.approved_at,
914
+ approval_name: assignment.approval_name || "",
915
+ approval_initials: assignment.approval_initials || "",
916
+ comments: assignment.comments || []
917
+ };
918
+ }
919
+
920
+ /** app.py public_document(). */
921
+ function publicDocument(record, includeText) {
922
+ var view = {
923
+ id: record.id,
924
+ filename: record.filename,
925
+ extension: record.extension,
926
+ status: record.status,
927
+ status_label: hasOwn(STATUS_LABELS, record.status)
928
+ ? STATUS_LABELS[record.status]
929
+ : record.status,
930
+ created_at: record.created_at,
931
+ updated_at: record.updated_at,
932
+ reviewed_at: record.reviewed_at === undefined ? null : record.reviewed_at,
933
+ approved_at: record.approved_at === undefined ? null : record.approved_at,
934
+ word_count: record.word_count === undefined ? 0 : record.word_count,
935
+ findings: record.findings || [],
936
+ comments: record.comments || [],
937
+ owner: isPlainObject(record.owner) ? record.owner : ownerFromPayload({}),
938
+ assignments: (record.assignments || []).map(publicAssignment),
939
+ assignment_counts: assignmentCounts(record),
940
+ activity: sortByDesc(record.activity || [], "created_at")
941
+ };
942
+ if (includeText) {
943
+ view.text = record.text || "";
944
+ }
945
+ return view;
946
+ }
947
+
948
+ /** app.py public_reviewer(). */
949
+ function publicReviewer(reviewer) {
950
+ return {
951
+ id: reviewer.id,
952
+ name: reviewer.name,
953
+ email: reviewer.email || "",
954
+ slack: reviewer.slack || "",
955
+ teams: reviewer.teams || "",
956
+ created_at: reviewer.created_at,
957
+ updated_at: reviewer.updated_at
958
+ };
959
+ }
960
+
961
+ /** app.py public_notification(). */
962
+ function publicNotification(notification) {
963
+ return {
964
+ id: notification.id,
965
+ recipient_type: notification.recipient_type,
966
+ recipient_name: notification.recipient_name,
967
+ recipient_contact: notification.recipient_contact || emptyContact(),
968
+ document_id: notification.document_id,
969
+ document_title: notification.document_title,
970
+ event: notification.event,
971
+ message: notification.message,
972
+ created_at: notification.created_at,
973
+ read_at: notification.read_at === undefined ? null : notification.read_at
974
+ };
975
+ }
976
+
977
+ function findDocument(data, documentId) {
978
+ return data.documents.filter(function (record) {
979
+ return record.id === documentId;
980
+ })[0] || null;
981
+ }
982
+
983
+ function findReviewer(data, reviewerId) {
984
+ return data.reviewers.filter(function (reviewer) {
985
+ return reviewer.id === reviewerId;
986
+ })[0] || null;
987
+ }
988
+
989
+ function findAssignment(record, reviewerId) {
990
+ return (record.assignments || []).filter(function (assignment) {
991
+ return assignment.reviewer_id === reviewerId;
992
+ })[0] || null;
993
+ }
994
+
995
+ /** app.py reviewer_payload(). */
996
+ function reviewerPayload(payload, existing) {
997
+ var reviewer = {};
998
+ if (existing) {
999
+ Object.keys(existing).forEach(function (key) {
1000
+ reviewer[key] = existing[key];
1001
+ });
1002
+ }
1003
+ reviewer.name = cleanText(payload.name, "", 120);
1004
+ if (!reviewer.name) throw apiError("Reviewer name is required.", 400);
1005
+ var contact = normalizeContact(payload);
1006
+ CONTACT_FIELDS.forEach(function (field) {
1007
+ reviewer[field] = contact[field];
1008
+ });
1009
+ return reviewer;
1010
+ }
1011
+
1012
+ /** app.py build_assignment(). */
1013
+ function buildAssignment(reviewer) {
1014
+ var timestamp = now();
1015
+ var assignment = {
1016
+ id: uuidHex(),
1017
+ reviewer_id: reviewer.id,
1018
+ reviewer_name: reviewer.name,
1019
+ reviewer_contact: normalizeContact(reviewer),
1020
+ status: "pending",
1021
+ status_label: "Pending",
1022
+ assigned_at: timestamp,
1023
+ updated_at: timestamp,
1024
+ approved_at: null,
1025
+ approval_name: "",
1026
+ approval_initials: "",
1027
+ comments: []
1028
+ };
1029
+ migrateAssignment(assignment);
1030
+ return assignment;
1031
+ }
1032
+
1033
+ /** app.py create_notification(). */
1034
+ function createNotification(data, record, recipientType, recipientName, recipientContact, event, message) {
1035
+ var notification = {
1036
+ id: uuidHex(),
1037
+ recipient_type: recipientType,
1038
+ recipient_name: cleanText(recipientName, "Recipient", 120),
1039
+ recipient_contact: normalizeContact(recipientContact),
1040
+ document_id: record.id,
1041
+ document_title: record.filename,
1042
+ event: event,
1043
+ message: cleanText(message, "", 1000),
1044
+ created_at: now(),
1045
+ read_at: null
1046
+ };
1047
+ if (!Array.isArray(data.notifications)) data.notifications = [];
1048
+ data.notifications.push(notification);
1049
+ addActivity(
1050
+ record,
1051
+ "notification",
1052
+ "System",
1053
+ "Queued notification for " + notification.recipient_name + ": " + notification.message,
1054
+ notification.created_at
1055
+ );
1056
+ return notification;
1057
+ }
1058
+
1059
+ // ------------------------------------------------------------- responses
1060
+
1061
+ function jsonResponse(payload, status) {
1062
+ return {
1063
+ status: status || 200,
1064
+ headers: { "Content-Type": "application/json; charset=utf-8" },
1065
+ body: JSON.stringify(payload)
1066
+ };
1067
+ }
1068
+
1069
+ function errorResponse(message, status) {
1070
+ return jsonResponse({ error: message }, status || 400);
1071
+ }
1072
+
1073
+ function notFound(message) {
1074
+ return errorResponse(message || "Not found.", 404);
1075
+ }
1076
+
1077
+ function parseJsonBody(body) {
1078
+ // app.py read_json_body(): an empty body is {}, malformed JSON is a 400.
1079
+ if (body === null || body === undefined || body === "") return {};
1080
+ if (isPlainObject(body)) return body;
1081
+ try {
1082
+ var parsed = JSON.parse(body);
1083
+ return isPlainObject(parsed) ? parsed : {};
1084
+ } catch (error) {
1085
+ throw apiError("Request body must be valid JSON.", 400);
1086
+ }
1087
+ }
1088
+
1089
+ // -------------------------------------------------------------- handlers
1090
+
1091
+ function handleDocumentsIndex() {
1092
+ return loadDb().then(function (data) {
1093
+ var documents = data.documents.map(function (record) {
1094
+ return publicDocument(record, false);
1095
+ });
1096
+ return jsonResponse({ documents: sortByDesc(documents, "updated_at") });
1097
+ });
1098
+ }
1099
+
1100
+ function handleReviewersIndex() {
1101
+ return loadDb().then(function (data) {
1102
+ var reviewers = data.reviewers.map(publicReviewer);
1103
+ return jsonResponse({
1104
+ reviewers: sortByAsc(reviewers, function (reviewer) {
1105
+ return String(reviewer.name).toLowerCase();
1106
+ })
1107
+ });
1108
+ });
1109
+ }
1110
+
1111
+ function handleNotificationsIndex() {
1112
+ return loadDb().then(function (data) {
1113
+ var notifications = sortByDesc(data.notifications.map(publicNotification), "created_at");
1114
+ var unread = notifications.filter(function (item) { return !item.read_at; }).length;
1115
+ return jsonResponse({ notifications: notifications, unread_count: unread });
1116
+ });
1117
+ }
1118
+
1119
+ function handleDocumentDetail(documentId) {
1120
+ return loadDb().then(function (data) {
1121
+ var record = findDocument(data, documentId);
1122
+ if (!record) return notFound("Document not found.");
1123
+ return jsonResponse(publicDocument(record, true));
1124
+ });
1125
+ }
1126
+
1127
+ function handleDownload(documentId) {
1128
+ return loadDb().then(function (data) {
1129
+ var record = findDocument(data, documentId);
1130
+ if (!record) return notFound("Document not found.");
1131
+ return Promise.resolve(store.getUpload(record.stored_name)).then(function (bytes) {
1132
+ if (!bytes) return notFound("Original upload is missing.");
1133
+ var extension = extensionOf(record.filename);
1134
+ return {
1135
+ status: 200,
1136
+ headers: {
1137
+ "Content-Type": DOWNLOAD_TYPES[extension] || "application/octet-stream",
1138
+ "Content-Disposition": 'attachment; filename="' + record.filename + '"'
1139
+ },
1140
+ bytes: bytes,
1141
+ filename: record.filename
1142
+ };
1143
+ });
1144
+ });
1145
+ }
1146
+
1147
+ /** app.py handle_upload(). */
1148
+ function handleUpload(upload) {
1149
+ if (!upload || !upload.bytes) throw apiError("Upload cannot be empty.", 400);
1150
+ // app.py measures Content-Length, so its 5 MB ceiling covers the whole
1151
+ // multipart request - the file plus a few hundred bytes of part headers.
1152
+ // There is no request here, so the file itself is what gets measured,
1153
+ // which makes this marginally more permissive for a file within a few
1154
+ // hundred bytes of the limit.
1155
+ if (upload.bytes.length > MAX_UPLOAD_BYTES) {
1156
+ throw apiError("Upload is too large. Maximum size is 5 MB.", 400);
1157
+ }
1158
+
1159
+ var fields = upload.fields || {};
1160
+ var filename = sanitizeFilename(upload.filename);
1161
+ var extension = extensionOf(filename);
1162
+ if (ALLOWED_EXTENSIONS.indexOf(extension) === -1) {
1163
+ return Promise.resolve(
1164
+ errorResponse("Unsupported file type. Upload TXT, MD, or DOCX.", 415)
1165
+ );
1166
+ }
1167
+ if (upload.bytes.length === 0) throw apiError("Uploaded file is empty.", 400);
1168
+
1169
+ return extractText(filename, upload.bytes, inflateRaw).then(function (text) {
1170
+ if (!text) throw apiError("No readable text was found in the document.", 400);
1171
+
1172
+ var documentId = uuidHex();
1173
+ var storedName = documentId + extension;
1174
+
1175
+ return Promise.resolve(store.putUpload(storedName, upload.bytes)).then(function () {
1176
+ var timestamp = now();
1177
+ var owner = ownerFromPayload({
1178
+ name: fields.owner_name || fields.owner,
1179
+ email: fields.owner_email,
1180
+ slack: fields.owner_slack,
1181
+ teams: fields.owner_teams
1182
+ });
1183
+ var record = {
1184
+ id: documentId,
1185
+ filename: filename,
1186
+ stored_name: storedName,
1187
+ extension: extension,
1188
+ status: "uploaded",
1189
+ created_at: timestamp,
1190
+ updated_at: timestamp,
1191
+ reviewed_at: null,
1192
+ approved_at: null,
1193
+ word_count: countWords(text),
1194
+ text: text,
1195
+ findings: [],
1196
+ comments: [],
1197
+ owner: owner,
1198
+ assignments: [],
1199
+ activity: []
1200
+ };
1201
+ addActivity(record, "uploaded", owner.name, "Uploaded " + filename + ".", timestamp);
1202
+
1203
+ return loadDb().then(function (data) {
1204
+ data.documents.push(record);
1205
+ return saveDb(data).then(function () {
1206
+ return jsonResponse(publicDocument(record, true), 201);
1207
+ });
1208
+ });
1209
+ });
1210
+ });
1211
+ }
1212
+
1213
+ /** app.py handle_review(). */
1214
+ function handleReview(documentId) {
1215
+ return loadDb().then(function (data) {
1216
+ var record = findDocument(data, documentId);
1217
+ if (!record) return notFound("Document not found.");
1218
+ var result = analyzeDocument(record.text || "", now);
1219
+ record.findings = result.findings;
1220
+ record.reviewed_at = result.reviewed_at;
1221
+ record.word_count = result.word_count;
1222
+ if (record.status !== "approved") record.status = "in_review";
1223
+ record.updated_at = now();
1224
+ addActivity(record, "review_run", "System", "Ran the local rubric review.", result.reviewed_at);
1225
+ return saveDb(data).then(function () {
1226
+ return jsonResponse(publicDocument(record, true));
1227
+ });
1228
+ });
1229
+ }
1230
+
1231
+ /** app.py handle_comment(). */
1232
+ function handleComment(documentId, body) {
1233
+ var payload = parseJsonBody(body);
1234
+ var text = cleanText(payload.body, "", 2000);
1235
+ var author = cleanText(payload.author, "Reviewer", 80);
1236
+ if (!text) throw apiError("Comment body is required.", 400);
1237
+
1238
+ return loadDb().then(function (data) {
1239
+ var record = findDocument(data, documentId);
1240
+ if (!record) return notFound("Document not found.");
1241
+
1242
+ var timestamp = now();
1243
+ if (!Array.isArray(record.comments)) record.comments = [];
1244
+ record.comments.push({
1245
+ id: uuidHex(),
1246
+ author: author,
1247
+ body: text,
1248
+ created_at: timestamp
1249
+ });
1250
+ record.updated_at = timestamp;
1251
+ addActivity(record, "comment_added", author, "Commented: " + text.slice(0, 120), timestamp);
1252
+ return saveDb(data).then(function () {
1253
+ return jsonResponse(publicDocument(record, true));
1254
+ });
1255
+ });
1256
+ }
1257
+
1258
+ /** app.py handle_status(). */
1259
+ function handleStatus(documentId, status) {
1260
+ return loadDb().then(function (data) {
1261
+ var record = findDocument(data, documentId);
1262
+ if (!record) return notFound("Document not found.");
1263
+
1264
+ var owner = isPlainObject(record.owner) ? record.owner : {};
1265
+ record.status = status;
1266
+ record.updated_at = now();
1267
+ if (status === "approved") {
1268
+ record.approved_at = now();
1269
+ addActivity(record, "approved", owner.name || "Owner", "Owner approved the document.");
1270
+ } else {
1271
+ record.approved_at = null;
1272
+ addActivity(record, "changes_requested", owner.name || "Owner", "Owner requested changes.");
1273
+ }
1274
+ return saveDb(data).then(function () {
1275
+ return jsonResponse(publicDocument(record, true));
1276
+ });
1277
+ });
1278
+ }
1279
+
1280
+ /** app.py handle_create_reviewer(). */
1281
+ function handleCreateReviewer(body) {
1282
+ var payload = parseJsonBody(body);
1283
+ var timestamp = now();
1284
+ var reviewer = reviewerPayload(payload, null);
1285
+ reviewer.id = uuidHex();
1286
+ reviewer.created_at = timestamp;
1287
+ reviewer.updated_at = timestamp;
1288
+ return loadDb().then(function (data) {
1289
+ data.reviewers.push(reviewer);
1290
+ return saveDb(data).then(function () {
1291
+ return jsonResponse(publicReviewer(reviewer), 201);
1292
+ });
1293
+ });
1294
+ }
1295
+
1296
+ /** app.py handle_update_reviewer(). */
1297
+ function handleUpdateReviewer(reviewerId, body) {
1298
+ return loadDb().then(function (data) {
1299
+ var reviewer = findReviewer(data, reviewerId);
1300
+ if (!reviewer) return notFound("Reviewer not found.");
1301
+ var updated = reviewerPayload(parseJsonBody(body), reviewer);
1302
+ Object.keys(updated).forEach(function (key) {
1303
+ reviewer[key] = updated[key];
1304
+ });
1305
+ reviewer.updated_at = now();
1306
+ return saveDb(data).then(function () {
1307
+ return jsonResponse(publicReviewer(reviewer));
1308
+ });
1309
+ });
1310
+ }
1311
+
1312
+ /** app.py handle_delete_reviewer(). */
1313
+ function handleDeleteReviewer(reviewerId) {
1314
+ return loadDb().then(function (data) {
1315
+ var before = data.reviewers.length;
1316
+ data.reviewers = data.reviewers.filter(function (reviewer) {
1317
+ return reviewer.id !== reviewerId;
1318
+ });
1319
+ if (data.reviewers.length === before) return notFound("Reviewer not found.");
1320
+ return saveDb(data).then(function () {
1321
+ return jsonResponse({ ok: true });
1322
+ });
1323
+ });
1324
+ }
1325
+
1326
+ /** app.py handle_assign_reviewers(). */
1327
+ function handleAssignReviewers(documentId, body) {
1328
+ var payload = parseJsonBody(body);
1329
+ var requested = payload.reviewer_ids === undefined ? [] : payload.reviewer_ids;
1330
+ if (!Array.isArray(requested)) throw apiError("reviewer_ids must be a list.", 400);
1331
+
1332
+ var reviewerIds = [];
1333
+ requested.forEach(function (item) {
1334
+ var id = pyStr(item);
1335
+ if (!id.trim()) return;
1336
+ if (reviewerIds.indexOf(id) === -1) reviewerIds.push(id);
1337
+ });
1338
+
1339
+ return loadDb().then(function (data) {
1340
+ var record = findDocument(data, documentId);
1341
+ if (!record) return notFound("Document not found.");
1342
+
1343
+ var reviewersById = {};
1344
+ data.reviewers.forEach(function (reviewer) {
1345
+ reviewersById[reviewer.id] = reviewer;
1346
+ });
1347
+ var missing = reviewerIds.filter(function (id) {
1348
+ return !hasOwn(reviewersById, id);
1349
+ });
1350
+ if (missing.length) {
1351
+ throw apiError("One or more selected reviewers no longer exists.", 400);
1352
+ }
1353
+
1354
+ var existingById = {};
1355
+ (record.assignments || []).forEach(function (assignment) {
1356
+ existingById[assignment.reviewer_id] = assignment;
1357
+ });
1358
+
1359
+ var assignments = [];
1360
+ var created = [];
1361
+ reviewerIds.forEach(function (id) {
1362
+ if (hasOwn(existingById, id)) {
1363
+ assignments.push(existingById[id]);
1364
+ } else {
1365
+ var assignment = buildAssignment(reviewersById[id]);
1366
+ assignments.push(assignment);
1367
+ created.push(assignment);
1368
+ }
1369
+ });
1370
+ record.assignments = assignments;
1371
+
1372
+ var timestamp = now();
1373
+ record.updated_at = timestamp;
1374
+ if (reviewerIds.length) {
1375
+ record.status = "in_review";
1376
+ var names = assignments.map(function (assignment) {
1377
+ return assignment.reviewer_name;
1378
+ }).join(", ");
1379
+ addActivity(record, "reviewers_assigned", record.owner.name, "Assigned reviewers: " + names + ".", timestamp);
1380
+ } else {
1381
+ record.status = record.reviewed_at ? "in_review" : "uploaded";
1382
+ record.approved_at = null;
1383
+ addActivity(record, "reviewers_assigned", record.owner.name, "Cleared reviewer assignments.", timestamp);
1384
+ }
1385
+
1386
+ created.forEach(function (assignment) {
1387
+ var message =
1388
+ "Please review " + record.filename + " in SimpleDocReview. " +
1389
+ "Open the local app, select the document, and respond as " + assignment.reviewer_name + ".";
1390
+ createNotification(
1391
+ data,
1392
+ record,
1393
+ "reviewer",
1394
+ assignment.reviewer_name,
1395
+ assignment.reviewer_contact,
1396
+ "review_assigned",
1397
+ message
1398
+ );
1399
+ });
1400
+
1401
+ recalculateDocumentStatus(record);
1402
+ return saveDb(data).then(function () {
1403
+ return jsonResponse(publicDocument(record, true));
1404
+ });
1405
+ });
1406
+ }
1407
+
1408
+ /**
1409
+ * app.py require_assignment().
1410
+ *
1411
+ * Note the status quirk this preserves: a missing document reaches the
1412
+ * client as a 400 here, not the 404 that GET /api/documents/<id> returns,
1413
+ * because upstream raises ValueError rather than replying directly.
1414
+ */
1415
+ function requireAssignment(documentId, payload) {
1416
+ var reviewerId = cleanText(payload.reviewer_id, "", 80);
1417
+ if (!reviewerId) throw apiError("Reviewer is required.", 400);
1418
+ return loadDb().then(function (data) {
1419
+ var record = findDocument(data, documentId);
1420
+ if (!record) throw apiError("Document not found.", 400);
1421
+ var assignment = findAssignment(record, reviewerId);
1422
+ if (!assignment) throw apiError("Reviewer is not assigned to this document.", 400);
1423
+ return { data: data, record: record, assignment: assignment };
1424
+ });
1425
+ }
1426
+
1427
+ /** app.py handle_reviewer_comment(). */
1428
+ function handleReviewerComment(documentId, body) {
1429
+ var payload = parseJsonBody(body);
1430
+ return requireAssignment(documentId, payload).then(function (context) {
1431
+ var data = context.data;
1432
+ var record = context.record;
1433
+ var assignment = context.assignment;
1434
+ var text = cleanText(payload.body, "", 2000);
1435
+ var signature = cleanText(payload.signature, assignment.reviewer_name, 120);
1436
+ if (!text) throw apiError("Comment body is required.", 400);
1437
+
1438
+ var timestamp = now();
1439
+ var comment = {
1440
+ id: uuidHex(),
1441
+ author: signature,
1442
+ reviewer_id: assignment.reviewer_id,
1443
+ body: text,
1444
+ created_at: timestamp
1445
+ };
1446
+ if (!Array.isArray(assignment.comments)) assignment.comments = [];
1447
+ assignment.comments.push(comment);
1448
+ if (assignment.status !== "approved" && assignment.status !== "changes_requested") {
1449
+ assignment.status = "commented";
1450
+ }
1451
+ assignment.updated_at = timestamp;
1452
+ migrateAssignment(assignment);
1453
+ if (!Array.isArray(record.comments)) record.comments = [];
1454
+ record.comments.push(comment);
1455
+ record.updated_at = timestamp;
1456
+ addActivity(record, "reviewer_comment", signature, "Commented: " + text.slice(0, 120), timestamp);
1457
+ createNotification(
1458
+ data,
1459
+ record,
1460
+ "owner",
1461
+ record.owner.name,
1462
+ record.owner,
1463
+ "reviewer_comment",
1464
+ signature + " commented on " + record.filename + ": " + text.slice(0, 180)
1465
+ );
1466
+ recalculateDocumentStatus(record);
1467
+ return saveDb(data).then(function () {
1468
+ return jsonResponse(publicDocument(record, true));
1469
+ });
1470
+ });
1471
+ }
1472
+
1473
+ /** app.py handle_reviewer_approve(). */
1474
+ function handleReviewerApprove(documentId, body) {
1475
+ var payload = parseJsonBody(body);
1476
+ return requireAssignment(documentId, payload).then(function (context) {
1477
+ var data = context.data;
1478
+ var record = context.record;
1479
+ var assignment = context.assignment;
1480
+ var signature = cleanText(payload.signature, "", 120);
1481
+ if (!signature) throw apiError("Approval name or initials are required.", 400);
1482
+
1483
+ var wasFinal = record.status === "approved";
1484
+ var timestamp = now();
1485
+ assignment.status = "approved";
1486
+ assignment.approval_name = signature;
1487
+ assignment.approval_initials = cleanText(payload.initials || signature, "", 24);
1488
+ assignment.approved_at = timestamp;
1489
+ assignment.updated_at = timestamp;
1490
+ migrateAssignment(assignment);
1491
+ record.updated_at = timestamp;
1492
+ addActivity(record, "reviewer_approved", signature, "Approved as " + signature + ".", timestamp);
1493
+ recalculateDocumentStatus(record);
1494
+ if (record.status === "approved" && !wasFinal) {
1495
+ addActivity(
1496
+ record,
1497
+ "approved",
1498
+ "System",
1499
+ "All assigned reviewers approved the document.",
1500
+ record.approved_at
1501
+ );
1502
+ }
1503
+ createNotification(
1504
+ data,
1505
+ record,
1506
+ "owner",
1507
+ record.owner.name,
1508
+ record.owner,
1509
+ "reviewer_approved",
1510
+ signature + " approved " + record.filename + "."
1511
+ );
1512
+ return saveDb(data).then(function () {
1513
+ return jsonResponse(publicDocument(record, true));
1514
+ });
1515
+ });
1516
+ }
1517
+
1518
+ /** app.py handle_reviewer_request_changes(). */
1519
+ function handleReviewerRequestChanges(documentId, body) {
1520
+ var payload = parseJsonBody(body);
1521
+ return requireAssignment(documentId, payload).then(function (context) {
1522
+ var data = context.data;
1523
+ var record = context.record;
1524
+ var assignment = context.assignment;
1525
+ var text = cleanText(payload.body, "", 2000);
1526
+ var signature = cleanText(payload.signature, assignment.reviewer_name, 120);
1527
+ if (!text) throw apiError("A change request note is required.", 400);
1528
+
1529
+ var timestamp = now();
1530
+ assignment.status = "changes_requested";
1531
+ assignment.approved_at = null;
1532
+ assignment.approval_name = "";
1533
+ assignment.approval_initials = "";
1534
+ assignment.updated_at = timestamp;
1535
+ var comment = {
1536
+ id: uuidHex(),
1537
+ author: signature,
1538
+ reviewer_id: assignment.reviewer_id,
1539
+ body: text,
1540
+ created_at: timestamp
1541
+ };
1542
+ if (!Array.isArray(assignment.comments)) assignment.comments = [];
1543
+ assignment.comments.push(comment);
1544
+ migrateAssignment(assignment);
1545
+ if (!Array.isArray(record.comments)) record.comments = [];
1546
+ record.comments.push(comment);
1547
+ record.updated_at = timestamp;
1548
+ recalculateDocumentStatus(record);
1549
+ addActivity(
1550
+ record,
1551
+ "reviewer_changes_requested",
1552
+ signature,
1553
+ "Requested changes: " + text.slice(0, 120),
1554
+ timestamp
1555
+ );
1556
+ createNotification(
1557
+ data,
1558
+ record,
1559
+ "owner",
1560
+ record.owner.name,
1561
+ record.owner,
1562
+ "reviewer_changes_requested",
1563
+ signature + " requested changes on " + record.filename + ": " + text.slice(0, 180)
1564
+ );
1565
+ return saveDb(data).then(function () {
1566
+ return jsonResponse(publicDocument(record, true));
1567
+ });
1568
+ });
1569
+ }
1570
+
1571
+ /** app.py handle_notification_read(). */
1572
+ function handleNotificationRead(notificationId) {
1573
+ return loadDb().then(function (data) {
1574
+ var notification = data.notifications.filter(function (item) {
1575
+ return item.id === notificationId;
1576
+ })[0];
1577
+ if (!notification) return notFound("Notification not found.");
1578
+ notification.read_at = notification.read_at || now();
1579
+ return saveDb(data).then(function () {
1580
+ return jsonResponse(publicNotification(notification));
1581
+ });
1582
+ });
1583
+ }
1584
+
1585
+ // ----------------------------------------------------------------- router
1586
+ // Mirrors app.py's do_GET / do_POST / do_PUT / do_DELETE dispatch, in the
1587
+ // same order, so an unmatched path produces the same 404 body.
1588
+
1589
+ function pathParts(pathname) {
1590
+ return String(pathname)
1591
+ .split("?")[0]
1592
+ .split("#")[0]
1593
+ .split("/")
1594
+ .filter(function (part) { return part.length > 0; })
1595
+ .map(function (part) { return decodeURIComponent(part); });
1596
+ }
1597
+
1598
+ function route(method, pathname, body) {
1599
+ var parts = pathParts(pathname);
1600
+ var verb = String(method || "GET").toUpperCase();
1601
+
1602
+ if (verb === "GET") {
1603
+ if (parts.length === 2 && parts[0] === "api") {
1604
+ if (parts[1] === "documents") return handleDocumentsIndex();
1605
+ if (parts[1] === "reviewers") return handleReviewersIndex();
1606
+ if (parts[1] === "notifications") return handleNotificationsIndex();
1607
+ }
1608
+ if (parts.length === 3 && parts[0] === "api" && parts[1] === "documents") {
1609
+ return handleDocumentDetail(parts[2]);
1610
+ }
1611
+ if (parts.length === 4 && parts[0] === "api" && parts[1] === "documents" && parts[3] === "download") {
1612
+ return handleDownload(parts[2]);
1613
+ }
1614
+ return Promise.resolve(notFound());
1615
+ }
1616
+
1617
+ if (verb === "POST") {
1618
+ if (parts.length === 2 && parts[0] === "api" && parts[1] === "upload") {
1619
+ return handleUpload(body);
1620
+ }
1621
+ if (parts.length === 2 && parts[0] === "api" && parts[1] === "reviewers") {
1622
+ return handleCreateReviewer(body);
1623
+ }
1624
+ if (parts.length === 4 && parts[0] === "api" && parts[1] === "notifications" && parts[3] === "read") {
1625
+ return handleNotificationRead(parts[2]);
1626
+ }
1627
+ if (parts.length === 4 && parts[0] === "api" && parts[1] === "documents") {
1628
+ var documentId = parts[2];
1629
+ var action = parts[3];
1630
+ if (action === "review") return handleReview(documentId);
1631
+ if (action === "comments") return handleComment(documentId, body);
1632
+ if (action === "approve") return handleStatus(documentId, "approved");
1633
+ if (action === "request-changes") return handleStatus(documentId, "changes_requested");
1634
+ if (action === "assign-reviewers") return handleAssignReviewers(documentId, body);
1635
+ if (action === "reviewer-comment") return handleReviewerComment(documentId, body);
1636
+ if (action === "reviewer-approve") return handleReviewerApprove(documentId, body);
1637
+ if (action === "reviewer-request-changes") return handleReviewerRequestChanges(documentId, body);
1638
+ }
1639
+ return Promise.resolve(notFound());
1640
+ }
1641
+
1642
+ if (verb === "PUT") {
1643
+ if (parts.length === 3 && parts[0] === "api" && parts[1] === "reviewers") {
1644
+ return handleUpdateReviewer(parts[2], body);
1645
+ }
1646
+ return Promise.resolve(notFound());
1647
+ }
1648
+
1649
+ if (verb === "DELETE") {
1650
+ if (parts.length === 3 && parts[0] === "api" && parts[1] === "reviewers") {
1651
+ return handleDeleteReviewer(parts[2]);
1652
+ }
1653
+ return Promise.resolve(notFound());
1654
+ }
1655
+
1656
+ return Promise.resolve(notFound());
1657
+ }
1658
+
1659
+ // One request at a time. app.py serializes on the file it rewrites; here
1660
+ // every handler is a read-modify-write against the same store, and the app
1661
+ // fires three GETs in parallel on load, so interleaving them would let one
1662
+ // response overwrite another's changes.
1663
+ var queue = Promise.resolve();
1664
+
1665
+ function handle(method, pathname, body) {
1666
+ var result = queue.then(function () {
1667
+ return Promise.resolve()
1668
+ .then(function () {
1669
+ return route(method, pathname, body);
1670
+ })
1671
+ .catch(function (error) {
1672
+ if (error && error.apiStatus) {
1673
+ return errorResponse(error.message, error.apiStatus);
1674
+ }
1675
+ throw error;
1676
+ });
1677
+ });
1678
+ // Keep the chain alive even when a request rejects, and never let a
1679
+ // rejection here surface as an unhandled promise.
1680
+ queue = result.then(function () { return undefined; }, function () { return undefined; });
1681
+ return result;
1682
+ }
1683
+
1684
+ return {
1685
+ handle: handle,
1686
+ isApiPath: function (pathname) {
1687
+ var parts = pathParts(pathname);
1688
+ return parts[0] === "api";
1689
+ },
1690
+ // Exposed for the parity tests and for debugging in the browser console.
1691
+ internals: {
1692
+ analyzeDocument: function (text) { return analyzeDocument(text, now); },
1693
+ extractText: function (filename, bytes) { return extractText(filename, bytes, inflateRaw); },
1694
+ sanitizeFilename: sanitizeFilename,
1695
+ decodeTextBytes: decodeTextBytes,
1696
+ cleanText: cleanText,
1697
+ countWords: countWords,
1698
+ publicDocument: publicDocument,
1699
+ loadDb: loadDb
1700
+ }
1701
+ };
1702
+ }
1703
+
1704
+ return {
1705
+ createApi: createApi,
1706
+ MAX_UPLOAD_BYTES: MAX_UPLOAD_BYTES,
1707
+ ALLOWED_EXTENSIONS: ALLOWED_EXTENSIONS,
1708
+ STATUS_LABELS: STATUS_LABELS,
1709
+ ASSIGNMENT_LABELS: ASSIGNMENT_LABELS,
1710
+ defaultNow: defaultNow,
1711
+ defaultUuidHex: defaultUuidHex,
1712
+ defaultInflateRaw: defaultInflateRaw,
1713
+ sanitizeFilename: sanitizeFilename,
1714
+ decodeTextBytes: decodeTextBytes,
1715
+ cleanText: cleanText
1716
+ };
1717
+ });
sdr-api-shim.js ADDED
@@ -0,0 +1,689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * sdr-api-shim.js - wires sdr-api-core.js into the page in place of app.py.
3
+ *
4
+ * A Static Space serves files and nothing else, so the `http://127.0.0.1:4173`
5
+ * server upstream's `static/app.js` talks to does not exist. This file answers
6
+ * those requests in the browser:
7
+ *
8
+ * 1. an IndexedDB store standing in for data/reviews.json and uploads/,
9
+ * 2. an XMLHttpRequest (and fetch) interceptor for every /api/ path,
10
+ * 3. a click interceptor for the Download button, which upstream implements
11
+ * as a navigation rather than a request,
12
+ * 4. a one-line notice, because on a public URL "your documents stay in this
13
+ * browser" is not what a visitor would assume.
14
+ *
15
+ * Nothing here reimplements review logic - that all lives in sdr-api-core.js.
16
+ * This file is only the environment.
17
+ *
18
+ * Loaded by a <script> tag that scripts/build-static.ps1 inserts ahead of
19
+ * upstream's static/app.js. Upstream's files are never edited.
20
+ */
21
+ (function () {
22
+ "use strict";
23
+
24
+ if (typeof window === "undefined" || window.__sdrApiShimInstalled) return;
25
+ window.__sdrApiShimInstalled = true;
26
+
27
+ var Core = window.SdrApiCore;
28
+ if (!Core) {
29
+ console.error("[SimpleDocReview] sdr-api-core.js did not load; the app cannot run.");
30
+ return;
31
+ }
32
+
33
+ var DB_NAME = "simpledocreview";
34
+ var DB_VERSION = 1;
35
+ var RECORD_STORE = "records";
36
+ var UPLOAD_STORE = "uploads";
37
+ var RECORD_KEY = "db";
38
+
39
+ // ------------------------------------------------------------------- store
40
+
41
+ function openDatabase() {
42
+ return new Promise(function (resolve, reject) {
43
+ if (!window.indexedDB) {
44
+ reject(new Error("IndexedDB is unavailable."));
45
+ return;
46
+ }
47
+ var request = window.indexedDB.open(DB_NAME, DB_VERSION);
48
+ request.onupgradeneeded = function () {
49
+ var database = request.result;
50
+ if (!database.objectStoreNames.contains(RECORD_STORE)) {
51
+ database.createObjectStore(RECORD_STORE);
52
+ }
53
+ if (!database.objectStoreNames.contains(UPLOAD_STORE)) {
54
+ database.createObjectStore(UPLOAD_STORE);
55
+ }
56
+ };
57
+ request.onsuccess = function () { resolve(request.result); };
58
+ request.onerror = function () { reject(request.error || new Error("IndexedDB open failed.")); };
59
+ request.onblocked = function () { reject(new Error("IndexedDB is blocked by another tab.")); };
60
+ });
61
+ }
62
+
63
+ function transact(storeName, mode, work) {
64
+ return openDatabase().then(function (database) {
65
+ return new Promise(function (resolve, reject) {
66
+ var transaction = database.transaction(storeName, mode);
67
+ var request = work(transaction.objectStore(storeName));
68
+ transaction.oncomplete = function () {
69
+ database.close();
70
+ resolve(request ? request.result : undefined);
71
+ };
72
+ transaction.onerror = function () {
73
+ database.close();
74
+ reject(transaction.error || new Error("IndexedDB transaction failed."));
75
+ };
76
+ transaction.onabort = function () {
77
+ database.close();
78
+ reject(transaction.error || new Error("IndexedDB transaction aborted."));
79
+ };
80
+ });
81
+ });
82
+ }
83
+
84
+ var indexedDbStore = {
85
+ load: function () {
86
+ return transact(RECORD_STORE, "readonly", function (store) {
87
+ return store.get(RECORD_KEY);
88
+ }).then(function (value) {
89
+ return value || null;
90
+ });
91
+ },
92
+ save: function (data) {
93
+ return transact(RECORD_STORE, "readwrite", function (store) {
94
+ return store.put(data, RECORD_KEY);
95
+ });
96
+ },
97
+ putUpload: function (name, bytes) {
98
+ return transact(UPLOAD_STORE, "readwrite", function (store) {
99
+ return store.put(bytes, name);
100
+ });
101
+ },
102
+ getUpload: function (name) {
103
+ if (!name) return Promise.resolve(null);
104
+ return transact(UPLOAD_STORE, "readonly", function (store) {
105
+ return store.get(name);
106
+ }).then(function (value) {
107
+ if (!value) return null;
108
+ return value instanceof Uint8Array ? value : new Uint8Array(value);
109
+ });
110
+ },
111
+ clear: function () {
112
+ return transact(RECORD_STORE, "readwrite", function (store) {
113
+ return store.clear();
114
+ }).then(function () {
115
+ return transact(UPLOAD_STORE, "readwrite", function (store) {
116
+ return store.clear();
117
+ });
118
+ });
119
+ }
120
+ };
121
+
122
+ /**
123
+ * Fallback for browsers that refuse storage.
124
+ *
125
+ * The Space renders inside an iframe on huggingface.co, and some browsers
126
+ * partition or block storage for embedded third-party origins. Losing
127
+ * persistence is better than a dead page, so the app still works for the
128
+ * length of the visit and the notice says so.
129
+ */
130
+ function createMemoryStore() {
131
+ var records = null;
132
+ var uploads = {};
133
+ return {
134
+ volatile: true,
135
+ load: function () { return Promise.resolve(records); },
136
+ save: function (data) { records = data; return Promise.resolve(); },
137
+ putUpload: function (name, bytes) { uploads[name] = bytes; return Promise.resolve(); },
138
+ getUpload: function (name) { return Promise.resolve(uploads[name] || null); },
139
+ clear: function () { records = null; uploads = {}; return Promise.resolve(); }
140
+ };
141
+ }
142
+
143
+ /**
144
+ * Probe storage once, then keep using whichever backend answered.
145
+ *
146
+ * The probe result is cached rather than retried per request, so a page that
147
+ * starts in memory stays consistent instead of writing half its records to
148
+ * one backend and half to the other.
149
+ */
150
+ var activeStore = null;
151
+ var storeProbe = null;
152
+
153
+ function resolveStore() {
154
+ if (activeStore) return Promise.resolve(activeStore);
155
+ if (!storeProbe) {
156
+ storeProbe = indexedDbStore
157
+ .load()
158
+ .then(function () {
159
+ activeStore = indexedDbStore;
160
+ return activeStore;
161
+ })
162
+ .catch(function (error) {
163
+ console.warn(
164
+ "[SimpleDocReview] IndexedDB unavailable (" + error.message + "); " +
165
+ "documents will be kept in memory for this visit only."
166
+ );
167
+ activeStore = createMemoryStore();
168
+ return activeStore;
169
+ });
170
+ }
171
+ return storeProbe;
172
+ }
173
+
174
+ var store = {
175
+ load: function () { return resolveStore().then(function (s) { return s.load(); }); },
176
+ save: function (data) { return resolveStore().then(function (s) { return s.save(data); }); },
177
+ putUpload: function (n, b) { return resolveStore().then(function (s) { return s.putUpload(n, b); }); },
178
+ getUpload: function (n) { return resolveStore().then(function (s) { return s.getUpload(n); }); },
179
+ clear: function () { return resolveStore().then(function (s) { return s.clear(); }); }
180
+ };
181
+
182
+ var api = Core.createApi({ store: store });
183
+
184
+ // ------------------------------------------------------------ request body
185
+
186
+ function apiError(message, status) {
187
+ var error = new Error(message);
188
+ error.apiStatus = status || 400;
189
+ return error;
190
+ }
191
+
192
+ /**
193
+ * Turn an XHR/fetch body into what the core API expects.
194
+ *
195
+ * Upload is the only interesting case: upstream posts multipart/form-data,
196
+ * which app.py parses back apart. Here the FormData object is already
197
+ * structured, so the parse step is just reading the parts out - the file as
198
+ * bytes, everything else as a text field.
199
+ */
200
+ function normalizeBody(body) {
201
+ if (body === null || body === undefined) return Promise.resolve(null);
202
+ if (typeof body === "string") return Promise.resolve(body);
203
+
204
+ if (typeof FormData !== "undefined" && body instanceof FormData) {
205
+ var file = body.get("file");
206
+ if (!file || typeof file === "string") {
207
+ return Promise.reject(apiError("No file part was found in the upload.", 400));
208
+ }
209
+ var fields = {};
210
+ body.forEach(function (value, key) {
211
+ if (typeof value === "string") fields[key] = value.trim();
212
+ });
213
+ return file.arrayBuffer().then(function (buffer) {
214
+ return {
215
+ filename: file.name,
216
+ bytes: new Uint8Array(buffer),
217
+ fields: fields
218
+ };
219
+ });
220
+ }
221
+
222
+ if (typeof Blob !== "undefined" && body instanceof Blob) return body.text();
223
+ if (body instanceof ArrayBuffer) return Promise.resolve(new TextDecoder().decode(body));
224
+ if (body && body.buffer instanceof ArrayBuffer) {
225
+ return Promise.resolve(new TextDecoder().decode(body));
226
+ }
227
+ return Promise.resolve(String(body));
228
+ }
229
+
230
+ function toPathname(url) {
231
+ try {
232
+ return new URL(String(url), window.location.href).pathname;
233
+ } catch (error) {
234
+ return String(url);
235
+ }
236
+ }
237
+
238
+ function isApiUrl(url) {
239
+ return api.isApiPath(toPathname(url));
240
+ }
241
+
242
+ // ----------------------------------------------------- selected document id
243
+
244
+ /**
245
+ * The id of the document currently on screen.
246
+ *
247
+ * Upstream's Download button navigates to /api/documents/<id>/download rather
248
+ * than requesting it, and a page cannot cancel an assignment to
249
+ * window.location.href. The click is intercepted instead (see below), which
250
+ * means the id has to come from somewhere other than the event.
251
+ *
252
+ * Every render of the document panel is driven by a response for that
253
+ * document - selectDocument() and refreshSelected() both fetch it by id, and
254
+ * the reviewer actions post to it - so the last /api/documents/<id> path to
255
+ * pass through here names what the panel is showing.
256
+ */
257
+ var lastDocumentId = null;
258
+
259
+ function rememberDocumentId(pathname) {
260
+ var match = /^\/api\/documents\/([^/]+)/.exec(pathname);
261
+ if (match && match[1] !== "download") lastDocumentId = decodeURIComponent(match[1]);
262
+ }
263
+
264
+ function dispatchToCore(method, url, body) {
265
+ var pathname = toPathname(url);
266
+ rememberDocumentId(pathname);
267
+ return normalizeBody(body).then(function (payload) {
268
+ return api.handle(method, pathname, payload);
269
+ });
270
+ }
271
+
272
+ // ------------------------------------------------- XMLHttpRequest override
273
+
274
+ var RealXMLHttpRequest = window.XMLHttpRequest;
275
+
276
+ var SIMULATED_PROPERTIES = {
277
+ readyState: true,
278
+ status: true,
279
+ statusText: true,
280
+ response: true,
281
+ responseText: true,
282
+ responseURL: true
283
+ };
284
+
285
+ var HANDLER_PROPERTIES = {
286
+ onreadystatechange: true,
287
+ onload: true,
288
+ onloadstart: true,
289
+ onloadend: true,
290
+ onerror: true,
291
+ onabort: true,
292
+ ontimeout: true,
293
+ onprogress: true
294
+ };
295
+
296
+ /**
297
+ * An XMLHttpRequest that answers /api/ locally and forwards everything else.
298
+ *
299
+ * A Proxy over a real XMLHttpRequest rather than a hand-written stand-in: any
300
+ * member this shim does not simulate still reaches the genuine object, so a
301
+ * future upstream change that uses more of the XHR surface keeps working
302
+ * instead of hitting a gap in a fake.
303
+ */
304
+ function createInterceptingXhr() {
305
+ var real = new RealXMLHttpRequest();
306
+ var state = {
307
+ intercepted: false,
308
+ method: "GET",
309
+ url: "",
310
+ overrides: {},
311
+ handlers: {},
312
+ listeners: {},
313
+ sent: false
314
+ };
315
+ var proxy;
316
+
317
+ function dispatch(type) {
318
+ var event = {
319
+ type: type,
320
+ target: proxy,
321
+ currentTarget: proxy,
322
+ lengthComputable: false,
323
+ loaded: 0,
324
+ total: 0
325
+ };
326
+ var handler = state.handlers["on" + type];
327
+ if (typeof handler === "function") handler.call(proxy, event);
328
+ (state.listeners[type] || []).forEach(function (listener) {
329
+ if (typeof listener === "function") listener.call(proxy, event);
330
+ else if (listener && typeof listener.handleEvent === "function") listener.handleEvent(event);
331
+ });
332
+ }
333
+
334
+ function settle(response) {
335
+ state.overrides.readyState = 4;
336
+ state.overrides.status = response.status;
337
+ state.overrides.statusText = response.status === 200 ? "OK" : "";
338
+ state.overrides.responseURL = new URL(state.url, window.location.href).href;
339
+ // A download reply carries bytes, not text. Upstream never reads one
340
+ // through XHR (it navigates instead), so the body is left empty rather
341
+ // than lossily decoded.
342
+ state.overrides.responseText = response.body || "";
343
+ state.overrides.response = response.body || "";
344
+ state.overrides.__headers = response.headers || {};
345
+ state.overrides.__bytes = response.bytes || null;
346
+ dispatch("readystatechange");
347
+ dispatch("load");
348
+ dispatch("loadend");
349
+ }
350
+
351
+ function failed(error) {
352
+ if (error && error.apiStatus) {
353
+ settle({
354
+ status: error.apiStatus,
355
+ headers: { "Content-Type": "application/json; charset=utf-8" },
356
+ body: JSON.stringify({ error: error.message })
357
+ });
358
+ return;
359
+ }
360
+ console.error("[SimpleDocReview] local API failed:", error);
361
+ state.overrides.readyState = 4;
362
+ state.overrides.status = 0;
363
+ state.overrides.responseText = "";
364
+ state.overrides.response = "";
365
+ dispatch("readystatechange");
366
+ dispatch("error");
367
+ dispatch("loadend");
368
+ }
369
+
370
+ var members = {
371
+ open: function (method, url) {
372
+ state.method = String(method || "GET");
373
+ state.url = String(url);
374
+ state.intercepted = isApiUrl(state.url);
375
+ state.overrides = {};
376
+ state.sent = false;
377
+ if (state.intercepted) {
378
+ state.overrides.readyState = 1;
379
+ dispatch("readystatechange");
380
+ return undefined;
381
+ }
382
+ return real.open.apply(real, arguments);
383
+ },
384
+
385
+ send: function (body) {
386
+ if (!state.intercepted) return real.send.apply(real, arguments);
387
+ if (state.sent) throw new Error("InvalidStateError: send() already called.");
388
+ state.sent = true;
389
+ dispatch("loadstart");
390
+ dispatchToCore(state.method, state.url, body).then(settle, failed);
391
+ return undefined;
392
+ },
393
+
394
+ setRequestHeader: function () {
395
+ if (state.intercepted) return undefined;
396
+ return real.setRequestHeader.apply(real, arguments);
397
+ },
398
+
399
+ getResponseHeader: function (name) {
400
+ if (!state.intercepted) return real.getResponseHeader.apply(real, arguments);
401
+ var headers = state.overrides.__headers || {};
402
+ var wanted = String(name).toLowerCase();
403
+ var found = Object.keys(headers).filter(function (key) {
404
+ return key.toLowerCase() === wanted;
405
+ })[0];
406
+ return found ? headers[found] : null;
407
+ },
408
+
409
+ getAllResponseHeaders: function () {
410
+ if (!state.intercepted) return real.getAllResponseHeaders.apply(real, arguments);
411
+ var headers = state.overrides.__headers || {};
412
+ return Object.keys(headers)
413
+ .map(function (key) { return key.toLowerCase() + ": " + headers[key] + "\r\n"; })
414
+ .join("");
415
+ },
416
+
417
+ abort: function () {
418
+ if (!state.intercepted) return real.abort.apply(real, arguments);
419
+ // The work is already running locally and has nothing to cancel; report
420
+ // the aborted state so callers waiting on it are not left hanging.
421
+ state.overrides.readyState = 4;
422
+ state.overrides.status = 0;
423
+ dispatch("readystatechange");
424
+ dispatch("abort");
425
+ dispatch("loadend");
426
+ return undefined;
427
+ },
428
+
429
+ addEventListener: function (type, listener) {
430
+ if (!state.listeners[type]) state.listeners[type] = [];
431
+ state.listeners[type].push(listener);
432
+ return real.addEventListener.apply(real, arguments);
433
+ },
434
+
435
+ removeEventListener: function (type, listener) {
436
+ state.listeners[type] = (state.listeners[type] || []).filter(function (item) {
437
+ return item !== listener;
438
+ });
439
+ return real.removeEventListener.apply(real, arguments);
440
+ }
441
+ };
442
+
443
+ proxy = new Proxy(real, {
444
+ get: function (target, property) {
445
+ if (Object.prototype.hasOwnProperty.call(members, property)) return members[property];
446
+ if (Object.prototype.hasOwnProperty.call(HANDLER_PROPERTIES, property)) {
447
+ return state.handlers[property] === undefined ? null : state.handlers[property];
448
+ }
449
+ if (state.intercepted && Object.prototype.hasOwnProperty.call(SIMULATED_PROPERTIES, property)) {
450
+ var override = state.overrides[property];
451
+ if (override !== undefined) return override;
452
+ if (property === "readyState" || property === "status") return 0;
453
+ return "";
454
+ }
455
+ var value = target[property];
456
+ return typeof value === "function" ? value.bind(target) : value;
457
+ },
458
+ set: function (target, property, value) {
459
+ if (Object.prototype.hasOwnProperty.call(HANDLER_PROPERTIES, property)) {
460
+ state.handlers[property] = value;
461
+ return true;
462
+ }
463
+ target[property] = value;
464
+ return true;
465
+ }
466
+ });
467
+
468
+ return proxy;
469
+ }
470
+
471
+ function ShimXMLHttpRequest() {
472
+ return createInterceptingXhr();
473
+ }
474
+ ShimXMLHttpRequest.prototype = RealXMLHttpRequest.prototype;
475
+ ["UNSENT", "OPENED", "HEADERS_RECEIVED", "LOADING", "DONE"].forEach(function (name) {
476
+ ShimXMLHttpRequest[name] = RealXMLHttpRequest[name];
477
+ });
478
+ window.XMLHttpRequest = ShimXMLHttpRequest;
479
+
480
+ // ------------------------------------------------------------ fetch override
481
+
482
+ // Upstream uses XHR throughout. This covers /api/ requests made with fetch so
483
+ // that a future upstream rewrite does not silently start 404ing.
484
+ if (typeof window.fetch === "function") {
485
+ var realFetch = window.fetch.bind(window);
486
+ window.fetch = function (input, init) {
487
+ var url = typeof input === "string"
488
+ ? input
489
+ : input instanceof URL ? input.toString() : input && input.url;
490
+
491
+ if (!url || !isApiUrl(url)) return realFetch(input, init);
492
+
493
+ var method = ((init && init.method) || (input && input.method) || "GET").toUpperCase();
494
+ var body = init ? init.body : null;
495
+
496
+ return dispatchToCore(method, url, body).then(function (response) {
497
+ var payload = response.bytes ? response.bytes : response.body;
498
+ return new Response(payload, { status: response.status, headers: response.headers });
499
+ }, function (error) {
500
+ if (error && error.apiStatus) {
501
+ return new Response(JSON.stringify({ error: error.message }), {
502
+ status: error.apiStatus,
503
+ headers: { "Content-Type": "application/json; charset=utf-8" }
504
+ });
505
+ }
506
+ throw error;
507
+ });
508
+ };
509
+ }
510
+
511
+ // --------------------------------------------------------------- downloads
512
+
513
+ /**
514
+ * Serve the Download button from IndexedDB.
515
+ *
516
+ * upstream: els.downloadButton.onclick = () => {
517
+ * window.location.href = `/api/documents/${document.id}/download`;
518
+ * }
519
+ *
520
+ * A navigation cannot be intercepted, so the click is caught in the capture
521
+ * phase at the document level - before the target phase, which is what stops
522
+ * upstream's own handler from running - and the file is handed over as a blob
523
+ * URL instead.
524
+ */
525
+ document.addEventListener(
526
+ "click",
527
+ function (event) {
528
+ var target = event.target;
529
+ if (!target || typeof target.closest !== "function") return;
530
+ if (!target.closest("#downloadButton")) return;
531
+
532
+ event.preventDefault();
533
+ event.stopPropagation();
534
+ if (typeof event.stopImmediatePropagation === "function") event.stopImmediatePropagation();
535
+
536
+ if (!lastDocumentId) {
537
+ console.warn("[SimpleDocReview] No document is selected, so there is nothing to download.");
538
+ return;
539
+ }
540
+
541
+ api.handle("GET", "/api/documents/" + encodeURIComponent(lastDocumentId) + "/download", null)
542
+ .then(function (response) {
543
+ if (response.status !== 200 || !response.bytes) {
544
+ var message = "The original upload could not be found.";
545
+ try {
546
+ message = JSON.parse(response.body).error || message;
547
+ } catch (error) { /* keep the default */ }
548
+ console.warn("[SimpleDocReview] " + message);
549
+ return;
550
+ }
551
+ var blob = new Blob([response.bytes], {
552
+ type: response.headers["Content-Type"] || "application/octet-stream"
553
+ });
554
+ var url = URL.createObjectURL(blob);
555
+ var link = document.createElement("a");
556
+ link.href = url;
557
+ link.download = response.filename || "document";
558
+ link.rel = "noopener";
559
+ document.body.appendChild(link);
560
+ link.click();
561
+ document.body.removeChild(link);
562
+ // Revoke on a later turn: Firefox cancels an in-flight download if the
563
+ // object URL disappears in the same task as the click.
564
+ setTimeout(function () { URL.revokeObjectURL(url); }, 30000);
565
+ })
566
+ .catch(function (error) {
567
+ console.error("[SimpleDocReview] Download failed:", error);
568
+ });
569
+ },
570
+ true
571
+ );
572
+
573
+ // ------------------------------------------------------------------ notice
574
+
575
+ var UPSTREAM_URL = "https://github.com/eputnam77/SimpleDocReview";
576
+
577
+ /**
578
+ * Say what this is.
579
+ *
580
+ * Upstream's README can leave storage unexplained, because you started the
581
+ * server yourself and the files are on your disk. A public URL cannot: a
582
+ * visitor's default assumption is a shared service that keeps their records,
583
+ * and this deployment keeps nothing. Somebody who ran a real approval round
584
+ * here and then cleared their browser would lose it with no warning.
585
+ *
586
+ * So the page says so twice: a badge that never goes away, and one notice
587
+ * explaining where the data lives. Both are injected rather than edited into
588
+ * upstream's markup, and both are styled inline so they do not depend on
589
+ * upstream's stylesheet.
590
+ */
591
+ function addDemoBadge() {
592
+ var heading = document.querySelector(".brand h1");
593
+ if (!heading || heading.querySelector(".sdr-demo-badge")) return;
594
+
595
+ var badge = document.createElement("span");
596
+ badge.className = "sdr-demo-badge";
597
+ badge.textContent = "Demo";
598
+ badge.title = "Runs entirely in your browser. Records are not stored on a server.";
599
+ // Upstream's palette tokens, so the badge retints with the app rather than
600
+ // sitting on it in a colour of its own.
601
+ badge.style.cssText = [
602
+ "margin-left:8px", "vertical-align:middle", "white-space:nowrap",
603
+ "padding:2px 6px", "border-radius:5px",
604
+ "border:1px solid var(--line, #d9e1e4)",
605
+ "color:var(--muted, #64737c)",
606
+ "font-size:.6em", "font-weight:700",
607
+ "letter-spacing:.08em", "text-transform:uppercase"
608
+ ].join(";");
609
+ heading.appendChild(badge);
610
+
611
+ var dot = document.querySelector(".brand .live-dot");
612
+ if (dot) dot.title = "Demo build - no server";
613
+ }
614
+
615
+ function showStorageNotice() {
616
+ if (window.sessionStorage && window.sessionStorage.getItem("sdrNoticeDismissed")) return;
617
+
618
+ // Borrowed from upstream's own .toast rule so the notice reads as part of
619
+ // the app: same ink, same radius, same shadow, same right margin. It sits
620
+ // one toast-height higher so an actual toast still has its usual corner.
621
+ var bar = document.createElement("aside");
622
+ bar.setAttribute("role", "note");
623
+ bar.style.cssText = [
624
+ "position:fixed", "right:22px", "bottom:84px", "z-index:60",
625
+ "max-width:min(460px, calc(100vw - 44px))",
626
+ "display:flex", "gap:12px", "align-items:flex-start",
627
+ "padding:12px 14px", "border-radius:8px",
628
+ "background:#172126", "color:#fff",
629
+ "box-shadow:0 18px 45px rgba(23, 33, 38, 0.28)",
630
+ "font-size:13px", "line-height:1.5"
631
+ ].join(";");
632
+
633
+ var text = document.createElement("p");
634
+ text.style.cssText = "margin:0";
635
+ text.innerHTML =
636
+ "<strong>Demo, not a review system.</strong> " +
637
+ (activeStore && activeStore.volatile
638
+ ? "This browser blocks storage for embedded pages, so anything you add lasts only until you close the tab. "
639
+ : "Documents and review records live only in this browser, and clearing site data deletes them. ") +
640
+ 'Nothing is sent to a server. For real reviews, <a href="' + UPSTREAM_URL +
641
+ '" target="_blank" rel="noopener" style="color:inherit;text-decoration:underline">run it locally</a>.';
642
+
643
+ var dismiss = document.createElement("button");
644
+ dismiss.type = "button";
645
+ dismiss.textContent = "Got it";
646
+ dismiss.style.cssText = [
647
+ "flex:0 0 auto", "cursor:pointer", "border-radius:6px", "border:0",
648
+ "background:rgba(255,255,255,0.14)", "color:inherit",
649
+ "padding:5px 10px", "font-size:inherit", "font-weight:600"
650
+ ].join(";");
651
+ dismiss.addEventListener("click", function () {
652
+ bar.remove();
653
+ if (window.sessionStorage) window.sessionStorage.setItem("sdrNoticeDismissed", "1");
654
+ });
655
+
656
+ bar.appendChild(text);
657
+ bar.appendChild(dismiss);
658
+ document.body.appendChild(bar);
659
+ }
660
+
661
+ // Wait for the store probe so the notice can tell the truth about persistence.
662
+ function whenReady(callback) {
663
+ if (document.readyState === "loading") {
664
+ document.addEventListener("DOMContentLoaded", callback, { once: true });
665
+ } else {
666
+ callback();
667
+ }
668
+ }
669
+ whenReady(function () {
670
+ addDemoBadge();
671
+ resolveStore().then(showStorageNotice, showStorageNotice);
672
+ });
673
+
674
+ // ------------------------------------------------------------------ console
675
+
676
+ /**
677
+ * Debug surface. `__sdrStaticApi.reset()` clears the workspace, which is the
678
+ * only way to start over other than clearing site data in the browser.
679
+ */
680
+ window.__sdrStaticApi = {
681
+ api: api,
682
+ store: store,
683
+ reset: function () {
684
+ return store.clear().then(function () {
685
+ window.location.reload();
686
+ });
687
+ }
688
+ };
689
+ })();
static/app.js ADDED
@@ -0,0 +1,710 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const state = {
2
+ documents: [],
3
+ reviewers: [],
4
+ notifications: [],
5
+ selectedId: null,
6
+ selectedDocument: null,
7
+ filter: "all",
8
+ view: "documents",
9
+ reviewerAction: "comment",
10
+ };
11
+
12
+ const els = {
13
+ fileInput: document.querySelector("#fileInput"),
14
+ uploadButton: document.querySelector("#uploadButton"),
15
+ dropZone: document.querySelector("#dropZone"),
16
+ ownerName: document.querySelector("#ownerName"),
17
+ ownerEmail: document.querySelector("#ownerEmail"),
18
+ ownerSlack: document.querySelector("#ownerSlack"),
19
+ ownerTeams: document.querySelector("#ownerTeams"),
20
+ sideTabs: document.querySelectorAll(".side-tab"),
21
+ documentsView: document.querySelector("#documentsView"),
22
+ reviewersView: document.querySelector("#reviewersView"),
23
+ notificationsView: document.querySelector("#notificationsView"),
24
+ notificationBadge: document.querySelector("#notificationBadge"),
25
+ filters: document.querySelectorAll(".filter"),
26
+ documentList: document.querySelector("#documentList"),
27
+ reviewerForm: document.querySelector("#reviewerForm"),
28
+ reviewerId: document.querySelector("#reviewerId"),
29
+ reviewerName: document.querySelector("#reviewerName"),
30
+ reviewerEmail: document.querySelector("#reviewerEmail"),
31
+ reviewerSlack: document.querySelector("#reviewerSlack"),
32
+ reviewerTeams: document.querySelector("#reviewerTeams"),
33
+ reviewerSaveButton: document.querySelector("#reviewerSaveButton"),
34
+ reviewerCancelButton: document.querySelector("#reviewerCancelButton"),
35
+ reviewerList: document.querySelector("#reviewerList"),
36
+ notificationList: document.querySelector("#notificationList"),
37
+ emptyState: document.querySelector("#emptyState"),
38
+ documentPanel: document.querySelector("#documentPanel"),
39
+ documentMeta: document.querySelector("#documentMeta"),
40
+ documentTitle: document.querySelector("#documentTitle"),
41
+ ownerLine: document.querySelector("#ownerLine"),
42
+ statusPill: document.querySelector("#statusPill"),
43
+ downloadButton: document.querySelector("#downloadButton"),
44
+ reviewButton: document.querySelector("#reviewButton"),
45
+ assignmentSummary: document.querySelector("#assignmentSummary"),
46
+ assignmentForm: document.querySelector("#assignmentForm"),
47
+ assignmentChoices: document.querySelector("#assignmentChoices"),
48
+ assignmentList: document.querySelector("#assignmentList"),
49
+ reviewerActionForm: document.querySelector("#reviewerActionForm"),
50
+ reviewerActionSelect: document.querySelector("#reviewerActionSelect"),
51
+ reviewerSignature: document.querySelector("#reviewerSignature"),
52
+ reviewerNote: document.querySelector("#reviewerNote"),
53
+ findings: document.querySelector("#findings"),
54
+ findingSummary: document.querySelector("#findingSummary"),
55
+ commentForm: document.querySelector("#commentForm"),
56
+ commentBody: document.querySelector("#commentBody"),
57
+ comments: document.querySelector("#comments"),
58
+ commentCount: document.querySelector("#commentCount"),
59
+ activityTimeline: document.querySelector("#activityTimeline"),
60
+ activityCount: document.querySelector("#activityCount"),
61
+ textPreview: document.querySelector("#textPreview"),
62
+ wordCount: document.querySelector("#wordCount"),
63
+ toast: document.querySelector("#toast"),
64
+ };
65
+
66
+ async function api(path, options = {}) {
67
+ return new Promise((resolve, reject) => {
68
+ const request = new XMLHttpRequest();
69
+ request.open(options.method || "GET", path, true);
70
+ for (const [key, value] of Object.entries(options.headers || {})) {
71
+ request.setRequestHeader(key, value);
72
+ }
73
+ request.onload = () => {
74
+ const contentType = request.getResponseHeader("Content-Type") || "";
75
+ const payload = contentType.includes("application/json") && request.responseText
76
+ ? JSON.parse(request.responseText)
77
+ : null;
78
+ if (request.status >= 200 && request.status < 300) {
79
+ resolve(payload);
80
+ } else {
81
+ reject(new Error(payload?.error || `Request failed with ${request.status}`));
82
+ }
83
+ };
84
+ request.onerror = () => reject(new Error("Request failed."));
85
+ request.send(options.body || null);
86
+ });
87
+ }
88
+
89
+ function showToast(message, isError = false) {
90
+ els.toast.textContent = message;
91
+ els.toast.classList.toggle("error", isError);
92
+ els.toast.classList.remove("hidden");
93
+ clearTimeout(showToast.timer);
94
+ showToast.timer = setTimeout(() => els.toast.classList.add("hidden"), 3600);
95
+ }
96
+
97
+ function formatDate(value) {
98
+ if (!value) return "Not recorded";
99
+ return new Intl.DateTimeFormat(undefined, {
100
+ month: "short",
101
+ day: "numeric",
102
+ hour: "numeric",
103
+ minute: "2-digit",
104
+ }).format(new Date(value));
105
+ }
106
+
107
+ function countsFor(document) {
108
+ const counts = { high: 0, medium: 0, low: 0 };
109
+ for (const finding of document.findings || []) {
110
+ counts[finding.severity] += 1;
111
+ }
112
+ return counts;
113
+ }
114
+
115
+ function contactLine(contact = {}) {
116
+ return [contact.email, contact.slack, contact.teams].filter(Boolean).join(" | ");
117
+ }
118
+
119
+ async function loadAll() {
120
+ const [documents, reviewers, notifications] = await Promise.all([
121
+ api("/api/documents"),
122
+ api("/api/reviewers"),
123
+ api("/api/notifications"),
124
+ ]);
125
+ state.documents = documents.documents;
126
+ state.reviewers = reviewers.reviewers;
127
+ state.notifications = notifications.notifications;
128
+ renderNavigation(notifications.unread_count || 0);
129
+ renderList();
130
+ renderReviewerList();
131
+ renderNotifications();
132
+
133
+ if (state.selectedId && state.documents.some((doc) => doc.id === state.selectedId)) {
134
+ await selectDocument(state.selectedId);
135
+ } else if (state.documents.length > 0 && !state.selectedId) {
136
+ await selectDocument(state.documents[0].id);
137
+ } else if (state.documents.length === 0) {
138
+ renderEmpty();
139
+ }
140
+ }
141
+
142
+ async function refreshSelected() {
143
+ const [documents, notifications] = await Promise.all([api("/api/documents"), api("/api/notifications")]);
144
+ state.documents = documents.documents;
145
+ state.notifications = notifications.notifications;
146
+ renderNavigation(notifications.unread_count || 0);
147
+ renderList();
148
+ renderNotifications();
149
+ if (state.selectedId) {
150
+ state.selectedDocument = await api(`/api/documents/${state.selectedId}`);
151
+ renderDocument();
152
+ }
153
+ }
154
+
155
+ function renderNavigation(unreadCount = 0) {
156
+ els.sideTabs.forEach((button) => button.classList.toggle("active", button.dataset.view === state.view));
157
+ els.documentsView.classList.toggle("hidden", state.view !== "documents");
158
+ els.reviewersView.classList.toggle("hidden", state.view !== "reviewers");
159
+ els.notificationsView.classList.toggle("hidden", state.view !== "notifications");
160
+ els.notificationBadge.textContent = `${unreadCount}`;
161
+ els.notificationBadge.classList.toggle("hidden", unreadCount === 0);
162
+ }
163
+
164
+ function renderList() {
165
+ const filtered = state.documents.filter((document) => {
166
+ if (state.filter === "all") return true;
167
+ if (state.filter === "in_review") return document.status === "in_review" || document.status === "uploaded";
168
+ return document.status === state.filter;
169
+ });
170
+
171
+ if (!filtered.length) {
172
+ els.documentList.innerHTML = `<p class="quiet">No documents in this view.</p>`;
173
+ return;
174
+ }
175
+
176
+ els.documentList.innerHTML = filtered
177
+ .map((document) => {
178
+ const counts = countsFor(document);
179
+ const assignments = document.assignment_counts || {};
180
+ return `
181
+ <button class="queue-item ${document.id === state.selectedId ? "active" : ""}" type="button" data-id="${document.id}">
182
+ <span class="queue-title">${escapeHtml(document.filename)}</span>
183
+ <span class="queue-meta">
184
+ <span>${escapeHtml(document.status_label)}</span>
185
+ <span>${document.word_count || 0} words</span>
186
+ </span>
187
+ <span class="queue-meta">
188
+ <span>${assignments.approved || 0}/${assignmentTotal(assignments)} approved</span>
189
+ <span class="mini-counts" title="High, medium, and low findings">
190
+ <span>${counts.high}</span><span>${counts.medium}</span><span>${counts.low}</span>
191
+ </span>
192
+ </span>
193
+ </button>
194
+ `;
195
+ })
196
+ .join("");
197
+
198
+ els.documentList.querySelectorAll("[data-id]").forEach((button) => {
199
+ button.addEventListener("click", () => selectDocument(button.dataset.id));
200
+ });
201
+ }
202
+
203
+ function assignmentTotal(counts) {
204
+ return (counts.pending || 0) + (counts.commented || 0) + (counts.changes_requested || 0) + (counts.approved || 0);
205
+ }
206
+
207
+ function renderEmpty() {
208
+ state.selectedDocument = null;
209
+ els.emptyState.classList.remove("hidden");
210
+ els.documentPanel.classList.add("hidden");
211
+ }
212
+
213
+ async function selectDocument(id) {
214
+ state.selectedId = id;
215
+ state.selectedDocument = await api(`/api/documents/${id}`);
216
+ renderList();
217
+ renderDocument();
218
+ }
219
+
220
+ function renderDocument() {
221
+ const document = state.selectedDocument;
222
+ if (!document) {
223
+ renderEmpty();
224
+ return;
225
+ }
226
+
227
+ els.emptyState.classList.add("hidden");
228
+ els.documentPanel.classList.remove("hidden");
229
+ els.documentTitle.textContent = document.filename;
230
+ els.documentMeta.textContent = `${document.extension.toUpperCase().replace(".", "")} | Uploaded ${formatDate(document.created_at)}`;
231
+ els.ownerLine.textContent = `Owner: ${document.owner?.name || "Owner"}${contactLine(document.owner) ? ` | ${contactLine(document.owner)}` : ""}`;
232
+ els.statusPill.textContent = document.status_label;
233
+ els.statusPill.className = `status-pill ${document.status}`;
234
+ els.wordCount.textContent = `${document.word_count || 0} words`;
235
+ els.textPreview.textContent = document.text || "";
236
+ els.downloadButton.onclick = () => {
237
+ window.location.href = `/api/documents/${document.id}/download`;
238
+ };
239
+
240
+ renderAssignments(document);
241
+ renderFindings(document);
242
+ renderComments(document);
243
+ renderActivity(document);
244
+ }
245
+
246
+ function renderAssignments(document) {
247
+ const selectedReviewerIds = new Set((document.assignments || []).map((assignment) => assignment.reviewer_id));
248
+ if (!state.reviewers.length) {
249
+ els.assignmentChoices.innerHTML = `<p class="quiet">Add reviewers in the sidebar first.</p>`;
250
+ } else {
251
+ els.assignmentChoices.innerHTML = state.reviewers
252
+ .map(
253
+ (reviewer) => `
254
+ <label class="check-card">
255
+ <input type="checkbox" value="${escapeHtml(reviewer.id)}" ${selectedReviewerIds.has(reviewer.id) ? "checked" : ""}>
256
+ <span>
257
+ <strong>${escapeHtml(reviewer.name)}</strong>
258
+ <small>${escapeHtml(contactLine(reviewer) || "No contact set")}</small>
259
+ </span>
260
+ </label>
261
+ `,
262
+ )
263
+ .join("");
264
+ }
265
+
266
+ const counts = document.assignment_counts || {};
267
+ const total = assignmentTotal(counts);
268
+ els.assignmentSummary.textContent = total ? `${counts.approved || 0}/${total} approved` : "No reviewers";
269
+
270
+ if (!(document.assignments || []).length) {
271
+ els.assignmentList.innerHTML = `<p class="quiet">No reviewers assigned.</p>`;
272
+ els.reviewerActionSelect.innerHTML = `<option value="">Assign a reviewer first</option>`;
273
+ els.reviewerActionForm.classList.add("muted-panel");
274
+ return;
275
+ }
276
+
277
+ els.reviewerActionForm.classList.remove("muted-panel");
278
+ els.assignmentList.innerHTML = document.assignments
279
+ .map(
280
+ (assignment) => `
281
+ <article class="assignment-card ${assignment.status}">
282
+ <div>
283
+ <strong>${escapeHtml(assignment.reviewer_name)}</strong>
284
+ <small>${escapeHtml(contactLine(assignment.reviewer_contact) || "No contact set")}</small>
285
+ </div>
286
+ <span class="status-chip ${assignment.status}">${escapeHtml(assignment.status_label)}</span>
287
+ ${assignment.approved_at ? `<small>Approved ${formatDate(assignment.approved_at)} as ${escapeHtml(assignment.approval_name)}</small>` : ""}
288
+ </article>
289
+ `,
290
+ )
291
+ .join("");
292
+ els.reviewerActionSelect.innerHTML = document.assignments
293
+ .map((assignment) => `<option value="${escapeHtml(assignment.reviewer_id)}">${escapeHtml(assignment.reviewer_name)}</option>`)
294
+ .join("");
295
+ }
296
+
297
+ function renderFindings(document) {
298
+ const findings = document.findings || [];
299
+ if (!document.reviewed_at) {
300
+ els.findingSummary.textContent = "Not reviewed";
301
+ els.findings.innerHTML = `<p class="quiet">Run a review to check required sections, placeholders, and vague language.</p>`;
302
+ return;
303
+ }
304
+
305
+ const counts = countsFor(document);
306
+ els.findingSummary.textContent = `${counts.high} high, ${counts.medium} medium, ${counts.low} low`;
307
+
308
+ if (!findings.length) {
309
+ els.findings.innerHTML = `<p class="quiet">No findings from the local rubric.</p>`;
310
+ return;
311
+ }
312
+
313
+ const groups = ["high", "medium", "low"]
314
+ .map((severity) => findings.filter((finding) => finding.severity === severity))
315
+ .filter((group) => group.length);
316
+
317
+ els.findings.innerHTML = groups
318
+ .map((group) => {
319
+ const severity = group[0].severity;
320
+ return `
321
+ <div class="finding-group">
322
+ <div class="severity-heading">
323
+ <span class="severity-dot ${severity}"></span>
324
+ ${severity} severity
325
+ </div>
326
+ ${group.map(renderFinding).join("")}
327
+ </div>
328
+ `;
329
+ })
330
+ .join("");
331
+ }
332
+
333
+ function renderFinding(finding) {
334
+ return `
335
+ <article class="finding ${finding.severity}">
336
+ <h4>${escapeHtml(finding.title)}</h4>
337
+ <p>${escapeHtml(finding.detail)}</p>
338
+ ${finding.snippet ? `<div class="snippet">${escapeHtml(finding.snippet)}</div>` : ""}
339
+ </article>
340
+ `;
341
+ }
342
+
343
+ function renderComments(document) {
344
+ const comments = document.comments || [];
345
+ els.commentCount.textContent = `${comments.length}`;
346
+ if (!comments.length) {
347
+ els.comments.innerHTML = `<p class="quiet">No comments yet.</p>`;
348
+ return;
349
+ }
350
+ els.comments.innerHTML = comments
351
+ .slice()
352
+ .reverse()
353
+ .map(
354
+ (comment) => `
355
+ <article class="comment">
356
+ <strong>${escapeHtml(comment.author)}</strong>
357
+ <time>${formatDate(comment.created_at)}</time>
358
+ <p>${escapeHtml(comment.body)}</p>
359
+ </article>
360
+ `,
361
+ )
362
+ .join("");
363
+ }
364
+
365
+ function renderActivity(document) {
366
+ const activity = document.activity || [];
367
+ els.activityCount.textContent = `${activity.length}`;
368
+ if (!activity.length) {
369
+ els.activityTimeline.innerHTML = `<p class="quiet">No activity yet.</p>`;
370
+ return;
371
+ }
372
+ els.activityTimeline.innerHTML = activity
373
+ .map(
374
+ (item) => `
375
+ <article class="timeline-item">
376
+ <span></span>
377
+ <div>
378
+ <strong>${escapeHtml(item.actor)}</strong>
379
+ <p>${escapeHtml(item.message)}</p>
380
+ <time>${formatDate(item.created_at)}</time>
381
+ </div>
382
+ </article>
383
+ `,
384
+ )
385
+ .join("");
386
+ }
387
+
388
+ function renderReviewerList() {
389
+ if (!state.reviewers.length) {
390
+ els.reviewerList.innerHTML = `<p class="quiet">No reviewers yet.</p>`;
391
+ return;
392
+ }
393
+ els.reviewerList.innerHTML = state.reviewers
394
+ .map(
395
+ (reviewer) => `
396
+ <article class="person-card">
397
+ <div>
398
+ <strong>${escapeHtml(reviewer.name)}</strong>
399
+ <small>${escapeHtml(contactLine(reviewer) || "No contact set")}</small>
400
+ </div>
401
+ <div class="icon-row">
402
+ <button class="secondary tiny" type="button" data-edit-reviewer="${escapeHtml(reviewer.id)}">Edit</button>
403
+ <button class="secondary tiny danger-text" type="button" data-delete-reviewer="${escapeHtml(reviewer.id)}">Remove</button>
404
+ </div>
405
+ </article>
406
+ `,
407
+ )
408
+ .join("");
409
+
410
+ els.reviewerList.querySelectorAll("[data-edit-reviewer]").forEach((button) => {
411
+ button.addEventListener("click", () => editReviewer(button.dataset.editReviewer));
412
+ });
413
+ els.reviewerList.querySelectorAll("[data-delete-reviewer]").forEach((button) => {
414
+ button.addEventListener("click", () => deleteReviewer(button.dataset.deleteReviewer));
415
+ });
416
+ }
417
+
418
+ function renderNotifications() {
419
+ if (!state.notifications.length) {
420
+ els.notificationList.innerHTML = `<p class="quiet">No notifications yet.</p>`;
421
+ return;
422
+ }
423
+ els.notificationList.innerHTML = state.notifications
424
+ .map(
425
+ (notification) => `
426
+ <article class="notification-card ${notification.read_at ? "" : "unread"}">
427
+ <div>
428
+ <strong>${escapeHtml(notification.recipient_name)}</strong>
429
+ <small>${escapeHtml(notification.recipient_type)} | ${formatDate(notification.created_at)}</small>
430
+ </div>
431
+ <p>${escapeHtml(notification.message)}</p>
432
+ <div class="icon-row">
433
+ <button class="secondary tiny" type="button" data-copy-notification="${escapeHtml(notification.id)}">Copy</button>
434
+ ${
435
+ notification.read_at
436
+ ? `<span class="quiet tiny-label">Read</span>`
437
+ : `<button class="secondary tiny" type="button" data-read-notification="${escapeHtml(notification.id)}">Mark read</button>`
438
+ }
439
+ </div>
440
+ </article>
441
+ `,
442
+ )
443
+ .join("");
444
+
445
+ els.notificationList.querySelectorAll("[data-copy-notification]").forEach((button) => {
446
+ button.addEventListener("click", () => copyNotification(button.dataset.copyNotification));
447
+ });
448
+ els.notificationList.querySelectorAll("[data-read-notification]").forEach((button) => {
449
+ button.addEventListener("click", () => markNotificationRead(button.dataset.readNotification));
450
+ });
451
+ }
452
+
453
+ async function uploadFile(file) {
454
+ if (!file) return;
455
+ const form = new FormData();
456
+ form.append("file", file);
457
+ form.append("owner_name", els.ownerName.value.trim());
458
+ form.append("owner_email", els.ownerEmail.value.trim());
459
+ form.append("owner_slack", els.ownerSlack.value.trim());
460
+ form.append("owner_teams", els.ownerTeams.value.trim());
461
+ els.uploadButton.disabled = true;
462
+ els.uploadButton.textContent = "Uploading...";
463
+ try {
464
+ const document = await api("/api/upload", { method: "POST", body: form });
465
+ showToast("Document uploaded.");
466
+ state.selectedId = document.id;
467
+ await loadAll();
468
+ } catch (error) {
469
+ showToast(error.message, true);
470
+ } finally {
471
+ els.uploadButton.disabled = false;
472
+ els.uploadButton.innerHTML = `<span class="button-icon">+</span>Upload document`;
473
+ els.fileInput.value = "";
474
+ }
475
+ }
476
+
477
+ async function refreshSelectedWith(action, message) {
478
+ if (!state.selectedId) return;
479
+ try {
480
+ state.selectedDocument = await api(`/api/documents/${state.selectedId}/${action}`, { method: "POST" });
481
+ showToast(message);
482
+ await refreshSelected();
483
+ } catch (error) {
484
+ showToast(error.message, true);
485
+ }
486
+ }
487
+
488
+ async function saveReviewer(event) {
489
+ event.preventDefault();
490
+ const payload = {
491
+ name: els.reviewerName.value.trim(),
492
+ email: els.reviewerEmail.value.trim(),
493
+ slack: els.reviewerSlack.value.trim(),
494
+ teams: els.reviewerTeams.value.trim(),
495
+ };
496
+ const id = els.reviewerId.value;
497
+ try {
498
+ if (id) {
499
+ await api(`/api/reviewers/${id}`, {
500
+ method: "PUT",
501
+ headers: { "Content-Type": "application/json" },
502
+ body: JSON.stringify(payload),
503
+ });
504
+ showToast("Reviewer updated.");
505
+ } else {
506
+ await api("/api/reviewers", {
507
+ method: "POST",
508
+ headers: { "Content-Type": "application/json" },
509
+ body: JSON.stringify(payload),
510
+ });
511
+ showToast("Reviewer added.");
512
+ }
513
+ resetReviewerForm();
514
+ await loadAll();
515
+ } catch (error) {
516
+ showToast(error.message, true);
517
+ }
518
+ }
519
+
520
+ function editReviewer(id) {
521
+ const reviewer = state.reviewers.find((item) => item.id === id);
522
+ if (!reviewer) return;
523
+ els.reviewerId.value = reviewer.id;
524
+ els.reviewerName.value = reviewer.name;
525
+ els.reviewerEmail.value = reviewer.email || "";
526
+ els.reviewerSlack.value = reviewer.slack || "";
527
+ els.reviewerTeams.value = reviewer.teams || "";
528
+ els.reviewerSaveButton.textContent = "Update reviewer";
529
+ els.reviewerCancelButton.classList.remove("hidden");
530
+ }
531
+
532
+ function resetReviewerForm() {
533
+ els.reviewerForm.reset();
534
+ els.reviewerId.value = "";
535
+ els.reviewerSaveButton.textContent = "Save reviewer";
536
+ els.reviewerCancelButton.classList.add("hidden");
537
+ }
538
+
539
+ async function deleteReviewer(id) {
540
+ const reviewer = state.reviewers.find((item) => item.id === id);
541
+ if (!reviewer) return;
542
+ if (!window.confirm(`Remove ${reviewer.name} from the reviewer directory? Historical assignments stay on documents.`)) {
543
+ return;
544
+ }
545
+ try {
546
+ await api(`/api/reviewers/${id}`, { method: "DELETE" });
547
+ showToast("Reviewer removed.");
548
+ await loadAll();
549
+ } catch (error) {
550
+ showToast(error.message, true);
551
+ }
552
+ }
553
+
554
+ async function assignReviewers(event) {
555
+ event.preventDefault();
556
+ if (!state.selectedId) return;
557
+ const reviewerIds = Array.from(els.assignmentChoices.querySelectorAll("input[type='checkbox']:checked")).map((input) => input.value);
558
+ try {
559
+ await api(`/api/documents/${state.selectedId}/assign-reviewers`, {
560
+ method: "POST",
561
+ headers: { "Content-Type": "application/json" },
562
+ body: JSON.stringify({ reviewer_ids: reviewerIds }),
563
+ });
564
+ showToast("Reviewer assignments updated.");
565
+ await refreshSelected();
566
+ } catch (error) {
567
+ showToast(error.message, true);
568
+ }
569
+ }
570
+
571
+ async function submitReviewerAction(event) {
572
+ event.preventDefault();
573
+ const submitter = event.submitter;
574
+ const action = submitter?.dataset.reviewerAction || state.reviewerAction;
575
+ const reviewerId = els.reviewerActionSelect.value;
576
+ const signature = els.reviewerSignature.value.trim();
577
+ const body = els.reviewerNote.value.trim();
578
+ if (!reviewerId) {
579
+ showToast("Choose an assigned reviewer.", true);
580
+ return;
581
+ }
582
+ if (action === "approve" && !signature) {
583
+ showToast("Enter a name or initials to approve.", true);
584
+ return;
585
+ }
586
+ if ((action === "comment" || action === "request") && !body) {
587
+ showToast("Add a note first.", true);
588
+ return;
589
+ }
590
+ if (action === "approve" && (state.selectedDocument?.findings || []).length) {
591
+ if (!window.confirm("This document still has review findings. Approve anyway?")) {
592
+ return;
593
+ }
594
+ }
595
+
596
+ const endpoint = {
597
+ comment: "reviewer-comment",
598
+ request: "reviewer-request-changes",
599
+ approve: "reviewer-approve",
600
+ }[action];
601
+
602
+ try {
603
+ await api(`/api/documents/${state.selectedId}/${endpoint}`, {
604
+ method: "POST",
605
+ headers: { "Content-Type": "application/json" },
606
+ body: JSON.stringify({ reviewer_id: reviewerId, signature, body }),
607
+ });
608
+ els.reviewerNote.value = "";
609
+ els.reviewerSignature.value = "";
610
+ showToast(action === "approve" ? "Reviewer approval recorded." : "Reviewer response recorded.");
611
+ await refreshSelected();
612
+ } catch (error) {
613
+ showToast(error.message, true);
614
+ }
615
+ }
616
+
617
+ async function copyNotification(id) {
618
+ const notification = state.notifications.find((item) => item.id === id);
619
+ if (!notification) return;
620
+ try {
621
+ await navigator.clipboard.writeText(notification.message);
622
+ showToast("Notification copied.");
623
+ } catch {
624
+ showToast(notification.message);
625
+ }
626
+ }
627
+
628
+ async function markNotificationRead(id) {
629
+ try {
630
+ await api(`/api/notifications/${id}/read`, { method: "POST" });
631
+ showToast("Notification marked read.");
632
+ const payload = await api("/api/notifications");
633
+ state.notifications = payload.notifications;
634
+ renderNavigation(payload.unread_count || 0);
635
+ renderNotifications();
636
+ } catch (error) {
637
+ showToast(error.message, true);
638
+ }
639
+ }
640
+
641
+ function escapeHtml(value) {
642
+ return String(value ?? "")
643
+ .replaceAll("&", "&amp;")
644
+ .replaceAll("<", "&lt;")
645
+ .replaceAll(">", "&gt;")
646
+ .replaceAll('"', "&quot;")
647
+ .replaceAll("'", "&#039;");
648
+ }
649
+
650
+ els.sideTabs.forEach((button) => {
651
+ button.addEventListener("click", () => {
652
+ state.view = button.dataset.view;
653
+ renderNavigation(state.notifications.filter((item) => !item.read_at).length);
654
+ });
655
+ });
656
+
657
+ els.uploadButton.addEventListener("click", () => els.fileInput.click());
658
+ els.fileInput.addEventListener("change", () => uploadFile(els.fileInput.files[0]));
659
+
660
+ ["dragenter", "dragover"].forEach((eventName) => {
661
+ els.dropZone.addEventListener(eventName, (event) => {
662
+ event.preventDefault();
663
+ els.dropZone.classList.add("dragging");
664
+ });
665
+ });
666
+
667
+ ["dragleave", "drop"].forEach((eventName) => {
668
+ els.dropZone.addEventListener(eventName, (event) => {
669
+ event.preventDefault();
670
+ els.dropZone.classList.remove("dragging");
671
+ });
672
+ });
673
+
674
+ els.dropZone.addEventListener("drop", (event) => uploadFile(event.dataTransfer.files[0]));
675
+
676
+ els.filters.forEach((button) => {
677
+ button.addEventListener("click", () => {
678
+ state.filter = button.dataset.filter;
679
+ els.filters.forEach((item) => item.classList.toggle("active", item === button));
680
+ renderList();
681
+ });
682
+ });
683
+
684
+ els.reviewerForm.addEventListener("submit", saveReviewer);
685
+ els.reviewerCancelButton.addEventListener("click", resetReviewerForm);
686
+ els.assignmentForm.addEventListener("submit", assignReviewers);
687
+ els.reviewerActionForm.addEventListener("submit", submitReviewerAction);
688
+ els.reviewButton.addEventListener("click", () => refreshSelectedWith("review", "Review complete."));
689
+
690
+ els.commentForm.addEventListener("submit", async (event) => {
691
+ event.preventDefault();
692
+ if (!state.selectedId) return;
693
+ const body = els.commentBody.value.trim();
694
+ if (!body) return;
695
+
696
+ try {
697
+ state.selectedDocument = await api(`/api/documents/${state.selectedId}/comments`, {
698
+ method: "POST",
699
+ headers: { "Content-Type": "application/json" },
700
+ body: JSON.stringify({ body, author: state.selectedDocument?.owner?.name || "Owner" }),
701
+ });
702
+ els.commentBody.value = "";
703
+ showToast("Comment added.");
704
+ await refreshSelected();
705
+ } catch (error) {
706
+ showToast(error.message, true);
707
+ }
708
+ });
709
+
710
+ loadAll().catch((error) => showToast(error.message, true));
static/styles.css ADDED
@@ -0,0 +1,838 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --ink: #172126;
3
+ --muted: #64737c;
4
+ --line: #d9e1e4;
5
+ --panel: #ffffff;
6
+ --wash: #f3f6f4;
7
+ --accent: #0f766e;
8
+ --accent-dark: #0a5c56;
9
+ --danger: #b42318;
10
+ --warning: #b85b00;
11
+ --low: #52606a;
12
+ --shadow: 0 18px 45px rgba(23, 33, 38, 0.12);
13
+ }
14
+
15
+ * {
16
+ box-sizing: border-box;
17
+ }
18
+
19
+ body {
20
+ margin: 0;
21
+ min-height: 100vh;
22
+ color: var(--ink);
23
+ background:
24
+ linear-gradient(180deg, rgba(15, 118, 110, 0.08), transparent 320px),
25
+ var(--wash);
26
+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
27
+ }
28
+
29
+ button,
30
+ input,
31
+ textarea {
32
+ font: inherit;
33
+ }
34
+
35
+ button {
36
+ border: 0;
37
+ cursor: pointer;
38
+ }
39
+
40
+ .app-shell {
41
+ display: grid;
42
+ grid-template-columns: 360px minmax(0, 1fr);
43
+ min-height: 100vh;
44
+ }
45
+
46
+ .sidebar {
47
+ display: flex;
48
+ flex-direction: column;
49
+ gap: 18px;
50
+ padding: 24px;
51
+ border-right: 1px solid var(--line);
52
+ background: rgba(255, 255, 255, 0.72);
53
+ backdrop-filter: blur(14px);
54
+ }
55
+
56
+ .brand {
57
+ display: flex;
58
+ align-items: flex-start;
59
+ justify-content: space-between;
60
+ gap: 16px;
61
+ }
62
+
63
+ .eyebrow {
64
+ margin: 0 0 6px;
65
+ color: var(--muted);
66
+ font-size: 0.75rem;
67
+ font-weight: 700;
68
+ letter-spacing: 0;
69
+ text-transform: uppercase;
70
+ }
71
+
72
+ h1,
73
+ h2,
74
+ h3,
75
+ p {
76
+ margin-top: 0;
77
+ }
78
+
79
+ h1 {
80
+ margin-bottom: 0;
81
+ font-size: 2rem;
82
+ line-height: 1.05;
83
+ }
84
+
85
+ h2 {
86
+ margin-bottom: 0;
87
+ font-size: clamp(1.4rem, 2vw, 2.3rem);
88
+ line-height: 1.08;
89
+ }
90
+
91
+ h3 {
92
+ margin-bottom: 0;
93
+ font-size: 1rem;
94
+ }
95
+
96
+ .live-dot {
97
+ width: 12px;
98
+ height: 12px;
99
+ margin-top: 9px;
100
+ border-radius: 999px;
101
+ background: #20a46b;
102
+ box-shadow: 0 0 0 5px rgba(32, 164, 107, 0.15);
103
+ }
104
+
105
+ .upload-zone {
106
+ display: grid;
107
+ gap: 10px;
108
+ padding: 16px;
109
+ border: 1px dashed #9eb3b1;
110
+ border-radius: 8px;
111
+ background: #f8fbfa;
112
+ transition: border-color 160ms ease, background 160ms ease;
113
+ }
114
+
115
+ .upload-zone.dragging {
116
+ border-color: var(--accent);
117
+ background: #e9f6f3;
118
+ }
119
+
120
+ #fileInput {
121
+ display: none;
122
+ }
123
+
124
+ .upload-zone p {
125
+ margin-bottom: 0;
126
+ color: var(--muted);
127
+ font-size: 0.88rem;
128
+ }
129
+
130
+ .upload-button,
131
+ .primary,
132
+ .secondary,
133
+ .warning {
134
+ display: inline-flex;
135
+ min-height: 40px;
136
+ align-items: center;
137
+ justify-content: center;
138
+ gap: 8px;
139
+ padding: 0 14px;
140
+ border-radius: 8px;
141
+ font-weight: 700;
142
+ transition: transform 120ms ease, box-shadow 120ms ease, background 120ms ease;
143
+ }
144
+
145
+ .upload-button,
146
+ .primary {
147
+ color: #fff;
148
+ background: var(--accent);
149
+ }
150
+
151
+ .upload-button:hover,
152
+ .primary:hover {
153
+ background: var(--accent-dark);
154
+ }
155
+
156
+ .secondary {
157
+ color: var(--ink);
158
+ background: #e8eeee;
159
+ }
160
+
161
+ .secondary:hover {
162
+ background: #dce5e5;
163
+ }
164
+
165
+ .warning {
166
+ color: #fff;
167
+ background: var(--warning);
168
+ }
169
+
170
+ .warning:hover {
171
+ background: #984a00;
172
+ }
173
+
174
+ .button-icon {
175
+ display: inline-grid;
176
+ min-width: 18px;
177
+ height: 18px;
178
+ place-items: center;
179
+ font-size: 0.76rem;
180
+ font-weight: 900;
181
+ line-height: 1;
182
+ }
183
+
184
+ .filters {
185
+ display: grid;
186
+ grid-template-columns: repeat(4, minmax(0, 1fr));
187
+ gap: 4px;
188
+ padding: 4px;
189
+ border: 1px solid var(--line);
190
+ border-radius: 8px;
191
+ background: #edf2f1;
192
+ }
193
+
194
+ .filter {
195
+ min-height: 34px;
196
+ border-radius: 6px;
197
+ color: var(--muted);
198
+ background: transparent;
199
+ font-size: 0.82rem;
200
+ font-weight: 800;
201
+ }
202
+
203
+ .filter.active {
204
+ color: var(--ink);
205
+ background: #fff;
206
+ box-shadow: 0 1px 4px rgba(23, 33, 38, 0.08);
207
+ }
208
+
209
+ .queue {
210
+ display: grid;
211
+ gap: 10px;
212
+ min-height: 0;
213
+ overflow: auto;
214
+ padding-right: 2px;
215
+ }
216
+
217
+ .queue-item {
218
+ display: grid;
219
+ gap: 8px;
220
+ width: 100%;
221
+ padding: 14px;
222
+ border: 1px solid var(--line);
223
+ border-radius: 8px;
224
+ color: var(--ink);
225
+ background: rgba(255, 255, 255, 0.86);
226
+ text-align: left;
227
+ }
228
+
229
+ .queue-item.active {
230
+ border-color: var(--accent);
231
+ box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.12);
232
+ }
233
+
234
+ .queue-title {
235
+ overflow: hidden;
236
+ font-weight: 800;
237
+ text-overflow: ellipsis;
238
+ white-space: nowrap;
239
+ }
240
+
241
+ .queue-meta {
242
+ display: flex;
243
+ align-items: center;
244
+ justify-content: space-between;
245
+ gap: 10px;
246
+ color: var(--muted);
247
+ font-size: 0.8rem;
248
+ }
249
+
250
+ .mini-counts {
251
+ display: inline-flex;
252
+ gap: 6px;
253
+ }
254
+
255
+ .mini-counts span {
256
+ min-width: 22px;
257
+ padding: 2px 6px;
258
+ border-radius: 999px;
259
+ background: #eef2f2;
260
+ text-align: center;
261
+ font-weight: 800;
262
+ }
263
+
264
+ .workspace {
265
+ min-width: 0;
266
+ padding: 30px;
267
+ }
268
+
269
+ .empty-state,
270
+ .document-panel {
271
+ width: min(1120px, 100%);
272
+ margin: 0 auto;
273
+ }
274
+
275
+ .empty-state {
276
+ display: grid;
277
+ min-height: calc(100vh - 60px);
278
+ place-content: center;
279
+ text-align: center;
280
+ }
281
+
282
+ .empty-mark {
283
+ display: grid;
284
+ width: 70px;
285
+ height: 70px;
286
+ place-items: center;
287
+ margin: 0 auto 20px;
288
+ border-radius: 8px;
289
+ color: #fff;
290
+ background: var(--accent);
291
+ font-weight: 900;
292
+ }
293
+
294
+ .empty-state p {
295
+ color: var(--muted);
296
+ }
297
+
298
+ .document-panel {
299
+ display: grid;
300
+ gap: 20px;
301
+ }
302
+
303
+ .hidden {
304
+ display: none !important;
305
+ }
306
+
307
+ .document-header {
308
+ display: flex;
309
+ align-items: flex-start;
310
+ justify-content: space-between;
311
+ gap: 20px;
312
+ }
313
+
314
+ .status-pill {
315
+ display: inline-flex;
316
+ min-height: 32px;
317
+ align-items: center;
318
+ padding: 0 12px;
319
+ border-radius: 999px;
320
+ color: var(--accent-dark);
321
+ background: #dff2ee;
322
+ font-size: 0.8rem;
323
+ font-weight: 900;
324
+ white-space: nowrap;
325
+ }
326
+
327
+ .status-pill.changes_requested {
328
+ color: #823b00;
329
+ background: #ffe6c7;
330
+ }
331
+
332
+ .status-pill.approved {
333
+ color: #0d5d36;
334
+ background: #dff6e9;
335
+ }
336
+
337
+ .status-pill.uploaded {
338
+ color: #44515a;
339
+ background: #e9eeee;
340
+ }
341
+
342
+ .actions {
343
+ display: flex;
344
+ flex-wrap: wrap;
345
+ gap: 10px;
346
+ }
347
+
348
+ .review-grid {
349
+ display: grid;
350
+ grid-template-columns: minmax(0, 1.2fr) minmax(300px, 0.8fr);
351
+ gap: 18px;
352
+ align-items: start;
353
+ }
354
+
355
+ .review-column,
356
+ .preview {
357
+ display: grid;
358
+ gap: 14px;
359
+ padding: 18px;
360
+ border: 1px solid var(--line);
361
+ border-radius: 8px;
362
+ background: rgba(255, 255, 255, 0.9);
363
+ box-shadow: var(--shadow);
364
+ }
365
+
366
+ .section-heading {
367
+ display: flex;
368
+ align-items: center;
369
+ justify-content: space-between;
370
+ gap: 12px;
371
+ }
372
+
373
+ .section-heading span {
374
+ color: var(--muted);
375
+ font-size: 0.86rem;
376
+ font-weight: 800;
377
+ }
378
+
379
+ .finding-group {
380
+ display: grid;
381
+ gap: 10px;
382
+ margin-bottom: 16px;
383
+ }
384
+
385
+ .finding-group:last-child {
386
+ margin-bottom: 0;
387
+ }
388
+
389
+ .severity-heading {
390
+ display: flex;
391
+ align-items: center;
392
+ gap: 8px;
393
+ color: var(--muted);
394
+ font-size: 0.78rem;
395
+ font-weight: 900;
396
+ text-transform: uppercase;
397
+ }
398
+
399
+ .severity-dot {
400
+ width: 9px;
401
+ height: 9px;
402
+ border-radius: 99px;
403
+ background: var(--low);
404
+ }
405
+
406
+ .severity-dot.high {
407
+ background: var(--danger);
408
+ }
409
+
410
+ .severity-dot.medium {
411
+ background: var(--warning);
412
+ }
413
+
414
+ .finding {
415
+ display: grid;
416
+ gap: 6px;
417
+ padding: 12px;
418
+ border: 1px solid var(--line);
419
+ border-left: 4px solid var(--low);
420
+ border-radius: 8px;
421
+ background: #fbfcfc;
422
+ }
423
+
424
+ .finding.high {
425
+ border-left-color: var(--danger);
426
+ }
427
+
428
+ .finding.medium {
429
+ border-left-color: var(--warning);
430
+ }
431
+
432
+ .finding h4 {
433
+ margin: 0;
434
+ font-size: 0.95rem;
435
+ }
436
+
437
+ .finding p {
438
+ margin-bottom: 0;
439
+ color: var(--muted);
440
+ font-size: 0.88rem;
441
+ }
442
+
443
+ .snippet {
444
+ padding: 8px;
445
+ border-radius: 6px;
446
+ background: #eef3f2;
447
+ color: #344147;
448
+ font-size: 0.82rem;
449
+ }
450
+
451
+ .comment-form {
452
+ display: grid;
453
+ gap: 10px;
454
+ }
455
+
456
+ textarea {
457
+ width: 100%;
458
+ min-height: 92px;
459
+ resize: vertical;
460
+ border: 1px solid var(--line);
461
+ border-radius: 8px;
462
+ padding: 12px;
463
+ color: var(--ink);
464
+ background: #fbfcfc;
465
+ }
466
+
467
+ textarea:focus {
468
+ outline: 3px solid rgba(15, 118, 110, 0.18);
469
+ border-color: var(--accent);
470
+ }
471
+
472
+ input,
473
+ select {
474
+ width: 100%;
475
+ min-height: 38px;
476
+ border: 1px solid var(--line);
477
+ border-radius: 8px;
478
+ padding: 0 11px;
479
+ color: var(--ink);
480
+ background: #fbfcfc;
481
+ }
482
+
483
+ input:focus,
484
+ select:focus {
485
+ outline: 3px solid rgba(15, 118, 110, 0.18);
486
+ border-color: var(--accent);
487
+ }
488
+
489
+ .comments {
490
+ display: grid;
491
+ gap: 10px;
492
+ }
493
+
494
+ .comment {
495
+ padding: 12px;
496
+ border-radius: 8px;
497
+ background: #f3f7f6;
498
+ }
499
+
500
+ .comment strong {
501
+ display: block;
502
+ margin-bottom: 4px;
503
+ }
504
+
505
+ .comment time {
506
+ color: var(--muted);
507
+ font-size: 0.78rem;
508
+ }
509
+
510
+ .comment p {
511
+ margin: 8px 0 0;
512
+ white-space: pre-wrap;
513
+ }
514
+
515
+ .preview pre {
516
+ max-height: 480px;
517
+ margin: 0;
518
+ overflow: auto;
519
+ border-radius: 8px;
520
+ padding: 16px;
521
+ background: #162126;
522
+ color: #edf7f4;
523
+ font-family: "Cascadia Mono", Consolas, monospace;
524
+ font-size: 0.88rem;
525
+ line-height: 1.55;
526
+ white-space: pre-wrap;
527
+ }
528
+
529
+ .toast {
530
+ position: fixed;
531
+ right: 22px;
532
+ bottom: 22px;
533
+ max-width: min(420px, calc(100vw - 44px));
534
+ padding: 12px 14px;
535
+ border-radius: 8px;
536
+ color: #fff;
537
+ background: #172126;
538
+ box-shadow: var(--shadow);
539
+ font-weight: 700;
540
+ }
541
+
542
+ .toast.error {
543
+ background: var(--danger);
544
+ }
545
+
546
+ .quiet {
547
+ color: var(--muted);
548
+ }
549
+
550
+ .owner-fields,
551
+ .compact-form,
552
+ .assignment-form,
553
+ .reviewer-action-form {
554
+ display: grid;
555
+ gap: 10px;
556
+ }
557
+
558
+ .owner-fields {
559
+ grid-template-columns: 1fr 1fr;
560
+ }
561
+
562
+ .sidebar-tabs {
563
+ display: grid;
564
+ grid-template-columns: repeat(3, minmax(0, 1fr));
565
+ gap: 4px;
566
+ padding: 4px;
567
+ border: 1px solid var(--line);
568
+ border-radius: 8px;
569
+ background: #edf2f1;
570
+ }
571
+
572
+ .side-tab {
573
+ display: inline-flex;
574
+ min-height: 34px;
575
+ align-items: center;
576
+ justify-content: center;
577
+ gap: 6px;
578
+ border-radius: 6px;
579
+ color: var(--muted);
580
+ background: transparent;
581
+ font-size: 0.82rem;
582
+ font-weight: 800;
583
+ }
584
+
585
+ .side-tab.active {
586
+ color: var(--ink);
587
+ background: #fff;
588
+ box-shadow: 0 1px 4px rgba(23, 33, 38, 0.08);
589
+ }
590
+
591
+ .badge {
592
+ display: inline-grid;
593
+ min-width: 20px;
594
+ height: 20px;
595
+ place-items: center;
596
+ border-radius: 999px;
597
+ color: #fff;
598
+ background: var(--danger);
599
+ font-size: 0.72rem;
600
+ font-weight: 900;
601
+ }
602
+
603
+ .side-view {
604
+ display: grid;
605
+ gap: 14px;
606
+ }
607
+
608
+ .form-row {
609
+ display: flex;
610
+ flex-wrap: wrap;
611
+ gap: 10px;
612
+ }
613
+
614
+ .form-row > * {
615
+ flex: 1 1 150px;
616
+ }
617
+
618
+ .people-list,
619
+ .notification-list,
620
+ .assignment-list,
621
+ .timeline {
622
+ display: grid;
623
+ gap: 10px;
624
+ }
625
+
626
+ .person-card,
627
+ .notification-card,
628
+ .assignment-card {
629
+ display: grid;
630
+ gap: 8px;
631
+ padding: 12px;
632
+ border: 1px solid var(--line);
633
+ border-radius: 8px;
634
+ background: rgba(255, 255, 255, 0.86);
635
+ }
636
+
637
+ .notification-card.unread {
638
+ border-color: var(--accent);
639
+ box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.11);
640
+ }
641
+
642
+ .person-card small,
643
+ .notification-card small,
644
+ .assignment-card small {
645
+ display: block;
646
+ margin-top: 3px;
647
+ color: var(--muted);
648
+ font-size: 0.78rem;
649
+ }
650
+
651
+ .notification-card p {
652
+ margin-bottom: 0;
653
+ color: #344147;
654
+ font-size: 0.88rem;
655
+ }
656
+
657
+ .icon-row {
658
+ display: flex;
659
+ flex-wrap: wrap;
660
+ gap: 8px;
661
+ }
662
+
663
+ .tiny {
664
+ min-height: 30px;
665
+ padding: 0 10px;
666
+ font-size: 0.76rem;
667
+ }
668
+
669
+ .tiny-label {
670
+ align-self: center;
671
+ font-size: 0.78rem;
672
+ font-weight: 800;
673
+ }
674
+
675
+ .danger-text {
676
+ color: var(--danger);
677
+ }
678
+
679
+ .owner-line {
680
+ margin: 8px 0 0;
681
+ color: var(--muted);
682
+ font-size: 0.9rem;
683
+ }
684
+
685
+ .assignment-panel {
686
+ box-shadow: none;
687
+ }
688
+
689
+ .check-grid {
690
+ display: grid;
691
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
692
+ gap: 10px;
693
+ }
694
+
695
+ .check-card {
696
+ display: grid;
697
+ grid-template-columns: 22px minmax(0, 1fr);
698
+ gap: 8px;
699
+ align-items: start;
700
+ padding: 10px;
701
+ border: 1px solid var(--line);
702
+ border-radius: 8px;
703
+ background: #fbfcfc;
704
+ }
705
+
706
+ .check-card input {
707
+ width: 18px;
708
+ min-height: 18px;
709
+ margin-top: 2px;
710
+ padding: 0;
711
+ }
712
+
713
+ .check-card small {
714
+ display: block;
715
+ margin-top: 2px;
716
+ color: var(--muted);
717
+ font-size: 0.78rem;
718
+ }
719
+
720
+ .assignment-card {
721
+ grid-template-columns: minmax(0, 1fr) auto;
722
+ align-items: center;
723
+ }
724
+
725
+ .assignment-card > small {
726
+ grid-column: 1 / -1;
727
+ }
728
+
729
+ .status-chip {
730
+ display: inline-flex;
731
+ min-height: 28px;
732
+ align-items: center;
733
+ justify-content: center;
734
+ padding: 0 10px;
735
+ border-radius: 999px;
736
+ color: #44515a;
737
+ background: #e9eeee;
738
+ font-size: 0.76rem;
739
+ font-weight: 900;
740
+ white-space: nowrap;
741
+ }
742
+
743
+ .status-chip.commented,
744
+ .status-chip.pending {
745
+ color: var(--accent-dark);
746
+ background: #dff2ee;
747
+ }
748
+
749
+ .status-chip.changes_requested {
750
+ color: #823b00;
751
+ background: #ffe6c7;
752
+ }
753
+
754
+ .status-chip.approved {
755
+ color: #0d5d36;
756
+ background: #dff6e9;
757
+ }
758
+
759
+ .muted-panel {
760
+ opacity: 0.62;
761
+ }
762
+
763
+ .timeline-item {
764
+ display: grid;
765
+ grid-template-columns: 16px minmax(0, 1fr);
766
+ gap: 10px;
767
+ }
768
+
769
+ .timeline-item > span {
770
+ width: 10px;
771
+ height: 10px;
772
+ margin-top: 7px;
773
+ border-radius: 999px;
774
+ background: var(--accent);
775
+ box-shadow: 0 0 0 4px rgba(15, 118, 110, 0.12);
776
+ }
777
+
778
+ .timeline-item div {
779
+ padding: 10px 12px;
780
+ border: 1px solid var(--line);
781
+ border-radius: 8px;
782
+ background: #fbfcfc;
783
+ }
784
+
785
+ .timeline-item p {
786
+ margin: 4px 0;
787
+ color: #344147;
788
+ font-size: 0.88rem;
789
+ }
790
+
791
+ .timeline-item time {
792
+ color: var(--muted);
793
+ font-size: 0.78rem;
794
+ }
795
+
796
+ @media (max-width: 980px) {
797
+ .app-shell {
798
+ grid-template-columns: 1fr;
799
+ }
800
+
801
+ .sidebar {
802
+ border-right: 0;
803
+ border-bottom: 1px solid var(--line);
804
+ }
805
+
806
+ .queue {
807
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
808
+ max-height: 340px;
809
+ }
810
+
811
+ .review-grid {
812
+ grid-template-columns: 1fr;
813
+ }
814
+ }
815
+
816
+ @media (max-width: 640px) {
817
+ .sidebar,
818
+ .workspace {
819
+ padding: 18px;
820
+ }
821
+
822
+ .filters {
823
+ grid-template-columns: repeat(2, 1fr);
824
+ }
825
+
826
+ .owner-fields {
827
+ grid-template-columns: 1fr;
828
+ }
829
+
830
+ .document-header {
831
+ display: grid;
832
+ }
833
+
834
+ .actions {
835
+ display: grid;
836
+ grid-template-columns: 1fr;
837
+ }
838
+ }
style.css DELETED
@@ -1,28 +0,0 @@
1
- body {
2
- padding: 2rem;
3
- font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;
4
- }
5
-
6
- h1 {
7
- font-size: 16px;
8
- margin-top: 0;
9
- }
10
-
11
- p {
12
- color: rgb(107, 114, 128);
13
- font-size: 15px;
14
- margin-bottom: 10px;
15
- margin-top: 5px;
16
- }
17
-
18
- .card {
19
- max-width: 620px;
20
- margin: 0 auto;
21
- padding: 16px;
22
- border: 1px solid lightgray;
23
- border-radius: 16px;
24
- }
25
-
26
- .card p:last-child {
27
- margin-bottom: 0;
28
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/README.md ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tests
2
+
3
+ This deployment repo would normally carry no tests — upstream has them, and a
4
+ copy-and-push pipeline has little to verify. These exist because of one thing:
5
+ `overlay/sdr-api-core.js` is a hand-written JavaScript port of upstream's
6
+ 1,200-line Python server, and a port that drifts from the server it mirrors makes
7
+ the Space lie about what the tool does.
8
+
9
+ Nothing else in the build would notice that drift. These two suites do.
10
+
11
+ ```powershell
12
+ node tests\parity\run-parity.mjs # the port vs. the real app.py
13
+ node tests\browser\run-browser-check.mjs # the built site in a real browser
14
+ ```
15
+
16
+ Both run automatically in `scripts\deploy.ps1` before anything is pushed, since a
17
+ Static Space goes live the instant the push lands.
18
+
19
+ ## parity/ — is the port the same program?
20
+
21
+ `run-parity.mjs` replays one 67-request workflow twice and diffs the results:
22
+
23
+ - **The reference.** `reference.py` imports the vendored `app.py` from `app/`,
24
+ points its storage at a temporary directory, replaces `utc_now` and `uuid4`
25
+ with counters, and serves it over real HTTP on a single-threaded server.
26
+ - **The port.** `run-parity.mjs` loads `overlay/sdr-api-core.js` in Node with an
27
+ in-memory store and the same counters.
28
+
29
+ Then it compares every response status, every response body, the SHA-256 of the
30
+ downloaded bytes, the final record store, and the list of stored uploads.
31
+
32
+ Two details do most of the work:
33
+
34
+ - **Sequential timestamps and ids.** Because the clock advances one second per
35
+ call and ids count up from 1, the port has to *call* them the same number of
36
+ times in the same order. A missing `utc_now()` or an extra `uuid4()` — easy to
37
+ introduce, since Python builds its migration `defaults` dict eagerly and
38
+ consumes an id whether it uses one or not — becomes a visible mismatch instead
39
+ of a value nobody compares.
40
+ - **A JSON round-trip on every load and save.** `app.py` re-reads its file per
41
+ request, so a handler that mutates a record and then fails without saving
42
+ throws the change away. The in-memory store copies on load and save for the
43
+ same reason; handing out a live object would let those changes stick and hide
44
+ the difference.
45
+
46
+ ### The corpus
47
+
48
+ `corpus/` is committed and covers the rubric and the text pipeline:
49
+
50
+ | File | What it is for |
51
+ | --- | --- |
52
+ | `clean-policy.md` | All six required sections, long enough, no findings |
53
+ | `messy-draft.md` | Every placeholder form, two vague phrases, an overlong sentence, missing sections |
54
+ | `tiny.txt` | Short-document and every missing-section finding at once |
55
+ | `unicode.md` | Word counting across scripts, apostrophes, hyphens, and combining marks — where Python's Unicode-aware `\w` and JavaScript's ASCII `\w` would otherwise disagree |
56
+ | `whitespace.txt` | Rejected: no readable text |
57
+ | `notes.rtf` | Rejected: unsupported type |
58
+
59
+ `.corpus/` is generated by `reference.py` on each run and gitignored, because the
60
+ fixtures are binary or encoding-specific: a deflated DOCX, a stored DOCX, a ZIP
61
+ with no `word/document.xml`, a file that is not a ZIP at all, UTF-16 with a BOM,
62
+ cp1252 with bytes that are not valid UTF-8, and an empty file.
63
+
64
+ `corpus/**` is marked `-text` in `.gitattributes`. One rubric rule counts
65
+ characters between sentence terminators, so a CRLF checkout would change a
66
+ finding.
67
+
68
+ ### Accepted divergences
69
+
70
+ `ACCEPTED_DIVERGENCES` in `run-parity.mjs` lists differences that are correct,
71
+ each with its reason, and prints them on every run rather than dropping them.
72
+ There is currently one: `mimetypes.guess_type` returns
73
+ `application/octet-stream` for `.docx` on a Windows machine with no Office
74
+ mapping, where the port always sends the real OOXML type.
75
+
76
+ Add to that list only for a difference you can justify in a sentence. Anything
77
+ not on it fails the run.
78
+
79
+ ## browser/ — does it work as a page?
80
+
81
+ The parity suite runs the port in Node, so it says nothing about the parts
82
+ between the port and the browser. `run-browser-check.mjs` serves the repository
83
+ root over HTTP — plainly, with no SPA fallback, the way a Static Space does —
84
+ opens it in headless Chromium through the DevTools protocol, and drives the real
85
+ UI: upload, review, add a reviewer, assign, approve, download, reload.
86
+
87
+ It checks the things only a browser can prove:
88
+
89
+ - both overlay scripts loaded, in order, before `app.js` ran
90
+ - upstream's `XMLHttpRequest` calls are answered locally
91
+ - IndexedDB keeps the workspace across a reload
92
+ - the Download button produces a file instead of navigating to a path that does
93
+ not exist on a static host
94
+ - no console errors anywhere in the run
95
+
96
+ It talks the DevTools protocol directly instead of adding a browser-automation
97
+ dependency this repo otherwise has no use for. It finds Edge or Chrome from the
98
+ usual Windows install paths; set `BROWSER` to override, and pass `--headed` to
99
+ watch it happen.
100
+
101
+ One quirk worth knowing: approving a document that still has findings goes
102
+ through `window.confirm`, and an unanswered dialog blocks the renderer — including
103
+ the evaluation waiting on it. The client accepts the dialog over CDP rather than
104
+ stubbing `confirm` in the page, so the real code path runs.
105
+
106
+ ## When a test fails after an upstream change
107
+
108
+ That is the intended outcome, not a broken test. `build-static.ps1` will already
109
+ have refused to build for the same reason. Read the upstream diff, carry the
110
+ behavior into `overlay/sdr-api-core.js`, re-run both suites, then acknowledge the
111
+ change with `.\scripts\build-static.ps1 -AcceptUpstreamChanges`.
tests/browser/run-browser-check.mjs ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Drive the built site in a real browser and check the whole review workflow.
3
+ *
4
+ * The parity tests prove overlay/sdr-api-core.js behaves like app.py, but they
5
+ * run in Node with an in-memory store. Everything between the port and the page
6
+ * is untested by them:
7
+ *
8
+ * - the script tags scripts/build-static.ps1 inserts, and their order
9
+ * - the XMLHttpRequest interception upstream's app.js actually goes through
10
+ * - IndexedDB, including whether records survive a reload
11
+ * - the Download button, which upstream implements as a navigation
12
+ *
13
+ * So this serves the repository root over HTTP, opens it in headless Chromium
14
+ * (via Microsoft Edge, which ships with Windows), runs an upload -> review ->
15
+ * assign -> approve workflow through the real UI, and asserts on the rendered
16
+ * DOM. It talks the DevTools protocol directly rather than pulling in a browser
17
+ * automation dependency, which this deployment repo otherwise does not need.
18
+ *
19
+ * node tests/browser/run-browser-check.mjs
20
+ * node tests/browser/run-browser-check.mjs --headed # watch it happen
21
+ *
22
+ * Set BROWSER to point at a different Chromium binary.
23
+ */
24
+
25
+ import { spawn } from "node:child_process";
26
+ import { createServer } from "node:http";
27
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
28
+ import { tmpdir } from "node:os";
29
+ import path from "node:path";
30
+ import { fileURLToPath } from "node:url";
31
+
32
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
33
+ const REPO_ROOT = path.resolve(HERE, "..", "..");
34
+ const headed = process.argv.includes("--headed");
35
+
36
+ const CANDIDATE_BROWSERS = [
37
+ process.env.BROWSER,
38
+ "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
39
+ "C:/Program Files/Microsoft/Edge/Application/msedge.exe",
40
+ "C:/Program Files/Google/Chrome/Application/chrome.exe",
41
+ "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"
42
+ ].filter(Boolean);
43
+
44
+ const CONTENT_TYPES = {
45
+ ".html": "text/html; charset=utf-8",
46
+ ".js": "text/javascript; charset=utf-8",
47
+ ".css": "text/css; charset=utf-8",
48
+ ".json": "application/json; charset=utf-8",
49
+ ".md": "text/markdown; charset=utf-8",
50
+ ".txt": "text/plain; charset=utf-8"
51
+ };
52
+
53
+ // ------------------------------------------------------------- static server
54
+
55
+ /**
56
+ * Serve the repository root the way a Static Space does.
57
+ *
58
+ * Deliberately plain: no SPA fallback and no rewrites, so a request for a path
59
+ * the build did not emit fails here exactly as it would on Hugging Face.
60
+ */
61
+ function startStaticServer() {
62
+ const server = createServer((request, response) => {
63
+ const requested = decodeURIComponent(request.url.split("?")[0]);
64
+ const relative = requested === "/" ? "index.html" : requested.replace(/^\/+/, "");
65
+ const target = path.join(REPO_ROOT, relative);
66
+
67
+ if (!target.startsWith(REPO_ROOT) || !existsSync(target)) {
68
+ response.writeHead(404, { "Content-Type": "text/plain" });
69
+ response.end("not found");
70
+ return;
71
+ }
72
+ response.writeHead(200, {
73
+ "Content-Type": CONTENT_TYPES[path.extname(target)] || "application/octet-stream"
74
+ });
75
+ response.end(readFileSync(target));
76
+ });
77
+
78
+ return new Promise((resolve) => {
79
+ server.listen(0, "127.0.0.1", () => {
80
+ resolve({ server, origin: `http://127.0.0.1:${server.address().port}` });
81
+ });
82
+ });
83
+ }
84
+
85
+ // ------------------------------------------------------------- DevTools client
86
+
87
+ async function waitFor(check, description, timeoutMs = 15000, intervalMs = 100) {
88
+ const deadline = Date.now() + timeoutMs;
89
+ for (;;) {
90
+ const value = await check();
91
+ if (value) return value;
92
+ if (Date.now() > deadline) throw new Error(`Timed out waiting for ${description}.`);
93
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
94
+ }
95
+ }
96
+
97
+ function launchBrowser(userDataDir) {
98
+ const binary = CANDIDATE_BROWSERS.find((candidate) => existsSync(candidate));
99
+ if (!binary) {
100
+ throw new Error(
101
+ "No Chromium-based browser found. Set BROWSER to a chrome.exe or msedge.exe path."
102
+ );
103
+ }
104
+
105
+ const args = [
106
+ "--remote-debugging-port=0",
107
+ `--user-data-dir=${userDataDir}`,
108
+ "--no-first-run",
109
+ "--no-default-browser-check",
110
+ "--disable-gpu",
111
+ "--disable-search-engine-choice-screen",
112
+ "about:blank"
113
+ ];
114
+ if (!headed) args.unshift("--headless=new");
115
+
116
+ const child = spawn(binary, args, { stdio: ["ignore", "pipe", "pipe"] });
117
+ child.stdout.resume();
118
+ child.stderr.resume();
119
+ return { child, binary };
120
+ }
121
+
122
+ async function connect(userDataDir) {
123
+ const portFile = path.join(userDataDir, "DevToolsActivePort");
124
+ const port = await waitFor(
125
+ () => {
126
+ if (!existsSync(portFile)) return null;
127
+ const first = readFileSync(portFile, "utf-8").split("\n")[0].trim();
128
+ return first ? Number(first) : null;
129
+ },
130
+ "the browser's debugging port"
131
+ );
132
+
133
+ const target = await waitFor(async () => {
134
+ const response = await fetch(`http://127.0.0.1:${port}/json/list`);
135
+ const targets = await response.json();
136
+ return targets.find((item) => item.type === "page" && item.webSocketDebuggerUrl) || null;
137
+ }, "a page target");
138
+
139
+ const socket = new WebSocket(target.webSocketDebuggerUrl);
140
+ await new Promise((resolve, reject) => {
141
+ socket.onopen = resolve;
142
+ socket.onerror = () => reject(new Error("Could not open the DevTools socket."));
143
+ });
144
+
145
+ let nextId = 0;
146
+ const pending = new Map();
147
+ const events = [];
148
+
149
+ socket.onmessage = (message) => {
150
+ const payload = JSON.parse(message.data);
151
+ if (payload.id !== undefined) {
152
+ const settle = pending.get(payload.id);
153
+ pending.delete(payload.id);
154
+ if (!settle) return;
155
+ if (payload.error) settle.reject(new Error(`${payload.error.message} (${settle.method})`));
156
+ else settle.resolve(payload.result);
157
+ return;
158
+ }
159
+ events.push(payload);
160
+
161
+ // Approving a document that still has findings goes through
162
+ // window.confirm, and an unanswered dialog blocks the renderer - including
163
+ // the Runtime.evaluate that is waiting on the result. Accept it here so the
164
+ // real code path runs rather than stubbing the dialog away in the page.
165
+ if (payload.method === "Page.javascriptDialogOpening") {
166
+ send("Page.handleJavaScriptDialog", { accept: true });
167
+ }
168
+ };
169
+
170
+ function send(method, params = {}) {
171
+ const id = (nextId += 1);
172
+ return new Promise((resolve, reject) => {
173
+ pending.set(id, { resolve, reject, method });
174
+ socket.send(JSON.stringify({ id, method, params }));
175
+ });
176
+ }
177
+
178
+ return { send, events, close: () => socket.close() };
179
+ }
180
+
181
+ // ------------------------------------------------------------------ assertions
182
+
183
+ const checks = [];
184
+
185
+ function check(description, passed, detail) {
186
+ checks.push({ description, passed, detail });
187
+ const mark = passed ? "ok " : "FAIL";
188
+ process.stdout.write(` ${mark} ${description}${detail && !passed ? ` -- ${detail}` : ""}\n`);
189
+ }
190
+
191
+ /**
192
+ * Evaluate an expression in the page and return its value.
193
+ *
194
+ * `awaitPromise` is on because every step here waits on the local API, which is
195
+ * asynchronous even though it never touches the network.
196
+ */
197
+ async function evaluate(client, expression) {
198
+ const result = await client.send("Runtime.evaluate", {
199
+ expression: `(async () => { ${expression} })()`,
200
+ awaitPromise: true,
201
+ returnByValue: true
202
+ });
203
+ if (result.exceptionDetails) {
204
+ const thrown = result.exceptionDetails.exception;
205
+ throw new Error(`Page threw: ${thrown?.description || thrown?.value || "unknown error"}`);
206
+ }
207
+ return result.result.value;
208
+ }
209
+
210
+ // The page-side helper the steps below build on. Kept as one string so it can be
211
+ // injected once and reused by every Runtime.evaluate call.
212
+ const PAGE_HELPERS = `
213
+ window.__t = {
214
+ text: (selector) => (document.querySelector(selector) || {}).textContent || "",
215
+ visible: (selector) => {
216
+ const node = document.querySelector(selector);
217
+ return Boolean(node) && !node.classList.contains("hidden");
218
+ },
219
+ settle: (predicate, label, timeout = 8000) => new Promise((resolve, reject) => {
220
+ const deadline = Date.now() + timeout;
221
+ const tick = () => {
222
+ let value = false;
223
+ try { value = predicate(); } catch (error) { value = false; }
224
+ if (value) { resolve(true); return; }
225
+ if (Date.now() > deadline) { reject(new Error("timed out waiting for " + label)); return; }
226
+ setTimeout(tick, 50);
227
+ };
228
+ tick();
229
+ }),
230
+ upload: (name, body) => {
231
+ const file = new File([body], name, { type: "text/markdown" });
232
+ const transfer = new DataTransfer();
233
+ transfer.items.add(file);
234
+ const input = document.querySelector("#fileInput");
235
+ input.files = transfer.files;
236
+ input.dispatchEvent(new Event("change", { bubbles: true }));
237
+ }
238
+ };
239
+ `;
240
+
241
+ const SAMPLE_DOCUMENT = `# Access Review
242
+
243
+ ## Purpose
244
+ Confirm that quarterly access reviews happen on schedule.
245
+
246
+ ## Scope
247
+ All production systems.
248
+
249
+ ## Owner
250
+ Security Operations.
251
+
252
+ ## Date
253
+ Effective date: 2026 April 01.
254
+
255
+ ## Risk
256
+ Stale accounts are the most common breach path.
257
+
258
+ ## Approval
259
+ Approved by the security lead.
260
+
261
+ TODO: attach the evidence export.
262
+ `;
263
+
264
+ // ------------------------------------------------------------------------ main
265
+
266
+ async function main() {
267
+ if (!existsSync(path.join(REPO_ROOT, "index.html"))) {
268
+ throw new Error("No index.html at the repository root. Run .\\scripts\\build-static.ps1 first.");
269
+ }
270
+
271
+ const { server, origin } = await startStaticServer();
272
+ const userDataDir = mkdtempSync(path.join(tmpdir(), "sdr-browser-"));
273
+ const { child, binary } = launchBrowser(userDataDir);
274
+ let client = null;
275
+
276
+ try {
277
+ process.stdout.write(`Browser: ${binary}\nServing: ${REPO_ROOT}\n\n`);
278
+ client = await connect(userDataDir);
279
+
280
+ await client.send("Page.enable");
281
+ await client.send("Runtime.enable");
282
+ await client.send("Log.enable");
283
+
284
+ await client.send("Page.navigate", { url: origin + "/" });
285
+ await waitFor(
286
+ () => client.events.some((event) => event.method === "Page.loadEventFired"),
287
+ "the page to load"
288
+ );
289
+
290
+ // --- the overlay loaded, in the right order --------------------------
291
+ await evaluate(client, PAGE_HELPERS + " return true;");
292
+
293
+ check(
294
+ "sdr-api-core.js and sdr-api-shim.js both loaded",
295
+ await evaluate(client, "return Boolean(window.SdrApiCore && window.__sdrApiShimInstalled);")
296
+ );
297
+ check(
298
+ "the shim replaced XMLHttpRequest before app.js ran",
299
+ await evaluate(client, "return window.XMLHttpRequest.name === 'ShimXMLHttpRequest';")
300
+ );
301
+
302
+ // --- the initial three requests were answered locally ---------------
303
+ await evaluate(client, "await window.__t.settle(() => window.__t.visible('#emptyState'), 'the empty state');");
304
+ check(
305
+ "the empty workspace rendered from the local API",
306
+ (await evaluate(client, "return window.__t.text('#documentList');")).includes("No documents")
307
+ );
308
+
309
+ // --- the demo framing ------------------------------------------------
310
+ // Load-bearing, not decoration: a visitor who takes this for a service and
311
+ // runs a real approval round through it loses the record when they clear
312
+ // their browser. See "What the demo cannot be" in DEPLOY.md.
313
+ check(
314
+ "a Demo badge sits next to the title and does not depend on dismissal",
315
+ (await evaluate(client, "return window.__t.text('.brand h1 .sdr-demo-badge');")) === "Demo"
316
+ );
317
+ const notice = await evaluate(
318
+ client,
319
+ `await window.__t.settle(() => Boolean(document.querySelector('aside[role=note]')), "the storage notice");
320
+ return document.querySelector("aside[role=note]").textContent;`
321
+ );
322
+ check(
323
+ "the first-load notice says it is a demo and where the data lives",
324
+ /demo/i.test(notice) && /browser/i.test(notice) && /run it locally/i.test(notice),
325
+ notice
326
+ );
327
+
328
+ // --- upload ---------------------------------------------------------
329
+ await evaluate(
330
+ client,
331
+ `document.querySelector("#ownerName").value = "Dana Owner";
332
+ window.__t.upload("Access Review.md", ${JSON.stringify(SAMPLE_DOCUMENT)});
333
+ await window.__t.settle(() => window.__t.visible("#documentPanel"), "the document panel");`
334
+ );
335
+ check(
336
+ "uploading a file opens it in the workspace",
337
+ (await evaluate(client, "return window.__t.text('#documentTitle');")) === "Access Review.md"
338
+ );
339
+ check(
340
+ "the word count came back from the local API",
341
+ /\d+ words/.test(await evaluate(client, "return window.__t.text('#wordCount');")),
342
+ await evaluate(client, "return window.__t.text('#wordCount');")
343
+ );
344
+ check(
345
+ "the owner name reached the record",
346
+ (await evaluate(client, "return window.__t.text('#ownerLine');")).includes("Dana Owner")
347
+ );
348
+
349
+ // --- review ---------------------------------------------------------
350
+ await evaluate(
351
+ client,
352
+ `document.querySelector("#reviewButton").click();
353
+ await window.__t.settle(() => !window.__t.text("#findingSummary").includes("Not reviewed"), "the review to run");`
354
+ );
355
+ const findingSummary = await evaluate(client, "return window.__t.text('#findingSummary');");
356
+ check(
357
+ "running the review reports the placeholder this document contains",
358
+ /[1-9]\d* high/.test(findingSummary),
359
+ findingSummary
360
+ );
361
+
362
+ // --- reviewers and assignment ---------------------------------------
363
+ await evaluate(
364
+ client,
365
+ `document.querySelector('[data-view="reviewers"]').click();
366
+ document.querySelector("#reviewerName").value = "Ada Lovelace";
367
+ document.querySelector("#reviewerEmail").value = "ada@example.com";
368
+ document.querySelector("#reviewerForm").dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
369
+ await window.__t.settle(() => window.__t.text("#reviewerList").includes("Ada Lovelace"), "the reviewer list");`
370
+ );
371
+ check("a reviewer can be added", true);
372
+
373
+ await evaluate(
374
+ client,
375
+ `const box = document.querySelector("#assignmentChoices input[type=checkbox]");
376
+ box.checked = true;
377
+ document.querySelector("#assignmentForm").dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
378
+ await window.__t.settle(() => window.__t.text("#assignmentList").includes("Ada Lovelace"), "the assignment list");`
379
+ );
380
+ check(
381
+ "assigning a reviewer moves the document into review",
382
+ (await evaluate(client, "return window.__t.text('#statusPill');")) === "In review",
383
+ await evaluate(client, "return window.__t.text('#statusPill');")
384
+ );
385
+ check(
386
+ "assigning queues a notification for the reviewer",
387
+ (await evaluate(client, "return window.__t.text('#notificationBadge');")) === "1",
388
+ await evaluate(client, "return window.__t.text('#notificationBadge');")
389
+ );
390
+
391
+ // --- approval -------------------------------------------------------
392
+ await evaluate(
393
+ client,
394
+ `document.querySelector("#reviewerSignature").value = "AL";
395
+ const form = document.querySelector("#reviewerActionForm");
396
+ const submit = form.querySelector('[data-reviewer-action="approve"]');
397
+ // The app reads event.submitter to tell its three buttons apart, and a
398
+ // synthetic SubmitEvent is the only way to set it.
399
+ form.dispatchEvent(new SubmitEvent("submit", { bubbles: true, cancelable: true, submitter: submit }));
400
+ await window.__t.settle(() => window.__t.text("#statusPill") === "Approved", "the approved status");`
401
+ );
402
+ check("a signed reviewer approval approves the document", true);
403
+ check(
404
+ "the activity timeline recorded the approval",
405
+ (await evaluate(client, "return window.__t.text('#activityTimeline');")).includes("Approved as AL")
406
+ );
407
+
408
+ // --- download -------------------------------------------------------
409
+ // The button navigates in upstream's code; the shim has to turn that into a
410
+ // blob download. Checking the location is unchanged is what proves it.
411
+ await client.send("Browser.setDownloadBehavior", {
412
+ behavior: "allow",
413
+ downloadPath: userDataDir,
414
+ eventsEnabled: true
415
+ });
416
+ await evaluate(client, `document.querySelector("#downloadButton").click(); return true;`);
417
+ const download = await waitFor(
418
+ () => client.events.find((event) => event.method === "Page.downloadWillBegin") || null,
419
+ "the download to start",
420
+ 8000
421
+ ).catch(() => null);
422
+ check(
423
+ "the Download button produces a file instead of navigating away",
424
+ Boolean(download) && download.params.suggestedFilename === "Access Review.md",
425
+ download ? download.params.suggestedFilename : "no download event"
426
+ );
427
+ check(
428
+ "the page did not navigate to the missing /api/ path",
429
+ (await evaluate(client, "return window.location.pathname;")) === "/"
430
+ );
431
+
432
+ // --- persistence ----------------------------------------------------
433
+ client.events.length = 0;
434
+ await client.send("Page.reload");
435
+ await waitFor(
436
+ () => client.events.some((event) => event.method === "Page.loadEventFired"),
437
+ "the reload"
438
+ );
439
+ await evaluate(client, PAGE_HELPERS + " return true;");
440
+ await evaluate(
441
+ client,
442
+ `await window.__t.settle(() => window.__t.text("#documentList").includes("Access Review"), "the reloaded document list");`
443
+ );
444
+ check("documents survive a reload (IndexedDB)", true);
445
+ check(
446
+ "the reloaded document is still approved",
447
+ (await evaluate(client, "return window.__t.text('#statusPill');")) === "Approved"
448
+ );
449
+
450
+ // --- no console errors ----------------------------------------------
451
+ const consoleErrors = client.events
452
+ .concat([])
453
+ .filter(
454
+ (event) =>
455
+ (event.method === "Runtime.consoleAPICalled" && event.params.type === "error") ||
456
+ (event.method === "Log.entryAdded" && event.params.entry.level === "error")
457
+ )
458
+ .map((event) =>
459
+ event.method === "Log.entryAdded"
460
+ ? event.params.entry.text
461
+ : (event.params.args[0] || {}).value
462
+ );
463
+ check("no console errors", consoleErrors.length === 0, consoleErrors.join(" | "));
464
+ } finally {
465
+ if (client) client.close();
466
+ child.kill();
467
+ server.close();
468
+ // The browser holds its profile briefly after exit; a failed cleanup is not
469
+ // a failed test.
470
+ try { rmSync(userDataDir, { recursive: true, force: true, maxRetries: 5 }); } catch { /* ignore */ }
471
+ }
472
+
473
+ const failed = checks.filter((item) => !item.passed);
474
+ process.stdout.write("\n");
475
+ if (failed.length === 0) {
476
+ process.stdout.write(`PASS ${checks.length} browser checks.\n`);
477
+ return 0;
478
+ }
479
+ process.stdout.write(`FAIL ${failed.length} of ${checks.length} browser checks.\n`);
480
+ return 1;
481
+ }
482
+
483
+ main().then(
484
+ (code) => process.exit(code),
485
+ (error) => {
486
+ process.stderr.write(`${error.stack || error.message}\n`);
487
+ process.exit(2);
488
+ }
489
+ );
tests/parity/corpus/clean-policy.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Vendor Access Policy
2
+
3
+ ## Purpose
4
+
5
+ This policy defines how the company grants, records, and withdraws vendor access
6
+ to internal systems. It exists so that every grant has a named requester, a
7
+ recorded justification, and a fixed end date that the security team can verify
8
+ without asking anyone.
9
+
10
+ ## Scope
11
+
12
+ This policy covers all third-party vendors with credentials to production or
13
+ staging systems. It does not cover employees, contractors on payroll, or guest
14
+ network access, each of which is governed by its own policy.
15
+
16
+ ## Owner
17
+
18
+ Security Operations owns this policy and reviews it every six months. Questions
19
+ go to the security operations queue, which is staffed during business hours.
20
+
21
+ ## Date
22
+
23
+ Effective date: 2026 March 01. Review date: 2026 September 01.
24
+
25
+ ## Risk
26
+
27
+ Unmanaged vendor credentials are the most common path to a breach in companies
28
+ of this size. A credential that outlives its purpose gives an attacker a valid
29
+ login that no alert will flag. Each grant therefore expires automatically after
30
+ ninety days.
31
+
32
+ ## Approval
33
+
34
+ Approved by the Chief Information Security Officer and the Head of Procurement.
35
+ Signature blocks for both roles appear on the final page of the signed copy held
36
+ by the legal team.
tests/parity/corpus/messy-draft.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Retention Standard (draft)
2
+
3
+ Owner: [insert owning team]
4
+
5
+ Support will be provided on a best effort basis, and escalation paths will be
6
+ documented as appropriate once the on-call rotation settles down.
7
+
8
+ TODO: decide whether backups count as retained copies.
9
+
10
+ Retention window: TBD
11
+
12
+ Signed: ______________________
13
+
14
+ Approver: {{approver_name}}
15
+
16
+ The retention window for operational telemetry has not been agreed yet because
17
+ the analytics team wants a longer window for seasonality work while the privacy
18
+ team wants the shortest window that still supports incident review, and until
19
+ those two positions are reconciled by the steering group this section cannot be
20
+ finalised or reviewed properly!
21
+
22
+ Remaining questions are tracked in the working document.
tests/parity/corpus/notes.rtf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {\rtf1\ansi\deff0{\fonttbl{\f0 Times New Roman;}}
2
+ \f0\fs24 Purpose: notes the app should refuse.\par
3
+ }
tests/parity/corpus/tiny.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ Draft only.
tests/parity/corpus/unicode.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Notes de révision
2
+
3
+ Purpose: vérifier le comptage des mots.
4
+ Scope: café, naïve, don't, well-known, e-mail, co-op.
5
+ Owner: Émile Zola
6
+ Date: 2026-03-01
7
+ Risk: 文書レビュー λόγος документ
8
+ Approval: sign-off requis ✅
9
+
10
+ Composed: café résumé.
11
+ Decomposed: café resumé.
12
+ Numbers: 2026, 3.14, 1⁄4, Ⅶ.
13
+ Quotes: “déjà vu” — l’accent aigu.
tests/parity/corpus/whitespace.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+
2
+
3
+
tests/parity/reference.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay scenario.json against the real app.py and print the results as JSON.
2
+
3
+ This is the reference half of the parity check. It imports the vendored copy of
4
+ upstream's server from ../../app, points its storage at a temporary directory,
5
+ and replaces its two sources of nondeterminism -- the clock and uuid4 -- with
6
+ counters so that a run is byte-for-byte reproducible.
7
+
8
+ Making the clock and the ids sequential does more than remove noise: it means
9
+ the port has to call them the same number of times, in the same order. A missing
10
+ utc_now() or an extra uuid4() in the JavaScript shows up as a mismatch instead
11
+ of hiding behind a value nobody compares.
12
+
13
+ Usage (normally driven by run-parity.mjs):
14
+
15
+ python tests/parity/reference.py # results to stdout
16
+ python tests/parity/reference.py --out x.json
17
+
18
+ Exit status is 0 when the scenario ran, regardless of the individual response
19
+ statuses -- rejections are part of what is being compared.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import hashlib
26
+ import io
27
+ import itertools
28
+ import json
29
+ import shutil
30
+ import sys
31
+ import tempfile
32
+ import threading
33
+ import urllib.error
34
+ import urllib.request
35
+ import zipfile
36
+ from datetime import datetime, timedelta, timezone
37
+ from http.server import HTTPServer
38
+ from pathlib import Path
39
+
40
+ HERE = Path(__file__).resolve().parent
41
+ REPO_ROOT = HERE.parent.parent
42
+ APP_DIR = REPO_ROOT / "app"
43
+ GENERATED_DIR = HERE / ".corpus"
44
+
45
+ # The instant the fake clock starts from. Any fixed value works; this one is
46
+ # obviously synthetic so it cannot be mistaken for a real timestamp.
47
+ CLOCK_START = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)
48
+
49
+ BOUNDARY = "----SimpleDocReviewParityBoundary"
50
+
51
+
52
+ # --------------------------------------------------------------- fixtures
53
+
54
+ def make_docx(paragraphs: list[str], compression: int) -> bytes:
55
+ """A minimal DOCX: one word/document.xml, stored or deflated."""
56
+ body = "".join(
57
+ f"<w:p><w:r><w:t>{paragraph}</w:t></w:r></w:p>" for paragraph in paragraphs
58
+ )
59
+ document_xml = (
60
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
61
+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
62
+ f"<w:body>{body}</w:body>"
63
+ "</w:document>"
64
+ )
65
+ buffer = io.BytesIO()
66
+ with zipfile.ZipFile(buffer, "w", compression) as archive:
67
+ # A real DOCX carries more parts than this; extract_docx_text reads only
68
+ # word/document.xml, so the extra parts would test nothing. One is added
69
+ # anyway so the archive has more than a single entry to walk past.
70
+ archive.writestr("[Content_Types].xml", "<Types/>")
71
+ archive.writestr("word/document.xml", document_xml)
72
+ return buffer.getvalue()
73
+
74
+
75
+ def write_generated_fixtures() -> None:
76
+ """Create the binary and encoding-specific fixtures scenario.json expects."""
77
+ GENERATED_DIR.mkdir(exist_ok=True)
78
+
79
+ paragraphs = [
80
+ "Purpose: confirm the DOCX text extractor agrees with the browser port.",
81
+ "Scope: paragraphs, entity escapes such as R&amp;D and &lt;brackets&gt;, and blank runs.",
82
+ "",
83
+ "Owner: Document Control",
84
+ "Date: 2026-04-01",
85
+ "Risk: a divergent extractor would change every finding downstream.",
86
+ "Approval: pending sign-off.",
87
+ ]
88
+ (GENERATED_DIR / "sample-deflate.docx").write_bytes(
89
+ make_docx(paragraphs, zipfile.ZIP_DEFLATED)
90
+ )
91
+ (GENERATED_DIR / "sample-stored.docx").write_bytes(
92
+ make_docx(paragraphs, zipfile.ZIP_STORED)
93
+ )
94
+
95
+ # A ZIP with no word/document.xml: "does not contain document text".
96
+ buffer = io.BytesIO()
97
+ with zipfile.ZipFile(buffer, "w") as archive:
98
+ archive.writestr("docProps/core.xml", "<coreProperties/>")
99
+ (GENERATED_DIR / "no-document-xml.docx").write_bytes(buffer.getvalue())
100
+
101
+ # Not a ZIP at all: BadZipFile -> "appears to be invalid".
102
+ (GENERATED_DIR / "broken.docx").write_bytes(b"PK\x03\x04 truncated nonsense")
103
+
104
+ # UTF-16 with a BOM, and cp1252 with bytes that are not valid UTF-8, so the
105
+ # decoder fallback chain in decode_text_bytes gets exercised.
106
+ (GENERATED_DIR / "utf16.txt").write_bytes(
107
+ (
108
+ "Purpose: check the UTF-16 decoder.\n"
109
+ "Owner: Encoding Team\n"
110
+ "Approval: signature on file.\n"
111
+ ).encode("utf-16")
112
+ )
113
+ # Curly quotes and an en dash become 0x93, 0x94, 0x96 in cp1252 - byte
114
+ # values that are not valid UTF-8, so decode_text_bytes has to fall through
115
+ # to its third attempt.
116
+ (GENERATED_DIR / "cp1252.txt").write_bytes(
117
+ (
118
+ "Purpose: check the cp1252 fallback.\n"
119
+ "Scope: “smart quotes” and an en dash – here.\n"
120
+ "Owner: Encoding Team\n"
121
+ "Approval: signature on file.\n"
122
+ ).encode("cp1252")
123
+ )
124
+
125
+ (GENERATED_DIR / "empty.txt").write_bytes(b"")
126
+
127
+
128
+ # ------------------------------------------------- deterministic app.py
129
+
130
+ def load_app(storage_root: Path):
131
+ """Import upstream's server with its clock, ids, and storage replaced."""
132
+ sys.path.insert(0, str(APP_DIR))
133
+ import app # noqa: E402 (the path has to be set up first)
134
+
135
+ clock = itertools.count()
136
+ ids = itertools.count(1)
137
+
138
+ def utc_now() -> str:
139
+ return (CLOCK_START + timedelta(seconds=next(clock))).isoformat(timespec="seconds")
140
+
141
+ class FakeUuid:
142
+ def __init__(self, value: int) -> None:
143
+ self.hex = f"{value:032x}"
144
+
145
+ class FakeUuidModule:
146
+ @staticmethod
147
+ def uuid4() -> FakeUuid:
148
+ return FakeUuid(next(ids))
149
+
150
+ app.utc_now = utc_now
151
+ app.uuid = FakeUuidModule()
152
+
153
+ app.DATA_DIR = storage_root / "data"
154
+ app.UPLOAD_DIR = storage_root / "uploads"
155
+ app.DB_PATH = app.DATA_DIR / "reviews.json"
156
+
157
+ # Keep the request log out of stdout, which carries the JSON results.
158
+ app.ReviewHandler.log_message = lambda self, fmt, *args: None
159
+ return app
160
+
161
+
162
+ def start_server(app_module):
163
+ """A single-threaded server, so requests cannot interleave the counters."""
164
+ server = HTTPServer(("127.0.0.1", 0), app_module.ReviewHandler)
165
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
166
+ thread.start()
167
+ return server, f"http://127.0.0.1:{server.server_address[1]}"
168
+
169
+
170
+ # ------------------------------------------------------------ scenario
171
+
172
+ def resolve(value, results):
173
+ """Substitute ${stepName|dotted.path} against earlier response bodies."""
174
+ if isinstance(value, str):
175
+ while True:
176
+ start = value.find("${")
177
+ if start < 0:
178
+ return value
179
+ end = value.index("}", start)
180
+ token = value[start + 2:end]
181
+ step, _, path = token.partition("|")
182
+ current = results[step]["json"]
183
+ for part in [p for p in path.split(".") if p]:
184
+ current = current[int(part)] if part.isdigit() else current[part]
185
+ value = value[:start] + str(current) + value[end + 1:]
186
+ if isinstance(value, list):
187
+ return [resolve(item, results) for item in value]
188
+ if isinstance(value, dict):
189
+ return {key: resolve(item, results) for key, item in value.items()}
190
+ return value
191
+
192
+
193
+ def multipart_body(filename: str, content: bytes, fields: dict) -> tuple[bytes, str]:
194
+ parts: list[bytes] = []
195
+ parts.append(
196
+ f'--{BOUNDARY}\r\nContent-Disposition: form-data; name="file"; '
197
+ f'filename="{filename}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode("utf-8")
198
+ + content
199
+ + b"\r\n"
200
+ )
201
+ for key, value in fields.items():
202
+ parts.append(
203
+ f'--{BOUNDARY}\r\nContent-Disposition: form-data; name="{key}"\r\n\r\n'.encode("utf-8")
204
+ + str(value).encode("utf-8")
205
+ + b"\r\n"
206
+ )
207
+ parts.append(f"--{BOUNDARY}--\r\n".encode("utf-8"))
208
+ return b"".join(parts), f"multipart/form-data; boundary={BOUNDARY}"
209
+
210
+
211
+ def request(base_url: str, step: dict, results: dict) -> dict:
212
+ path = resolve(step["path"], results)
213
+ method = step.get("method", "GET")
214
+ data = None
215
+ headers = {}
216
+
217
+ if "upload" in step:
218
+ upload = step["upload"]
219
+ content = (HERE / upload["file"]).read_bytes()
220
+ fields = resolve(upload.get("fields", {}), results)
221
+ data, content_type = multipart_body(upload["filename"], content, fields)
222
+ headers["Content-Type"] = content_type
223
+ elif "body" in step:
224
+ data = json.dumps(resolve(step["body"], results)).encode("utf-8")
225
+ headers["Content-Type"] = "application/json"
226
+
227
+ http_request = urllib.request.Request(base_url + path, data=data, method=method, headers=headers)
228
+ try:
229
+ with urllib.request.urlopen(http_request) as response:
230
+ status = response.status
231
+ payload = response.read()
232
+ response_headers = dict(response.headers.items())
233
+ except urllib.error.HTTPError as error:
234
+ status = error.code
235
+ payload = error.read()
236
+ response_headers = dict(error.headers.items())
237
+
238
+ record: dict = {
239
+ "name": step["name"],
240
+ "status": status,
241
+ "contentType": response_headers.get("Content-Type"),
242
+ }
243
+ if step.get("binary") and status == 200:
244
+ record["sha256"] = hashlib.sha256(payload).hexdigest()
245
+ record["bytes"] = len(payload)
246
+ record["contentDisposition"] = response_headers.get("Content-Disposition")
247
+ record["json"] = None
248
+ else:
249
+ record["json"] = json.loads(payload.decode("utf-8")) if payload else None
250
+ return record
251
+
252
+
253
+ def main() -> int:
254
+ parser = argparse.ArgumentParser(description=__doc__)
255
+ parser.add_argument("--out", help="write the results here instead of stdout")
256
+ args = parser.parse_args()
257
+
258
+ write_generated_fixtures()
259
+
260
+ scenario = json.loads((HERE / "scenario.json").read_text(encoding="utf-8"))
261
+ storage_root = Path(tempfile.mkdtemp(prefix="sdr-parity-"))
262
+
263
+ try:
264
+ app_module = load_app(storage_root)
265
+ server, base_url = start_server(app_module)
266
+ try:
267
+ results: dict = {}
268
+ ordered: list[dict] = []
269
+ for step in scenario["steps"]:
270
+ record = request(base_url, step, results)
271
+ results[step["name"]] = record
272
+ ordered.append(record)
273
+ finally:
274
+ server.shutdown()
275
+ server.server_close()
276
+
277
+ # The final store, so fields no response exposes (stored_name, the
278
+ # extracted text, per-assignment comment history) are compared too.
279
+ final_db = json.loads(app_module.DB_PATH.read_text(encoding="utf-8"))
280
+ uploads = sorted(path.name for path in app_module.UPLOAD_DIR.iterdir())
281
+
282
+ payload = {"steps": ordered, "db": final_db, "uploads": uploads}
283
+ text = json.dumps(payload, indent=2, sort_keys=True, ensure_ascii=False)
284
+ if args.out:
285
+ Path(args.out).write_text(text, encoding="utf-8")
286
+ else:
287
+ sys.stdout.write(text)
288
+ return 0
289
+ finally:
290
+ shutil.rmtree(storage_root, ignore_errors=True)
291
+
292
+
293
+ if __name__ == "__main__":
294
+ raise SystemExit(main())
tests/parity/run-parity.mjs ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Diff overlay/sdr-api-core.js against the real app.py.
3
+ *
4
+ * The overlay is a hand-written port of a 1,200-line Python server. Nothing in
5
+ * a copy-and-inject build would notice if the port drifted, so this replays one
6
+ * scenario through both implementations and compares everything: each response
7
+ * status, each response body, the download bytes, and the record store the two
8
+ * runs finish with.
9
+ *
10
+ * Both sides run off the same fixed clock and the same sequential ids, so the
11
+ * port has to call them the same number of times in the same order - a missing
12
+ * timestamp or an extra id is a mismatch rather than a value nobody checks.
13
+ *
14
+ * node tests/parity/run-parity.mjs # report and exit 0/1
15
+ * node tests/parity/run-parity.mjs --verbose # also list every step
16
+ *
17
+ * Set PYTHON to pick a different interpreter.
18
+ */
19
+
20
+ import { createHash } from "node:crypto";
21
+ import { spawnSync } from "node:child_process";
22
+ import { createRequire } from "node:module";
23
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
24
+ import { tmpdir } from "node:os";
25
+ import path from "node:path";
26
+ import { fileURLToPath } from "node:url";
27
+
28
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
29
+ const REPO_ROOT = path.resolve(HERE, "..", "..");
30
+ const require = createRequire(import.meta.url);
31
+
32
+ // Must match CLOCK_START in reference.py.
33
+ const CLOCK_START = Date.UTC(2026, 0, 2, 3, 4, 5);
34
+ const MAX_REPORTED_DIFFS = 40;
35
+
36
+ /**
37
+ * Differences that are correct, with the reason they are correct.
38
+ *
39
+ * These are reported separately rather than dropped, so the list stays short
40
+ * and reviewable. Anything not named here is a failure.
41
+ */
42
+ const ACCEPTED_DIVERGENCES = [
43
+ {
44
+ where: "downloadDocx.contentType",
45
+ reason:
46
+ "app.py asks mimetypes.guess_type, which on Windows reads the registry " +
47
+ "and returns application/octet-stream for .docx on a machine with no " +
48
+ "Office mapping. The overlay always sends the real OOXML type, because " +
49
+ "a browser-side answer that changes with the developer's machine would " +
50
+ "be worse than a fixed correct one."
51
+ }
52
+ ];
53
+
54
+ const verbose = process.argv.includes("--verbose");
55
+
56
+ // --------------------------------------------------------------- reference
57
+
58
+ function runReference() {
59
+ const scratch = mkdtempSync(path.join(tmpdir(), "sdr-parity-"));
60
+ const outPath = path.join(scratch, "reference.json");
61
+ const python = process.env.PYTHON || "python";
62
+ const result = spawnSync(python, [path.join(HERE, "reference.py"), "--out", outPath], {
63
+ cwd: REPO_ROOT,
64
+ encoding: "utf-8"
65
+ });
66
+
67
+ if (result.error) {
68
+ throw new Error(`Could not run ${python}: ${result.error.message}`);
69
+ }
70
+ if (result.status !== 0) {
71
+ throw new Error(`reference.py exited ${result.status}\n${result.stderr || result.stdout}`);
72
+ }
73
+ try {
74
+ return JSON.parse(readFileSync(outPath, "utf-8"));
75
+ } finally {
76
+ rmSync(scratch, { recursive: true, force: true });
77
+ }
78
+ }
79
+
80
+ // -------------------------------------------------------- the port under test
81
+
82
+ function two(value) {
83
+ return value < 10 ? "0" + value : String(value);
84
+ }
85
+
86
+ function createDeterministicEnvironment() {
87
+ let clock = 0;
88
+ let ids = 0;
89
+ return {
90
+ now() {
91
+ const when = new Date(CLOCK_START + clock * 1000);
92
+ clock += 1;
93
+ return (
94
+ when.getUTCFullYear() +
95
+ "-" + two(when.getUTCMonth() + 1) +
96
+ "-" + two(when.getUTCDate()) +
97
+ "T" + two(when.getUTCHours()) +
98
+ ":" + two(when.getUTCMinutes()) +
99
+ ":" + two(when.getUTCSeconds()) +
100
+ "+00:00"
101
+ );
102
+ },
103
+ uuidHex() {
104
+ ids += 1;
105
+ return ids.toString(16).padStart(32, "0");
106
+ },
107
+ counts() {
108
+ return { clock, ids };
109
+ }
110
+ };
111
+ }
112
+
113
+ /**
114
+ * An in-memory stand-in for data/reviews.json and uploads/.
115
+ *
116
+ * Every load and save round-trips through JSON on purpose. app.py re-reads the
117
+ * file per request, so a handler that mutates a record and then fails without
118
+ * calling save_db() throws its change away. Handing out a live object instead
119
+ * would quietly let those changes stick and hide the difference.
120
+ */
121
+ function createMemoryStore() {
122
+ let records = null;
123
+ const uploads = new Map();
124
+ return {
125
+ load: async () => (records === null ? null : JSON.parse(records)),
126
+ save: async (data) => { records = JSON.stringify(data); },
127
+ putUpload: async (name, bytes) => { uploads.set(name, Uint8Array.from(bytes)); },
128
+ getUpload: async (name) => uploads.get(name) || null,
129
+ snapshot: () => ({
130
+ db: records === null ? null : JSON.parse(records),
131
+ uploads: Array.from(uploads.keys()).sort()
132
+ })
133
+ };
134
+ }
135
+
136
+ // ------------------------------------------------------------- scenario replay
137
+
138
+ function resolvePlaceholders(value, results) {
139
+ if (typeof value === "string") {
140
+ let text = value;
141
+ for (;;) {
142
+ const start = text.indexOf("${");
143
+ if (start < 0) return text;
144
+ const end = text.indexOf("}", start);
145
+ const token = text.slice(start + 2, end);
146
+ const separator = token.indexOf("|");
147
+ const step = separator < 0 ? token : token.slice(0, separator);
148
+ const pointer = separator < 0 ? "" : token.slice(separator + 1);
149
+ let current = results[step].json;
150
+ for (const part of pointer.split(".").filter(Boolean)) {
151
+ current = /^\d+$/.test(part) ? current[Number(part)] : current[part];
152
+ }
153
+ text = text.slice(0, start) + String(current) + text.slice(end + 1);
154
+ }
155
+ }
156
+ if (Array.isArray(value)) return value.map((item) => resolvePlaceholders(item, results));
157
+ if (value && typeof value === "object") {
158
+ const mapped = {};
159
+ for (const [key, item] of Object.entries(value)) {
160
+ mapped[key] = resolvePlaceholders(item, results);
161
+ }
162
+ return mapped;
163
+ }
164
+ return value;
165
+ }
166
+
167
+ async function runPort(scenario) {
168
+ const Core = require(path.join(REPO_ROOT, "overlay", "sdr-api-core.js"));
169
+ const environment = createDeterministicEnvironment();
170
+ const store = createMemoryStore();
171
+ const api = Core.createApi({
172
+ store,
173
+ now: environment.now,
174
+ uuidHex: environment.uuidHex
175
+ });
176
+
177
+ const results = {};
178
+ const ordered = [];
179
+
180
+ for (const step of scenario.steps) {
181
+ const requestPath = resolvePlaceholders(step.path, results);
182
+ let body = null;
183
+
184
+ if (step.upload) {
185
+ const bytes = new Uint8Array(readFileSync(path.join(HERE, step.upload.file)));
186
+ const fields = {};
187
+ for (const [key, value] of Object.entries(
188
+ resolvePlaceholders(step.upload.fields || {}, results)
189
+ )) {
190
+ // The shim reads FormData values, which arrive already trimmed by
191
+ // upstream's app.js; app.py trims them in parse_multipart_upload.
192
+ fields[key] = String(value).trim();
193
+ }
194
+ body = { filename: step.upload.filename, bytes, fields };
195
+ } else if (step.body !== undefined) {
196
+ body = JSON.stringify(resolvePlaceholders(step.body, results));
197
+ }
198
+
199
+ const response = await api.handle(step.method || "GET", requestPath, body);
200
+ const record = {
201
+ name: step.name,
202
+ status: response.status,
203
+ contentType: response.headers["Content-Type"] || null
204
+ };
205
+ if (step.binary && response.status === 200) {
206
+ record.sha256 = createHash("sha256").update(response.bytes).digest("hex");
207
+ record.bytes = response.bytes.length;
208
+ record.contentDisposition = response.headers["Content-Disposition"] || null;
209
+ record.json = null;
210
+ } else {
211
+ record.json = response.body ? JSON.parse(response.body) : null;
212
+ }
213
+
214
+ results[step.name] = record;
215
+ ordered.push(record);
216
+ }
217
+
218
+ const snapshot = store.snapshot();
219
+ return { steps: ordered, db: snapshot.db, uploads: snapshot.uploads, counts: environment.counts() };
220
+ }
221
+
222
+ // ------------------------------------------------------------------- diffing
223
+
224
+ function diff(expected, actual, where, out) {
225
+ if (out.length >= MAX_REPORTED_DIFFS) return;
226
+
227
+ if (expected === actual) return;
228
+
229
+ const expectedType = expected === null ? "null" : Array.isArray(expected) ? "array" : typeof expected;
230
+ const actualType = actual === null ? "null" : Array.isArray(actual) ? "array" : typeof actual;
231
+
232
+ if (expectedType !== actualType) {
233
+ out.push({ where, expected, actual });
234
+ return;
235
+ }
236
+
237
+ if (expectedType === "array") {
238
+ if (expected.length !== actual.length) {
239
+ out.push({ where: `${where}.length`, expected: expected.length, actual: actual.length });
240
+ }
241
+ for (let index = 0; index < Math.max(expected.length, actual.length); index += 1) {
242
+ diff(expected[index], actual[index], `${where}[${index}]`, out);
243
+ }
244
+ return;
245
+ }
246
+
247
+ if (expectedType === "object") {
248
+ const keys = new Set([...Object.keys(expected), ...Object.keys(actual)]);
249
+ for (const key of keys) {
250
+ if (!(key in expected)) {
251
+ out.push({ where: `${where}.${key}`, expected: "<absent>", actual: actual[key] });
252
+ } else if (!(key in actual)) {
253
+ out.push({ where: `${where}.${key}`, expected: expected[key], actual: "<absent>" });
254
+ } else {
255
+ diff(expected[key], actual[key], `${where}.${key}`, out);
256
+ }
257
+ }
258
+ return;
259
+ }
260
+
261
+ out.push({ where, expected, actual });
262
+ }
263
+
264
+ function abbreviate(value) {
265
+ const text = typeof value === "string" ? JSON.stringify(value) : JSON.stringify(value);
266
+ if (text === undefined) return String(value);
267
+ return text.length > 160 ? text.slice(0, 157) + "..." : text;
268
+ }
269
+
270
+ // ---------------------------------------------------------------------- main
271
+
272
+ async function main() {
273
+ const scenario = JSON.parse(readFileSync(path.join(HERE, "scenario.json"), "utf-8"));
274
+
275
+ process.stdout.write(`Replaying ${scenario.steps.length} requests through app.py...\n`);
276
+ const reference = runReference();
277
+
278
+ process.stdout.write("Replaying them through overlay/sdr-api-core.js...\n");
279
+ const port = await runPort(scenario);
280
+
281
+ const differences = [];
282
+ const referenceByName = new Map(reference.steps.map((step) => [step.name, step]));
283
+
284
+ for (const step of port.steps) {
285
+ const expected = referenceByName.get(step.name);
286
+ if (!expected) {
287
+ differences.push({ where: step.name, expected: "<not run by reference>", actual: "" });
288
+ continue;
289
+ }
290
+ diff(expected, step, step.name, differences);
291
+ if (verbose) {
292
+ const marker = differences.length ? " " : " ";
293
+ process.stdout.write(` ${marker}${step.name.padEnd(34)} ${step.status}\n`);
294
+ }
295
+ }
296
+
297
+ diff(reference.db, port.db, "store", differences);
298
+ diff(reference.uploads, port.uploads, "uploads", differences);
299
+
300
+ const accepted = differences.filter((item) =>
301
+ ACCEPTED_DIVERGENCES.some((allowed) => allowed.where === item.where)
302
+ );
303
+ const failures = differences.filter((item) => !accepted.includes(item));
304
+
305
+ process.stdout.write("\n");
306
+ for (const item of accepted) {
307
+ const allowed = ACCEPTED_DIVERGENCES.find((entry) => entry.where === item.where);
308
+ process.stdout.write(`NOTE accepted divergence at ${item.where}\n`);
309
+ process.stdout.write(` app.py: ${abbreviate(item.expected)}\n`);
310
+ process.stdout.write(` overlay: ${abbreviate(item.actual)}\n`);
311
+ process.stdout.write(` ${allowed.reason}\n\n`);
312
+ }
313
+
314
+ differences.length = 0;
315
+ differences.push(...failures);
316
+
317
+ if (differences.length === 0) {
318
+ process.stdout.write(
319
+ `PASS ${port.steps.length} responses, the record store, and ${port.uploads.length} stored uploads all match app.py.\n`
320
+ );
321
+ process.stdout.write(
322
+ ` (${port.counts.clock} timestamps and ${port.counts.ids} ids consumed, in the same order.)\n`
323
+ );
324
+ return 0;
325
+ }
326
+
327
+ process.stdout.write(`FAIL ${differences.length} difference(s) from app.py:\n\n`);
328
+ for (const item of differences.slice(0, MAX_REPORTED_DIFFS)) {
329
+ process.stdout.write(` ${item.where}\n`);
330
+ process.stdout.write(` app.py: ${abbreviate(item.expected)}\n`);
331
+ process.stdout.write(` overlay: ${abbreviate(item.actual)}\n`);
332
+ }
333
+ if (differences.length > MAX_REPORTED_DIFFS) {
334
+ process.stdout.write(`\n ...and more (reporting capped at ${MAX_REPORTED_DIFFS}).\n`);
335
+ }
336
+ return 1;
337
+ }
338
+
339
+ main().then(
340
+ (code) => process.exit(code),
341
+ (error) => {
342
+ process.stderr.write(`${error.stack || error.message}\n`);
343
+ process.exit(2);
344
+ }
345
+ );
tests/parity/scenario.json ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_comment": [
3
+ "The request sequence both implementations replay: app.py behind a real",
4
+ "HTTP server, and overlay/sdr-api-core.js in Node. Every response is",
5
+ "compared field by field, and so is the record store they end up with.",
6
+ "",
7
+ "Placeholders take the form ${stepName|dotted.path} and read a value out of",
8
+ "an earlier step's response body, so the scenario never hard-codes an id.",
9
+ "",
10
+ "Files under corpus/ are committed. Files under .corpus/ are generated by",
11
+ "reference.py, because they are binary or encoding-specific: DOCX archives,",
12
+ "UTF-16, and cp1252."
13
+ ],
14
+ "steps": [
15
+ { "name": "emptyDocuments", "method": "GET", "path": "/api/documents" },
16
+ { "name": "emptyReviewers", "method": "GET", "path": "/api/reviewers" },
17
+ { "name": "emptyNotifications", "method": "GET", "path": "/api/notifications" },
18
+
19
+ {
20
+ "name": "uploadClean",
21
+ "method": "POST",
22
+ "path": "/api/upload",
23
+ "upload": {
24
+ "file": "corpus/clean-policy.md",
25
+ "filename": "Clean Policy.md",
26
+ "fields": {
27
+ "owner_name": "Dana Owner",
28
+ "owner_email": "dana@example.com",
29
+ "owner_slack": "@dana",
30
+ "owner_teams": "Dana O."
31
+ }
32
+ }
33
+ },
34
+ {
35
+ "name": "uploadMessy",
36
+ "method": "POST",
37
+ "path": "/api/upload",
38
+ "upload": {
39
+ "file": "corpus/messy-draft.md",
40
+ "filename": "../Messy Draft!.md",
41
+ "fields": { "owner_name": "", "owner_email": "", "owner_slack": "", "owner_teams": "" }
42
+ }
43
+ },
44
+ {
45
+ "name": "uploadTiny",
46
+ "method": "POST",
47
+ "path": "/api/upload",
48
+ "upload": { "file": "corpus/tiny.txt", "filename": "tiny.txt", "fields": {} }
49
+ },
50
+ {
51
+ "name": "uploadUnicode",
52
+ "method": "POST",
53
+ "path": "/api/upload",
54
+ "upload": { "file": "corpus/unicode.md", "filename": "unicode.md", "fields": { "owner_name": "Émile" } }
55
+ },
56
+ {
57
+ "name": "uploadDocxDeflate",
58
+ "method": "POST",
59
+ "path": "/api/upload",
60
+ "upload": { "file": ".corpus/sample-deflate.docx", "filename": "sample-deflate.docx", "fields": {} }
61
+ },
62
+ {
63
+ "name": "uploadDocxStored",
64
+ "method": "POST",
65
+ "path": "/api/upload",
66
+ "upload": { "file": ".corpus/sample-stored.docx", "filename": "sample-stored.docx", "fields": {} }
67
+ },
68
+ {
69
+ "name": "uploadUtf16",
70
+ "method": "POST",
71
+ "path": "/api/upload",
72
+ "upload": { "file": ".corpus/utf16.txt", "filename": "utf16.txt", "fields": {} }
73
+ },
74
+ {
75
+ "name": "uploadCp1252",
76
+ "method": "POST",
77
+ "path": "/api/upload",
78
+ "upload": { "file": ".corpus/cp1252.txt", "filename": "cp1252.txt", "fields": {} }
79
+ },
80
+
81
+ {
82
+ "name": "rejectUnsupportedType",
83
+ "method": "POST",
84
+ "path": "/api/upload",
85
+ "upload": { "file": "corpus/notes.rtf", "filename": "notes.rtf", "fields": {} }
86
+ },
87
+ {
88
+ "name": "rejectBlankDocument",
89
+ "method": "POST",
90
+ "path": "/api/upload",
91
+ "upload": { "file": "corpus/whitespace.txt", "filename": "whitespace.txt", "fields": {} }
92
+ },
93
+ {
94
+ "name": "rejectCorruptDocx",
95
+ "method": "POST",
96
+ "path": "/api/upload",
97
+ "upload": { "file": ".corpus/broken.docx", "filename": "broken.docx", "fields": {} }
98
+ },
99
+ {
100
+ "name": "rejectDocxWithoutBody",
101
+ "method": "POST",
102
+ "path": "/api/upload",
103
+ "upload": { "file": ".corpus/no-document-xml.docx", "filename": "no-document-xml.docx", "fields": {} }
104
+ },
105
+ {
106
+ "name": "rejectEmptyFile",
107
+ "method": "POST",
108
+ "path": "/api/upload",
109
+ "upload": { "file": ".corpus/empty.txt", "filename": "empty.txt", "fields": {} }
110
+ },
111
+
112
+ { "name": "reviewClean", "method": "POST", "path": "/api/documents/${uploadClean|id}/review" },
113
+ { "name": "reviewMessy", "method": "POST", "path": "/api/documents/${uploadMessy|id}/review" },
114
+ { "name": "reviewTiny", "method": "POST", "path": "/api/documents/${uploadTiny|id}/review" },
115
+ { "name": "reviewUnicode", "method": "POST", "path": "/api/documents/${uploadUnicode|id}/review" },
116
+ { "name": "reviewDocx", "method": "POST", "path": "/api/documents/${uploadDocxDeflate|id}/review" },
117
+ { "name": "reviewUtf16", "method": "POST", "path": "/api/documents/${uploadUtf16|id}/review" },
118
+ { "name": "reviewCp1252", "method": "POST", "path": "/api/documents/${uploadCp1252|id}/review" },
119
+
120
+ {
121
+ "name": "addReviewerAda",
122
+ "method": "POST",
123
+ "path": "/api/reviewers",
124
+ "body": { "name": " Ada Reviewer ", "email": "ada@example.com", "slack": "@ada", "teams": "" }
125
+ },
126
+ {
127
+ "name": "addReviewerGrace",
128
+ "method": "POST",
129
+ "path": "/api/reviewers",
130
+ "body": { "name": "grace hopper", "email": "", "slack": "", "teams": "Grace H." }
131
+ },
132
+ {
133
+ "name": "rejectNamelessReviewer",
134
+ "method": "POST",
135
+ "path": "/api/reviewers",
136
+ "body": { "name": " ", "email": "nobody@example.com" }
137
+ },
138
+ {
139
+ "name": "updateReviewerAda",
140
+ "method": "PUT",
141
+ "path": "/api/reviewers/${addReviewerAda|id}",
142
+ "body": { "name": "Ada Lovelace", "email": "ada@example.org", "slack": "@ada", "teams": "Ada L." }
143
+ },
144
+ {
145
+ "name": "rejectUnknownReviewerUpdate",
146
+ "method": "PUT",
147
+ "path": "/api/reviewers/does-not-exist",
148
+ "body": { "name": "Ghost" }
149
+ },
150
+ { "name": "listReviewers", "method": "GET", "path": "/api/reviewers" },
151
+
152
+ {
153
+ "name": "assignBoth",
154
+ "method": "POST",
155
+ "path": "/api/documents/${uploadClean|id}/assign-reviewers",
156
+ "body": { "reviewer_ids": ["${addReviewerAda|id}", "${addReviewerGrace|id}", "${addReviewerAda|id}", " "] }
157
+ },
158
+ {
159
+ "name": "rejectUnknownAssignment",
160
+ "method": "POST",
161
+ "path": "/api/documents/${uploadMessy|id}/assign-reviewers",
162
+ "body": { "reviewer_ids": ["nope"] }
163
+ },
164
+ {
165
+ "name": "rejectAssignmentPayload",
166
+ "method": "POST",
167
+ "path": "/api/documents/${uploadMessy|id}/assign-reviewers",
168
+ "body": { "reviewer_ids": "ada" }
169
+ },
170
+
171
+ {
172
+ "name": "reviewerCommentAda",
173
+ "method": "POST",
174
+ "path": "/api/documents/${uploadClean|id}/reviewer-comment",
175
+ "body": { "reviewer_id": "${addReviewerAda|id}", "signature": "AL", "body": "Section 3 needs the escalation contact." }
176
+ },
177
+ {
178
+ "name": "reviewerRequestChangesGrace",
179
+ "method": "POST",
180
+ "path": "/api/documents/${uploadClean|id}/reviewer-request-changes",
181
+ "body": { "reviewer_id": "${addReviewerGrace|id}", "signature": "", "body": "Add the retention period." }
182
+ },
183
+ { "name": "documentAfterChanges", "method": "GET", "path": "/api/documents/${uploadClean|id}" },
184
+ {
185
+ "name": "rejectEmptyReviewerComment",
186
+ "method": "POST",
187
+ "path": "/api/documents/${uploadClean|id}/reviewer-comment",
188
+ "body": { "reviewer_id": "${addReviewerAda|id}", "signature": "AL", "body": " " }
189
+ },
190
+ {
191
+ "name": "rejectUnassignedReviewer",
192
+ "method": "POST",
193
+ "path": "/api/documents/${uploadMessy|id}/reviewer-approve",
194
+ "body": { "reviewer_id": "${addReviewerAda|id}", "signature": "AL" }
195
+ },
196
+ {
197
+ "name": "rejectUnsignedApproval",
198
+ "method": "POST",
199
+ "path": "/api/documents/${uploadClean|id}/reviewer-approve",
200
+ "body": { "reviewer_id": "${addReviewerAda|id}", "signature": "" }
201
+ },
202
+ {
203
+ "name": "approveGrace",
204
+ "method": "POST",
205
+ "path": "/api/documents/${uploadClean|id}/reviewer-approve",
206
+ "body": { "reviewer_id": "${addReviewerGrace|id}", "signature": "Grace Hopper", "initials": "GH" }
207
+ },
208
+ {
209
+ "name": "approveAda",
210
+ "method": "POST",
211
+ "path": "/api/documents/${uploadClean|id}/reviewer-approve",
212
+ "body": { "reviewer_id": "${addReviewerAda|id}", "signature": "Ada Lovelace" }
213
+ },
214
+ { "name": "documentAfterApproval", "method": "GET", "path": "/api/documents/${uploadClean|id}" },
215
+ {
216
+ "name": "approveAdaAgain",
217
+ "method": "POST",
218
+ "path": "/api/documents/${uploadClean|id}/reviewer-approve",
219
+ "body": { "reviewer_id": "${addReviewerAda|id}", "signature": "Ada Lovelace" }
220
+ },
221
+
222
+ {
223
+ "name": "ownerComment",
224
+ "method": "POST",
225
+ "path": "/api/documents/${uploadClean|id}/comments",
226
+ "body": { "body": "Sending to legal on Friday.", "author": "Dana Owner" }
227
+ },
228
+ {
229
+ "name": "rejectEmptyOwnerComment",
230
+ "method": "POST",
231
+ "path": "/api/documents/${uploadClean|id}/comments",
232
+ "body": { "body": "" }
233
+ },
234
+ {
235
+ "name": "assignMessy",
236
+ "method": "POST",
237
+ "path": "/api/documents/${uploadMessy|id}/assign-reviewers",
238
+ "body": { "reviewer_ids": ["${addReviewerGrace|id}"] }
239
+ },
240
+ {
241
+ "name": "clearMessyAssignments",
242
+ "method": "POST",
243
+ "path": "/api/documents/${uploadMessy|id}/assign-reviewers",
244
+ "body": { "reviewer_ids": [] }
245
+ },
246
+ {
247
+ "name": "assignTinyUnreviewed",
248
+ "method": "POST",
249
+ "path": "/api/documents/${uploadTiny|id}/assign-reviewers",
250
+ "body": { "reviewer_ids": [] }
251
+ },
252
+
253
+ { "name": "notificationsBeforeRead", "method": "GET", "path": "/api/notifications" },
254
+ {
255
+ "name": "markNotificationRead",
256
+ "method": "POST",
257
+ "path": "/api/notifications/${notificationsBeforeRead|notifications.0.id}/read"
258
+ },
259
+ {
260
+ "name": "markNotificationReadAgain",
261
+ "method": "POST",
262
+ "path": "/api/notifications/${notificationsBeforeRead|notifications.0.id}/read"
263
+ },
264
+ { "name": "rejectUnknownNotification", "method": "POST", "path": "/api/notifications/nope/read" },
265
+ { "name": "notificationsAfterRead", "method": "GET", "path": "/api/notifications" },
266
+
267
+ { "name": "ownerApprove", "method": "POST", "path": "/api/documents/${uploadTiny|id}/approve" },
268
+ { "name": "ownerRequestChanges", "method": "POST", "path": "/api/documents/${uploadTiny|id}/request-changes" },
269
+
270
+ { "name": "deleteReviewerGrace", "method": "DELETE", "path": "/api/reviewers/${addReviewerGrace|id}" },
271
+ { "name": "rejectUnknownReviewerDelete", "method": "DELETE", "path": "/api/reviewers/${addReviewerGrace|id}" },
272
+ { "name": "documentKeepsAssignmentHistory", "method": "GET", "path": "/api/documents/${uploadClean|id}" },
273
+
274
+ { "name": "rejectUnknownDocument", "method": "GET", "path": "/api/documents/does-not-exist" },
275
+ {
276
+ "name": "rejectUnknownDocumentReviewerAction",
277
+ "method": "POST",
278
+ "path": "/api/documents/does-not-exist/reviewer-approve",
279
+ "body": { "reviewer_id": "${addReviewerAda|id}", "signature": "AL" }
280
+ },
281
+ { "name": "rejectUnknownRoute", "method": "GET", "path": "/api/nope" },
282
+ { "name": "rejectUnknownAction", "method": "POST", "path": "/api/documents/${uploadClean|id}/nope" },
283
+
284
+ { "name": "downloadClean", "method": "GET", "path": "/api/documents/${uploadClean|id}/download", "binary": true },
285
+ { "name": "downloadDocx", "method": "GET", "path": "/api/documents/${uploadDocxStored|id}/download", "binary": true },
286
+ { "name": "rejectUnknownDownload", "method": "GET", "path": "/api/documents/nope/download", "binary": true },
287
+
288
+ { "name": "finalDocuments", "method": "GET", "path": "/api/documents" },
289
+ { "name": "finalReviewers", "method": "GET", "path": "/api/reviewers" },
290
+ { "name": "finalNotifications", "method": "GET", "path": "/api/notifications" }
291
+ ]
292
+ }