Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

feat(spec-review): browser review surface for design_spec.md

hugohe361ad7aecedf2
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index dd35feb6..4307b035 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -58,6 +58,7 @@ python3 scripts/update_repo.py
| PPTX animations | `pptx_animations.py`, `animation_config.py` | [docs/pptx-animations.md](./docs/pptx-animations.md) |
| Animation resources | `sound_sync.py` | [sound vocabulary and sync](../templates/sounds/README.md); [docs/pptx-animations.md](./docs/pptx-animations.md) |
| Spec maintenance | `update_spec.py`, `visualization_recall.py`; legacy `chart_recall.py` | [docs/update_spec.md](./docs/update_spec.md); [docs/visualization-recall.md](./docs/visualization-recall.md) |
+| Spec review | `spec_review/server.py`, `check_spec_annotations.py` | [docs/spec_review.md](./docs/spec_review.md) |
| Image tools | `image_gen.py`, `image_treat.py`, `analyze_images.py`, `gemini_watermark_remover.py` | [docs/image.md](./docs/image.md) |
| Maintenance smokes | Inline temporary-project commands | [advanced image and motion](./docs/advanced-image-motion-smoke.md); [mask and gradient](./docs/mask-gradient-smoke.md); [multilingual text](./docs/multilingual-text-smoke.md) |
| Repo maintenance | `update_repo.py` | README install/update section |
diff --git a/skills/ppt-master/scripts/check_spec_annotations.py b/skills/ppt-master/scripts/check_spec_annotations.py
new file mode 100644
index 00000000..c372a09f
--- /dev/null
+++ b/skills/ppt-master/scripts/check_spec_annotations.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Spec Annotation Checker
+
+Print compact JSON to-dos and unread direct-edit summaries; acknowledge listed
+edits or unchanged comments. See scripts/docs/spec_review.md.
+
+Usage:
+ python3 scripts/check_spec_annotations.py <project_path> [--applied ID | --ack-edits]
+
+Examples:
+ python3 scripts/check_spec_annotations.py projects/example
+ python3 scripts/check_spec_annotations.py projects/example --applied abc123
+ python3 scripts/check_spec_annotations.py projects/example --ack-edits
+
+Dependencies:
+ None (only uses the standard library and local project modules)
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+_SCRIPTS_DIR = Path(__file__).resolve().parent
+if str(_SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(_SCRIPTS_DIR))
+
+from console_encoding import configure_utf8_stdio # noqa: E402
+from spec_review.store import ReviewStore # noqa: E402
+
+configure_utf8_stdio()
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("project_path")
+ actions = parser.add_mutually_exclusive_group()
+ actions.add_argument("--applied", metavar="ID")
+ actions.add_argument("--ack-edits", action="store_true", help="Consume direct edits from the last CLI listing")
+ args = parser.parse_args(argv)
+ store = ReviewStore(Path(args.project_path))
+ try:
+ store.document()
+ if args.applied:
+ store.remove_annotation(args.applied, applied=True)
+ result = {"applied": args.applied}
+ elif args.ack_edits:
+ result = {"edits_cursor": store.ack_edits()}
+ else:
+ result = store.list_todo()
+ print(json.dumps(result, ensure_ascii=False, separators=(",", ":")))
+ return 0
+ except (OSError, ValueError) as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/docs/spec_review.md b/skills/ppt-master/scripts/docs/spec_review.md
new file mode 100644
index 00000000..1bca8996
--- /dev/null
+++ b/skills/ppt-master/scripts/docs/spec_review.md
@@ -0,0 +1,219 @@
+# `spec_review/server.py`
+
+Local browser review of `design_spec.md`, with block comments and staged Markdown
+editing. The tool writes the same spec file, keeps comments in sidecars, and does
+not read or write `spec_lock.md`, invoke a model, or start generation.
+
+## Commands
+
+```bash
+python3 skills/ppt-master/scripts/spec_review/server.py <project_path> --daemon
+python3 skills/ppt-master/scripts/spec_review/server.py <project_path> --daemon --no-browser
+python3 skills/ppt-master/scripts/spec_review/server.py <project_path> --port 6070 --timeout 7200
+python3 skills/ppt-master/scripts/spec_review/server.py <project_path> --hold on
+python3 skills/ppt-master/scripts/spec_review/server.py <project_path> --hold off
+python3 skills/ppt-master/scripts/check_spec_annotations.py <project_path>
+python3 skills/ppt-master/scripts/check_spec_annotations.py <project_path> --ack-edits
+python3 skills/ppt-master/scripts/check_spec_annotations.py <project_path> --applied <id>
+python3 skills/ppt-master/scripts/spec_review/server.py <project_path> --shutdown
+```
+
+The daemon launcher waits for `GET /api/health` and prints a compact JSON object
+with the actual URL, pid, and port. Diagnostics go to stderr; detached server
+output goes to `<project_path>/spec_review/server.log`.
+As with other project CLIs, an existing `validation/workflow.log` receives the
+launch/check command envelope through the shared console helper; detached server
+requests are not copied into that workflow log.
+
+## Lifecycle
+
+- **Port**: bind loopback only. Without `--port`, scan 50 ports starting at `6060`;
+ an explicit `--port N` binds strictly. Use the returned URL, not an assumed port.
+- **Single instance**: `<project_path>/spec_review/lock.json` records pid and port.
+ A second launch reuses the live instance; a different explicit port fails.
+ Dead-pid locks are replaced. `service.guard` serializes concurrent launches.
+- **Timeout**: `7200s` of inactivity by default; `--timeout 0` disables it.
+ `/api/state` polling and `/api/health` requests do not refresh activity; other
+ requests that pass the Host/Origin guard do. An idle open tab does not prevent
+ timeout. Closing a tab leaves the service running. **Exit review**, `--shutdown`,
+ timeout, or process termination stops it.
+- **Draft lifetime**: per-block drafts live only in server memory. A tab reload
+ can retrieve them; stopping or restarting the server loses unapplied drafts.
+ The browser requests leave-page confirmation while it has pending work.
+- **Exit review**: the button checks for unapplied drafts and unsaved comments
+ before calling `POST /api/shutdown`. Pending work requires confirmation.
+ Successful shutdown stops polling and replaces the review workspace with a
+ static stopped message in the selected UI language; saved comments remain on disk.
+- **Write handoff**: `--hold on` waits for an active Apply to finish and makes
+ subsequent Apply requests return `423`. The page displays an AI-editing banner.
+ `--hold off` causes automatic block/hash reload, including when both transitions
+ occur between polls. Existing drafts survive and stale bases remain conflicts.
+- **External changes**: the browser polls the raw-byte SHA-256 every two seconds.
+ A changed hash prompts reload; reload preserves drafts. After inspecting the
+ current source, **Use current disk as draft base** explicitly rebases a draft.
+ A draft whose block was removed externally remains available for copying or
+ discarding; it cannot be applied to a different block.
+ External writers must honor hold for coordinated writes: the last hash check
+ and filesystem replacement cannot form a compare-and-swap with arbitrary writers.
+- **Request boundary**: Host must name loopback; a supplied Origin must match the
+ request origin. Responses disable caching and carry a restrictive CSP. There
+ are no remote scripts, fonts, styles, or other resources.
+
+## Review surface
+
+The three-column dark UI has ordered block navigation, rendered/source views,
+a raw Markdown editor, and block/global comments. First/prev/next/last and
+`Left`/`Right`/`Home`/`End` navigation are suppressed while typing. Four languages
+(Chinese, Traditional Chinese, English, Japanese) follow `navigator.language`
+and a persistent `localStorage` selection.
+
+Blocks use each `##` section, except IX: its lead-in, each Slide heading matching
+the shared `SLIDE_HEADING_RE` (levels 3–6), and every other `###` heading are
+separate blocks. Non-Slide `###` headings have kind `part` and occurrence keys
+`part:01`, `part:02`, etc. Each range ends immediately before the next block.
+Navigation renders Parts as clickable group headings with indented Slides below.
+Backtick and tilde fences hide internal headings. The preamble and all ordered ranges
+reconstruct the exact source bytes. The shared `project_management/spec_blocks.py`
+API exposes character offsets and corresponding UTF-8 byte offsets; malformed
+duplicate keys receive occurrence suffixes.
+
+**Apply changes** saves the selected block. The service serializes Apply and
+hold, checks the supplied SHA-256 against disk (`409` on mismatch), validates the
+candidate text with the existing design-spec schema, replaces only the target
+byte interval using a sibling temporary file and `os.replace`, and appends edit
+history. Schema errors are returned verbatim and displayed without blocking the
+save. Direct editing locks the section heading, Slide level/number, and structural
+boundaries; a Slide page name may change. A Part permits only title text changes:
+its heading stays level 3 and its remaining content stays unchanged. Slides do
+not contain the next Part heading, so appending page content does not edit a Part.
+Additional unfenced `##` headings or headings matching `SLIDE_HEADING_RE` are
+rejected; additional `###` headings in IX are also rejected. Page insertion,
+removal, and ordering are comment requests. Changed blocks retain their newline style and terminal
+whitespace; a no-op preserves even mixed line endings. Drafts on other unchanged
+blocks advance to the new hash after a successful browser Apply.
+
+The renderer uses DOM creation and text nodes for headings, paragraphs, lists
+(including nesting), emphasis, inline code, tables, fenced code, quotations, and
+rules. LaTeX stays monospace text; unsupported syntax falls back to literal text.
+Links and image syntax do not create clickable links or loaded images.
+Inline fragments over 4096 characters remain plain text to bound delimiter
+backtracking. A rendering exception replaces that block's preview with its full
+source in a monospace display; editing and staging remain available.
+
+Comments are saved immediately to `spec_review/annotations.json`, separately
+from Apply. Each item contains `id`, `key`, `title`, `spec_sha256` (creation-time
+whole-spec hash), `body`, `created_at`, `updated_at`, and a unique `revision`.
+Block comments also store `block_sha256`, the creation-time SHA-256 of that raw
+block's UTF-8 bytes. Updating a comment preserves its original hashes. API and
+CLI listings report `block_changed` as `true` or `false` against the current block;
+legacy items without `block_sha256` report `null` (unknown). An absent block has
+`block_missing: true` and `block_changed: null`; present blocks have
+`block_missing: false`. The UI uses these block statuses. `global` is the global
+comment slot and retains the whole-spec `base_current` comparison instead.
+`annotations.jsonl` appends `saved`, `updated`, `removed`,
+and `annotation_applied` events. `storage.guard` serializes browser/CLI
+sidecar transactions and edit-log access across processes. `edits.jsonl` appends `ts`, `key`, `title`,
+`before`, `after`, `before_sha256`, and `after_sha256` for each changed block.
+
+`check_spec_annotations.py` prints compact JSON with pending comments, their
+current baseline statuses, and unread direct-edit summaries (`ts`, `key`, `title`,
+plus the first 12 characters of `before_sha256` and `after_sha256`, no block bodies).
+`annotations.json` stores an acknowledged byte offset in `edits_cursor` (default
+`0`) and the last CLI listing's end offset in `listed_edits_cursor`. Listing does
+not consume edits. `--ack-edits` advances the acknowledged cursor only to that
+last listed offset; edits appended after the listing remain unread. It requires a
+prior CLI listing and never rewrites `edits.jsonl`. Later listings return only
+edits after the acknowledged cursor. `--ack-edits` and `--applied` are mutually exclusive.
+
+Listing also records full-item fingerprints (including revisions) in the same
+sidecar's `listed` map. `--applied ID` clears only that listed version; an unlisted or subsequently
+changed comment stays pending and the command exits nonzero with stderr detail.
+Browser reads do not advance this agent receipt. Updating even to identical text
+creates a new revision. A fresh CLI listing replaces the previous listing receipt.
+
+### HTTP API
+
+JSON bodies and responses use UTF-8. Block keys are URL-encoded path components.
+
+| Method and path | Result or request body |
+| --- | --- |
+| `GET /api/health` | Service identity, project path, pid |
+| `GET /api/state` | `sha256`, `hold`, `hold_revision` |
+| `GET /api/blocks` | Ordered metadata, annotation/draft flags, global-comment flag, draft keys, orphan drafts, state |
+| `GET /api/blocks/<key>` | Original `text`, title, ranges, current hash, optional separate draft |
+| `GET /api/spec` | Full raw `text` and `sha256` |
+| `PUT /api/drafts/<key>` | `text`, `sha256`, `version` (`null` for a new draft); returns a new draft version |
+| `DELETE /api/drafts/<key>` | `version` of the draft to discard |
+| `POST /api/apply/<key>` | `sha256`, `version`; returns `saved`, new hash, `validation_errors` |
+| `GET /api/annotations` | Pending items with block baseline status, or `base_current` for global comments |
+| `POST /api/annotations` | `key`, `body`; returns the saved item |
+| `PUT /api/annotations/<id>` | `body`, `revision` |
+| `DELETE /api/annotations/<id>` | `revision` |
+| `POST /api/hold` | `hold` boolean |
+| `POST /api/shutdown` | Stops the service |
+
+Stale draft or comment versions return `409`; malformed bodies and structural
+edits return `400`. Request bodies are limited to 4 MiB. No approval or generation
+endpoint exists.
+
+## Frontend regression checks
+
+There is no repository JavaScript test runner. Use a disposable project copy
+with at least two editable blocks for these manual checks. Start the review
+server with the commands above, open its URL, and use the browser's Network
+panel to inspect request keys and bodies. To keep write responses in flight
+while typing or navigating, run this temporary console snippet; reloading the
+tab restores normal fetching:
+
+```javascript
+const originalFetch = window.fetch.bind(window);
+window.fetch = async (...args) => {
+ const response = await originalFetch(...args);
+ if ((args[1]?.method || 'GET') !== 'GET') {
+ await new Promise(resolve => setTimeout(resolve, 1500));
+ }
+ return response;
+};
+```
+
+1. **Apply target and snapshot**: stage a draft in block B, return to A, and
+ edit A. Within the 350 ms debounce window, click B and immediately click
+ Apply while A is still displayed. Repeat after A's draft PUT has started,
+ adding another character before clicking B and Apply. Expect the queued
+ navigation to flush A, then Apply to target A with the text present at the
+ Apply click and the version returned by staging. Only A changes on disk;
+ B's draft remains. Also wait until B is displayed before clicking Apply in
+ a separate run: only B should change. The editor and Apply stay disabled
+ until the pending Apply finishes, including across polling responses.
+2. **Typing during responses**: stage an A draft, change the disposable spec
+ externally, reload its disk content, and choose the rebase action. Type
+ more text while the draft PUT response is delayed. Expect all new text to
+ remain in the editor and to stage using the returned version and new base.
+ Separately save a new annotation and update an existing annotation, typing
+ more in the same field before each response arrives. Expect the sent text
+ to be saved, the newer input to remain, and a subsequent update to succeed
+ with the latest revision. With no additional typing, saving a new annotation
+ should still clear its input as usual.
+3. **Pathological Markdown**: append a line produced by
+ `'x' + String.fromCharCode(96).repeat(200000) + 'y'` to an editable block.
+ Expect literal text to appear promptly and the draft PUT to proceed. Also
+ try an unclosed code fence, hundreds of increasingly indented list items,
+ and a table with a two-cell header and one-/three-cell body rows. Expect
+ each preview to finish without throwing or looping. To exercise exception
+ recovery, temporarily replace `markdown` in the console with a function
+ that throws, then type: the preview must show the entire block as monospace
+ source and staging must continue. Reload the tab to restore the renderer.
+4. **External edit before metadata refresh**: on a fresh tab without drafts,
+ run `clearInterval(pollTimer)` in the console to hold off the two-second
+ poll. Change the disposable spec on disk, then save an annotation. Expect
+ the reload warning immediately after metadata refresh, while the preview
+ and displayed fingerprint still describe the old block. Click the in-page
+ reload button: the preview/fingerprint should advance and the warning should
+ clear. Reload the tab afterward to restore polling.
+
+## Remote access
+
+Start with `--no-browser` on the remote host. Forward the actual port `<P>` from
+launch output or `spec_review/lock.json`: use the IDE's **PORTS** panel, a Termius
+local rule bound to `127.0.0.1:<P>`, or
+`ssh -L <P>:127.0.0.1:<P> <user>@<host>`. Open `http://localhost:<P>` locally.
diff --git a/skills/ppt-master/scripts/prompt_audit_manifest.json b/skills/ppt-master/scripts/prompt_audit_manifest.json
index 26d60692..f48fe0ff 100644
--- a/skills/ppt-master/scripts/prompt_audit_manifest.json
+++ b/skills/ppt-master/scripts/prompt_audit_manifest.json
@@ -2429,6 +2429,10 @@
"glob": "skills/ppt-master/scripts/docs/svg_editor.md",
"reason": "Browser editor behavior and lifecycle reference; the live-preview stage carries the launch and annotation procedure."
},
+ {
+ "glob": "skills/ppt-master/scripts/docs/spec_review.md",
+ "reason": "Spec review tool reference for browser editing, annotation sidecars, HTTP APIs, and server lifecycle; not loaded as runtime prompt context."
+ },
{
"glob": "skills/ppt-master/scripts/docs/narration.md",
"reason": "Narration tool behavior and flag reference; the generate-audio stage carries the procedure and confirmation contract."
diff --git a/skills/ppt-master/scripts/spec_review/__init__.py b/skills/ppt-master/scripts/spec_review/__init__.py
new file mode 100644
index 00000000..7f4c5649
--- /dev/null
+++ b/skills/ppt-master/scripts/spec_review/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Spec Review
+
+Browser review, annotations, and staged Markdown edits for design_spec.md.
+
+Usage:
+ python3 scripts/spec_review/server.py <project_path>
+
+Examples:
+ python3 scripts/spec_review/server.py projects/example --daemon
+
+Dependencies:
+ Flask (server); standard library (storage and annotation CLI)
+"""
diff --git a/skills/ppt-master/scripts/spec_review/server.py b/skills/ppt-master/scripts/spec_review/server.py
new file mode 100644
index 00000000..95f83f1f
--- /dev/null
+++ b/skills/ppt-master/scripts/spec_review/server.py
@@ -0,0 +1,341 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Spec Review Server
+
+Serve a local Markdown review surface with staged edits and sidecar comments.
+See scripts/docs/spec_review.md for commands, APIs, and runtime files.
+
+Usage:
+ python3 scripts/spec_review/server.py <project_path> [--daemon]
+
+Examples:
+ python3 scripts/spec_review/server.py projects/example --daemon --no-browser
+ python3 scripts/spec_review/server.py projects/example --hold on
+
+Dependencies:
+ Flask (already used by svg_editor and confirm_ui)
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import logging
+import os
+import signal
+import subprocess
+import sys
+import threading
+import time
+import urllib.parse
+import urllib.request
+from pathlib import Path
+
+_SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+if str(_SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(_SCRIPTS_DIR))
+
+from console_encoding import configure_utf8_stdio # noqa: E402
+
+configure_utf8_stdio()
+
+from flask import Flask, jsonify, request, send_from_directory # noqa: E402
+from werkzeug.exceptions import HTTPException # noqa: E402
+from werkzeug.serving import make_server # noqa: E402
+
+from server_common import ( # noqa: E402
+ claim_lock,
+ clear_lock,
+ find_free_port,
+ lock_pid,
+ open_preview_browser,
+ popen_detached,
+ process_alive,
+ read_lock,
+ release_lock,
+ validate_port,
+)
+from spec_review.store import ReviewError, ReviewStore, file_mutex # noqa: E402
+
+
+PUBLIC_HOST = "127.0.0.1"
+DEFAULT_PORT = 6060
+logger = logging.getLogger("spec_review")
+
+
+def create_app(project_dir: str, idle_timeout: int = 7200) -> Flask:
+ """Create the testable HTTP surface; lifecycle threads belong to main()."""
+ store = ReviewStore(Path(project_dir))
+ store.document()
+ app = Flask(__name__, static_folder="static", static_url_path="/static")
+ app.config.update(MAX_CONTENT_LENGTH=4 * 1024 * 1024, LAST_ACTIVITY=time.monotonic(), IDLE_TIMEOUT=idle_timeout)
+ app.extensions["review_store"] = store
+ app.extensions["stop_event"] = threading.Event()
+
+ @app.before_request
+ def protect_local_service():
+ try:
+ host = urllib.parse.urlsplit("//" + request.host)
+ if host.hostname not in {PUBLIC_HOST, "localhost", "::1"} or host.username or host.password:
+ raise ValueError("Host")
+ host_port = host.port or 80
+ origin = request.headers.get("Origin")
+ if origin is not None:
+ parsed = urllib.parse.urlsplit(origin)
+ if (parsed.scheme != request.scheme or parsed.hostname != host.hostname
+ or (parsed.port or 80) != host_port or parsed.username or parsed.password
+ or parsed.path or parsed.query or parsed.fragment):
+ raise ValueError("Origin")
+ except ValueError:
+ return jsonify(error="Forbidden Host or Origin header"), 403
+ if request.path not in {"/api/state", "/api/health"}:
+ app.config["LAST_ACTIVITY"] = time.monotonic()
+
+ @app.after_request
+ def secure_response(response):
+ response.headers["Cache-Control"] = "no-store"
+ response.headers["X-Content-Type-Options"] = "nosniff"
+ response.headers["Content-Security-Policy"] = (
+ "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; "
+ "img-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'"
+ )
+ return response
+
+ @app.errorhandler(ReviewError)
+ def review_error(error):
+ return jsonify(error=str(error)), error.status
+
+ @app.errorhandler(OSError)
+ @app.errorhandler(ValueError)
+ def storage_error(error):
+ logger.error("spec review storage: %s", error)
+ return jsonify(error=str(error)), 500
+
+ @app.errorhandler(HTTPException)
+ def http_error(error):
+ return jsonify(error=error.description), error.code
+
+ def payload(*strings: str) -> dict:
+ data = request.get_json(silent=True)
+ if not isinstance(data, dict) or any(not isinstance(data.get(key), str) for key in strings):
+ raise ReviewError("Send a JSON object with string fields: " + ", ".join(strings))
+ return data
+
+ @app.get("/")
+ def index():
+ return send_from_directory(app.static_folder, "index.html")
+
+ @app.get("/api/health")
+ def health():
+ return jsonify(status="ok", service="spec_review", pid=os.getpid(), project=str(store.project))
+
+ @app.get("/api/state")
+ def state():
+ return jsonify(store.state())
+
+ @app.get("/api/blocks")
+ def blocks():
+ return jsonify(store.snapshot())
+
+ @app.get("/api/spec")
+ def spec():
+ return jsonify(store.document())
+
+ @app.get("/api/blocks/<path:key>")
+ def block(key):
+ return jsonify(store.block(key))
+
+ @app.put("/api/drafts/<path:key>")
+ def stage(key):
+ data = payload("text", "sha256")
+ return jsonify(store.stage(key, data["text"], data["sha256"], data.get("version")))
+
+ @app.delete("/api/drafts/<path:key>")
+ def discard(key):
+ data = payload("version")
+ store.discard(key, data["version"])
+ return jsonify(status="ok")
+
+ @app.post("/api/apply/<path:key>")
+ def apply(key):
+ data = payload("sha256", "version")
+ return jsonify(store.apply(key, data["sha256"], data["version"]))
+
+ @app.route("/api/annotations", methods=["GET", "POST"])
+ def annotations():
+ if request.method == "GET":
+ return jsonify(annotations=store.annotations())
+ data = payload("key", "body")
+ return jsonify(store.save_annotation(data["key"], data["body"])), 201
+
+ @app.route("/api/annotations/<item_id>", methods=["PUT", "DELETE"])
+ def annotation(item_id):
+ data = payload("revision", *( ["body"] if request.method == "PUT" else []))
+ if request.method == "DELETE":
+ store.remove_annotation(item_id, data["revision"])
+ return jsonify(status="ok")
+ return jsonify(store.save_annotation("", data["body"], item_id, data["revision"]))
+
+ @app.post("/api/hold")
+ def hold():
+ data = payload()
+ if not isinstance(data.get("hold"), bool):
+ raise ReviewError("hold must be true or false")
+ return jsonify(store.set_hold(data["hold"]))
+
+ @app.post("/api/shutdown")
+ def shutdown():
+ store.set_hold(True)
+ app.extensions["stop_event"].set()
+ return jsonify(status="ok")
+
+ return app
+
+
+def _call(port: int, path: str, data: dict | None = None) -> dict:
+ url = f"http://{PUBLIC_HOST}:{validate_port(port)}{path}"
+ request_data = None if data is None else json.dumps(data).encode("utf-8")
+ req = urllib.request.Request(url, data=request_data, headers={"Content-Type": "application/json"})
+ with urllib.request.build_opener(urllib.request.ProxyHandler({})).open(req, timeout=2) as response:
+ return json.load(response)
+
+
+def _running(project: Path) -> dict | None:
+ lock = read_lock(project / "spec_review" / "lock.json")
+ if not lock or not process_alive(lock_pid(lock)):
+ return None
+ health = _call(lock.get("port"), "/api/health")
+ if health.get("service") != "spec_review" or health.get("project") != str(project) or (
+ health.get("pid") != lock_pid(lock)
+ ):
+ raise ValueError("The lock does not identify this project's spec review service.")
+ return lock
+
+
+def _announce(lock: dict, no_browser: bool) -> None:
+ url = f"http://{PUBLIC_HOST}:{lock['port']}"
+ print(json.dumps({"service": "spec_review", "url": url, **lock}, separators=(",", ":")))
+ if not no_browser:
+ open_preview_browser(url, logger=logger)
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("project_path")
+ actions = parser.add_mutually_exclusive_group()
+ actions.add_argument("--daemon", action="store_true")
+ actions.add_argument("--shutdown", action="store_true")
+ actions.add_argument("--hold", choices=("on", "off"))
+ parser.add_argument("--no-browser", action="store_true")
+ parser.add_argument("--port", type=int, help="Bind exactly this port; otherwise scan from 6060")
+ parser.add_argument("--timeout", type=int, default=7200, help="Idle seconds; 0 disables the timeout")
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s spec_review: %(message)s")
+ project = Path(args.project_path).resolve()
+ runtime = project / "spec_review"
+ lock_file = runtime / "lock.json"
+ try:
+ if args.port is not None:
+ validate_port(args.port)
+ if args.timeout < 0:
+ raise ValueError("--timeout must be nonnegative")
+ existing = _running(project)
+ if args.shutdown or args.hold:
+ if not existing:
+ if args.hold:
+ raise ValueError("Start spec review before setting --hold.")
+ clear_lock(lock_file)
+ print('{"status":"stopped"}')
+ return 0
+ path = "/api/shutdown" if args.shutdown else "/api/hold"
+ result = _call(existing["port"], path, {} if args.shutdown else {"hold": args.hold == "on"})
+ if args.shutdown:
+ deadline = time.monotonic() + 5
+ while read_lock(lock_file) == existing and time.monotonic() < deadline:
+ time.sleep(0.1)
+ if read_lock(lock_file) == existing:
+ raise ValueError("Shutdown is still pending; inspect spec_review/server.log.")
+ print(json.dumps(result, separators=(",", ":")))
+ return 0
+ if existing:
+ if args.port is not None and existing["port"] != args.port:
+ raise ValueError("A server is already running on a different port; use --shutdown first.")
+ _announce(existing, args.no_browser)
+ return 0
+ if not (project / "design_spec.md").is_file():
+ raise ValueError("The project must contain design_spec.md.")
+ runtime.mkdir(parents=True, exist_ok=True)
+ if args.daemon:
+ command = [sys.executable, str(Path(__file__).resolve()), str(project),
+ "--no-browser", "--timeout", str(args.timeout)]
+ if args.port is not None:
+ command.extend(["--port", str(args.port)])
+ with (runtime / "server.log").open("a", encoding="utf-8") as log:
+ process = popen_detached(command, stdin=subprocess.DEVNULL, stdout=log, stderr=log, logger=logger)
+ deadline = time.monotonic() + 15
+ while time.monotonic() < deadline:
+ try:
+ existing = _running(project)
+ except (OSError, ValueError):
+ existing = None
+ if existing:
+ if args.port is not None and existing["port"] != args.port:
+ raise ValueError("A concurrent launch claimed another port; use --shutdown first.")
+ _announce(existing, args.no_browser)
+ return 0
+ if process.poll() is not None:
+ break
+ time.sleep(0.2)
+ if process.poll() is None:
+ process.terminate()
+ raise ValueError("Server failed to start; inspect spec_review/server.log.")
+
+ # Serialize startup without changing the shared servers' lock behavior.
+ with file_mutex(runtime / "service.guard"):
+ existing = _running(project)
+ if existing:
+ if args.port is not None and args.port != existing["port"]:
+ raise ValueError("A concurrent launch claimed another port; use --shutdown first.")
+ _announce(existing, args.no_browser)
+ return 0
+ app = create_app(str(project), args.timeout)
+ port = args.port if args.port is not None else find_free_port(DEFAULT_PORT)
+ httpd = make_server(PUBLIC_HOST, port, app, threaded=True)
+ # Let in-flight writes finish before server_close releases the slot.
+ httpd.daemon_threads = False
+ if claim_lock(lock_file, port):
+ httpd.server_close()
+ raise ValueError("Another process claimed the project lock; launch again.")
+ stop = app.extensions["stop_event"]
+
+ def watch():
+ while not stop.wait(0.25):
+ with app.extensions["review_store"].mutex:
+ if args.timeout and time.monotonic() - app.config["LAST_ACTIVITY"] > args.timeout:
+ logger.info("idle timeout reached")
+ break
+ httpd.shutdown()
+
+ signal.signal(signal.SIGTERM, lambda *_: stop.set())
+ threading.Thread(target=watch, daemon=True).start()
+ try:
+ _announce({"pid": os.getpid(), "port": port}, args.no_browser)
+ httpd.serve_forever(poll_interval=0.2)
+ except KeyboardInterrupt:
+ stop.set()
+ finally:
+ stop.set()
+ httpd.server_close()
+ release_lock(lock_file)
+ return 0
+ except (OSError, ValueError, RuntimeError) as exc:
+ logger.error("%s", exc)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/spec_review/static/app.js b/skills/ppt-master/scripts/spec_review/static/app.js
new file mode 100644
index 00000000..47c924d4
--- /dev/null
+++ b/skills/ppt-master/scripts/spec_review/static/app.js
@@ -0,0 +1,496 @@
+'use strict';
+
+const strings = {
+ en: {
+ first: 'First', prev: 'Prev', next: 'Next', last: 'Last', source: 'View source', rendered: 'Rendered view',
+ reload: 'Reload from disk', editor: 'Block Markdown', apply: 'Apply changes', undo: 'Discard draft',
+ rebase: 'Use current disk as draft base', annotations: 'Annotations', thisBlock: 'This block', global: 'Global',
+ newAnnotation: 'New annotation', saveAnnotation: 'Save annotation', save: 'Update', remove: 'Delete',
+ annotationHint: 'Annotations are saved separately from the Design Spec.',
+ structureHint: 'Keep section headings and Slide levels/numbers. Part blocks allow title text edits only. Request page additions, deletions, or reordering in annotations.',
+ hold: 'AI is editing — Apply is paused.', changed: 'The spec changed on disk. Reload to read the latest version.',
+ conflict: 'The spec changed. Drafts are retained; reload and review the current source before choosing a new draft base.',
+ pending: 'Unapplied draft', staging: 'Staging…', clean: 'No draft', saved: 'Saved', validation: 'Schema diagnostics (saved)',
+ missing: 'This block was removed externally. Its draft is retained for copying or discarding.',
+ stale: 'Base differs from current spec', current: 'Base matches current spec', comments: 'Comments', draft: 'Draft',
+ blockChanged: 'This block changed since the comment was created', blockUnchanged: 'This block is unchanged since the comment was created',
+ blockUnknown: 'Block baseline unknown', blockMissing: 'This block no longer exists',
+ exit: 'Exit review', exitConfirm: 'There are unapplied drafts or unsaved comments. Stop review and discard pending work?',
+ stopped: 'Spec review has stopped. You can close this tab.',
+ disconnected: 'Cannot reach spec review. Local edits are retained.', rebaseConfirm: 'Stage this text against the current disk version, replacing any current staged draft? Review the source first; Apply will replace this block.',
+ },
+ zh: {
+ first: '首块', prev: '上一块', next: '下一块', last: '末块', source: '查看原文', rendered: '渲染视图',
+ reload: '重载磁盘原文', editor: '块 Markdown', apply: '应用更改', undo: '撤销草稿', rebase: '以当前磁盘版本为草稿基准',
+ annotations: '修改意见', thisBlock: '当前块', global: '全局', newAnnotation: '新增意见', saveAnnotation: '保存意见',
+ save: '更新', remove: '删除', annotationHint: '意见独立保存,不写入 Design Spec。',
+ structureHint: '保留章节标题及 Slide 层级和编号;Part 块仅可改标题文字。增页、删页、调序请写修改意见。',
+ hold: 'AI 正在修改,已暂停应用更改。', changed: '磁盘原文已变化,请重载查看最新版本。',
+ conflict: '原文已变化,草稿已保留;请重载并核对最新原文,再选择新的草稿基准。',
+ pending: '有未应用草稿', staging: '暂存中…', clean: '无草稿', saved: '已保存', validation: '校验提示(已保存)',
+ missing: '该块已被外部删除,草稿仍可复制或撤销。',
+ stale: '基准与当前原文不同', current: '基准与当前原文相同', comments: '意见', draft: '草稿',
+ blockChanged: '该块自意见创建后已变化', blockUnchanged: '该块自意见创建后未变化',
+ blockUnknown: '该块的意见基准未知', blockMissing: '该块已不存在',
+ exit: '退出评审', exitConfirm: '存在未应用草稿或未保存意见。是否停止评审并放弃待保存内容?',
+ stopped: '评审服务已停止,可以关闭此标签页。',
+ disconnected: '无法连接评审服务,本地编辑已保留。', rebaseConfirm: '以当前磁盘版本为基准暂存此内容,替换服务端的当前草稿?请先核对最新原文;应用时将替换该块。',
+ },
+ 'zh-TW': {
+ first: '首塊', prev: '上一塊', next: '下一塊', last: '末塊', source: '查看原文', rendered: '算繪檢視',
+ reload: '重新載入磁碟原文', editor: '區塊 Markdown', apply: '套用變更', undo: '撤銷草稿', rebase: '以目前磁碟版本為草稿基準',
+ annotations: '修改意見', thisBlock: '目前區塊', global: '全域', newAnnotation: '新增意見', saveAnnotation: '儲存意見',
+ save: '更新', remove: '刪除', annotationHint: '意見獨立儲存,不寫入 Design Spec。',
+ structureHint: '保留章節標題及 Slide 層級和編號;Part 區塊僅可改標題文字。增頁、刪頁、調序請寫修改意見。',
+ hold: 'AI 正在修改,已暫停套用變更。', changed: '磁碟原文已變更,請重新載入最新版本。',
+ conflict: '原文已變更,草稿已保留;請重新載入並核對原文,再選擇新的草稿基準。',
+ pending: '有未套用草稿', staging: '暫存中…', clean: '無草稿', saved: '已儲存', validation: '驗證提示(已儲存)',
+ missing: '該區塊已被外部刪除,草稿仍可複製或撤銷。',
+ stale: '基準與目前原文不同', current: '基準與目前原文相同', comments: '意見', draft: '草稿',
+ blockChanged: '該區塊自意見建立後已變更', blockUnchanged: '該區塊自意見建立後未變更',
+ blockUnknown: '該區塊的意見基準未知', blockMissing: '該區塊已不存在',
+ exit: '退出評審', exitConfirm: '存在未套用草稿或未儲存意見。是否停止評審並放棄待儲存內容?',
+ stopped: '評審服務已停止,可以關閉此分頁。',
+ disconnected: '無法連線評審服務,本機編輯已保留。', rebaseConfirm: '以目前磁碟版本為基準暫存此內容,取代伺服器上的目前草稿?請先核對最新原文;套用時將取代該區塊。',
+ },
+ ja: {
+ first: '先頭', prev: '前へ', next: '次へ', last: '末尾', source: '原文を表示', rendered: '表示に戻る',
+ reload: 'ディスクから再読込', editor: 'ブロック Markdown', apply: '変更を適用', undo: '下書きを破棄',
+ rebase: '現在の原文を下書きの基準にする', annotations: '修正コメント', thisBlock: '現在のブロック', global: '全体',
+ newAnnotation: '新しいコメント', saveAnnotation: 'コメントを保存', save: '更新', remove: '削除',
+ annotationHint: 'コメントは Design Spec と別に保存されます。',
+ structureHint: 'セクション見出しと Slide の階層・番号は固定です。Part は見出しの文字だけ変更できます。追加・削除・並べ替えはコメントで依頼してください。',
+ hold: 'AI が編集中です。変更の適用は一時停止中です。', changed: '原文が変更されました。再読込してください。',
+ conflict: '原文が変更されました。下書きは保持されています。再読込して原文を確認し、新しい基準を選択してください。',
+ pending: '未適用の下書き', staging: '一時保存中…', clean: '下書きなし', saved: '保存済み', validation: '検証結果(保存済み)',
+ missing: 'このブロックは外部で削除されました。下書きはコピーまたは破棄できます。',
+ stale: '基準が現在の原文と異なります', current: '基準は現在の原文と一致', comments: 'コメント', draft: '下書き',
+ blockChanged: 'コメント作成後にこのブロックは変更されています', blockUnchanged: 'コメント作成後にこのブロックは変更されていません',
+ blockUnknown: 'ブロックの基準は不明です', blockMissing: 'このブロックは存在しません',
+ exit: 'レビューを終了', exitConfirm: '未適用の下書きまたは未保存のコメントがあります。レビューを終了して未保存の内容を破棄しますか?',
+ stopped: 'レビューサービスは停止しました。このタブを閉じてください。',
+ disconnected: 'サービスに接続できません。編集内容は保持されています。', rebaseConfirm: '現在の原文を基準にこの内容を一時保存し、サーバーの下書きを置き換えますか?原文を先に確認してください。適用でこのブロックを置き換えます。',
+ },
+};
+const $ = id => document.getElementById(id);
+const node = (tag, text) => {
+ const result = document.createElement(tag);
+ if (text !== undefined) result.textContent = text;
+ return result;
+};
+const detected = navigator.language.toLowerCase();
+let lang = detected.startsWith('zh') ? (/tw|hk|hant/.test(detected) ? 'zh-TW' : 'zh') :
+ (detected.startsWith('ja') ? 'ja' : 'en');
+try { lang = localStorage.getItem('spec-review-language') || lang; } catch (_) { /* Optional browser storage. */ }
+if (!strings[lang]) lang = 'en';
+const t = key => strings[lang][key];
+
+// User Markdown never crosses an HTML parser boundary. Unsupported constructs
+// remain literal text; links and image syntax never create active elements.
+function inline(parent, text, depth = 0) {
+ // Bound regex backtracking even for long runs of unmatched delimiters.
+ if (depth > 12 || text.length > 4096) { parent.append(document.createTextNode(text)); return; }
+ const pattern = /(`+)(.+?)\1|\*\*(.+?)\*\*|__(.+?)__|\*([^*]+)\*|_([^_]+)_|(\$[^$\n]+\$|\\\([^\n]*?\\\))/g;
+ let start = 0;
+ for (const match of text.matchAll(pattern)) {
+ parent.append(document.createTextNode(text.slice(start, match.index)));
+ const tag = match[1] || match[7] ? 'code' : (match[3] || match[4] ? 'strong' : 'em');
+ const child = node(tag);
+ const value = match[2] || match[3] || match[4] || match[5] || match[6] || match[7];
+ if (tag === 'code') child.textContent = value;
+ else inline(child, value, depth + 1);
+ parent.append(child);
+ start = match.index + match[0].length;
+ }
+ parent.append(document.createTextNode(text.slice(start)));
+}
+
+const listItem = line => /^( *)([-+*]|\d+[.)])\s+(.*)$/.exec(line);
+const fenceLine = line => /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
+function tableCells(line) {
+ return line.trim().replace(/^\|/, '').replace(/\|$/, '').split(/(?<!\\)\|/).map(cell => cell.trim());
+}
+
+function markdown(text, target, depth = 0) {
+ if (depth > 12) { target.append(node('pre', text)); return; }
+ const lines = text.replace(/\r\n?/g, '\n').split('\n');
+ let i = 0;
+ function list(indent, nesting = 0) {
+ if (nesting > 12) {
+ const body = [];
+ while (i < lines.length && lines[i].search(/\S/) >= indent) body.push(lines[i++]);
+ return node('pre', body.join('\n'));
+ }
+ const first = listItem(lines[i]);
+ const ordered = /^\d/.test(first[2]);
+ const container = node(ordered ? 'ol' : 'ul');
+ if (ordered) container.start = parseInt(first[2], 10);
+ while (i < lines.length) {
+ const item = listItem(lines[i]);
+ if (!item || item[1].length !== indent || /^\d/.test(item[2]) !== ordered) break;
+ const li = node('li'); inline(li, item[3]); container.append(li); i++;
+ while (i < lines.length) {
+ const next = listItem(lines[i]);
+ if (next && next[1].length > indent) { li.append(list(next[1].length, nesting + 1)); continue; }
+ if (!next && lines[i].trim() && lines[i].search(/\S/) > indent) {
+ li.append(node('pre', lines[i++])); continue;
+ }
+ break;
+ }
+ }
+ return container;
+ }
+ while (i < lines.length) {
+ const line = lines[i];
+ if (!line.trim()) { i++; continue; }
+ const fence = fenceLine(line);
+ if (fence && !(fence[1][0] === '`' && fence[2].includes('`'))) {
+ const body = []; i++;
+ while (i < lines.length) {
+ const closing = fenceLine(lines[i]);
+ if (closing && closing[1][0] === fence[1][0] && closing[1].length >= fence[1].length && !closing[2].trim()) {
+ i++; break;
+ }
+ body.push(lines[i++]);
+ }
+ const pre = node('pre'); pre.append(node('code', body.join('\n'))); target.append(pre); continue;
+ }
+ if (/^\s*(\$\$|\\\[|\\begin\{)/.test(line)) {
+ const body = [line]; i++;
+ const end = line.trim().startsWith('$$') ? '$$' : (line.includes('\\[') ? '\\]' : '\\end{');
+ if (!line.trim().slice(2).includes(end)) {
+ while (i < lines.length) { const part = lines[i++]; body.push(part); if (part.includes(end)) break; }
+ }
+ target.append(node('pre', body.join('\n'))); continue;
+ }
+ const heading = /^ {0,3}(#{1,6})\s+(.*)$/.exec(line);
+ if (heading) { const h = node('h' + heading[1].length); inline(h, heading[2]); target.append(h); i++; continue; }
+ if (/^ {0,3}((\*\s*){3,}|(-\s*){3,}|(_\s*){3,})$/.test(line)) { target.append(node('hr')); i++; continue; }
+ if (/^ {0,3}>/.test(line)) {
+ const body = [];
+ while (i < lines.length && /^ {0,3}>/.test(lines[i])) body.push(lines[i++].replace(/^ {0,3}> ?/, ''));
+ const quote = node('blockquote'); markdown(body.join('\n'), quote, depth + 1); target.append(quote); continue;
+ }
+ if (line.includes('|') && i + 1 < lines.length && tableCells(lines[i + 1]).every(cell => /^:?-{3,}:?$/.test(cell))) {
+ const table = node('table'); const head = node('thead'); const row = node('tr');
+ tableCells(line).forEach(cell => { const th = node('th'); inline(th, cell); row.append(th); });
+ head.append(row); table.append(head); const body = node('tbody'); i += 2;
+ while (i < lines.length && lines[i].trim() && lines[i].includes('|')) {
+ const tr = node('tr');
+ tableCells(lines[i++]).forEach(cell => { const td = node('td'); inline(td, cell); tr.append(td); });
+ body.append(tr);
+ }
+ table.append(body); target.append(table); continue;
+ }
+ const item = listItem(line);
+ if (item) { target.append(list(item[1].length)); continue; }
+ if (/^( {4}|\t)|^\s*(<|!\[|\[\^|\[.+\]:|[|]|:::|\\|={3,}\s*$)/.test(line)) {
+ target.append(node('pre', line)); i++; continue;
+ }
+ const body = [line]; i++;
+ while (i < lines.length && lines[i].trim() && !listItem(lines[i]) && !fenceLine(lines[i]) &&
+ !/^\s*(#|>|\||<|!\[|\[|\\|\$\$|:::|[-*_]{3,}|={3,})|^( {4}|\t)/.test(lines[i]) &&
+ !(lines[i].includes('|') && i + 1 < lines.length &&
+ tableCells(lines[i + 1]).every(cell => /^:?-{3,}:?$/.test(cell)))) {
+ body.push(lines[i++]);
+ }
+ const paragraph = node('p'); inline(paragraph, body.join('\n')); target.append(paragraph);
+ }
+}
+
+let metadata = {blocks: [], orphan_drafts: [], draft_keys: [], sha256: '', hold: false, hold_revision: 0};
+let current = null;
+let source = false;
+let stageTimer;
+let stopped = false;
+let applying = false;
+let queue = Promise.resolve();
+const drafts = new Map();
+const annotationBuffers = new Map();
+let comments = [];
+const pathKey = key => encodeURIComponent(key);
+const hasDrafts = () => drafts.size > 0 || metadata.draft_keys.length > 0;
+const annotationKey = () => $('scope').value === 'global' ? 'global' : current?.key;
+function navigationBlocks() {
+ const blocks = [...metadata.blocks, ...metadata.orphan_drafts];
+ for (const [key, draft] of drafts) {
+ if (!blocks.some(block => block.key === key)) blocks.push({key, title: draft.title || key, kind: 'missing'});
+ }
+ return blocks;
+}
+
+async function api(path, method = 'GET', data) {
+ let response;
+ try {
+ response = await fetch(path, {method, cache: 'no-store', headers: {'Content-Type': 'application/json'},
+ body: data === undefined ? undefined : JSON.stringify(data)});
+ } catch (_) { throw new Error(t('disconnected')); }
+ const result = await response.json();
+ if (!response.ok) {
+ const error = new Error(result.error || String(response.status)); error.status = response.status; throw error;
+ }
+ return result;
+}
+function showError(error) {
+ $('error').textContent = error.message; $('error').hidden = false;
+ if (error.status === 409) showConflict(true);
+ if (error.status === 423) { metadata.hold = true; renderStatus(); }
+}
+function run(action) {
+ queue = queue.then(() => { if (!stopped) return action(); }).catch(showError);
+ return queue;
+}
+function showConflict(conflict = hasDrafts()) {
+ $('conflict').textContent = t(conflict ? 'conflict' : 'changed'); $('conflict').hidden = false;
+}
+function renderStatus() {
+ $('hold').textContent = t('hold'); $('hold').hidden = !metadata.hold;
+ const draft = drafts.get(current?.key);
+ $('draft-status').textContent = t(draft?.dirty ? 'staging' : (draft ? 'pending' : 'clean'));
+ $('editor').disabled = applying || !current;
+ $('apply').disabled = applying || !draft || metadata.hold || current?.missing;
+ $('undo').disabled = applying || !draft;
+ $('rebase').disabled = applying;
+ $('rebase').hidden = !draft || current?.missing || (draft.sha256 === current?.sha256 &&
+ (draft.version || null) === (current?.draft?.version || null));
+ $('fingerprint').textContent = current?.sha256 ?? metadata.sha256;
+}
+function renderNavigation() {
+ $('blocks').replaceChildren();
+ const blocks = navigationBlocks();
+ blocks.forEach(block => {
+ const button = node('button', block.title.replace(/^\s*#+\s*/, ''));
+ button.className = [block.kind, block.key === current?.key ? 'selected' : ''].join(' ');
+ if (block.key === current?.key) button.setAttribute('aria-current', 'true');
+ if (block.has_annotations) button.append(Object.assign(node('span', t('comments')), {className: 'badge'}));
+ if (block.has_draft || drafts.has(block.key)) button.append(Object.assign(node('span', t('draft')), {className: 'badge'}));
+ button.addEventListener('click', () => navigate(block.key)); $('blocks').append(button);
+ });
+ const index = blocks.findIndex(block => block.key === current?.key);
+ $('position').textContent = blocks.length ? `${index + 1} / ${blocks.length}` : '0 / 0';
+ $('first').disabled = $('prev').disabled = index <= 0;
+ $('next').disabled = $('last').disabled = index >= blocks.length - 1;
+}
+function renderPreview() {
+ const text = drafts.get(current?.key)?.text ?? current?.text ?? '';
+ $('preview').replaceChildren();
+ try { markdown(text, $('preview')); }
+ catch (_) { $('preview').replaceChildren(node('pre', text)); }
+ // Source view always shows the current disk block, so a stale draft can be
+ // compared with its replacement before explicitly choosing a new base.
+ $('raw').textContent = current?.text || '';
+ $('raw').hidden = !source; $('preview').hidden = source;
+ $('source').textContent = t(source ? 'rendered' : 'source');
+ $('source').setAttribute('aria-pressed', String(source));
+}
+async function stage(key, text = drafts.get(key)?.text) {
+ const draft = drafts.get(key);
+ if (!draft) return;
+ if (!draft.dirty && draft.text === text) return {...draft};
+ const result = await api('/api/drafts/' + pathKey(key), 'PUT', {
+ text, sha256: draft.sha256, version: draft.version || null,
+ });
+ draft.version = result.version;
+ draft.dirty = draft.text !== text;
+ if (current?.key === key) current.draft = result;
+ if (!metadata.draft_keys.includes(key)) metadata.draft_keys.push(key);
+ renderStatus(); renderNavigation();
+ return result;
+}
+async function loadComments() {
+ comments = (await api('/api/annotations')).annotations; renderComments();
+}
+function renderComments() {
+ $('comments').replaceChildren();
+ for (const item of comments.filter(item => item.key === annotationKey())) {
+ const card = node('div'); card.className = 'comment';
+ card.append(node('small', `${item.id} · ${item.title}`));
+ const status = item.key === 'global' ? (item.base_current ? 'current' : 'stale') :
+ (item.block_missing ? 'blockMissing' : (item.block_changed === true ? 'blockChanged' :
+ (item.block_changed === false ? 'blockUnchanged' : 'blockUnknown')));
+ card.append(node('small', t(status)));
+ const textarea = node('textarea'); textarea.rows = 4; textarea.value = annotationBuffers.get(item.id) ?? item.body;
+ textarea.addEventListener('input', () => annotationBuffers.set(item.id, textarea.value)); card.append(textarea);
+ const buttons = node('div'); buttons.className = 'toolbar';
+ const save = node('button', t('save')); const remove = node('button', t('remove'));
+ save.addEventListener('click', () => {
+ const body = textarea.value;
+ run(async () => {
+ const result = await api('/api/annotations/' + item.id, 'PUT', {body, revision: item.revision});
+ Object.assign(item, result);
+ if (annotationBuffers.get(item.id) === body) annotationBuffers.delete(item.id);
+ await refreshMetadata(); await loadComments();
+ });
+ });
+ remove.addEventListener('click', () => run(async () => {
+ await api('/api/annotations/' + item.id, 'DELETE', {revision: item.revision});
+ annotationBuffers.delete(item.id); await refreshMetadata(); await loadComments();
+ }));
+ buttons.append(save, remove); card.append(buttons); $('comments').append(card);
+ }
+ $('annotation').value = annotationBuffers.get('new:' + annotationKey()) || '';
+}
+async function refreshMetadata() {
+ metadata = await api('/api/blocks');
+ if (current && current.sha256 !== metadata.sha256) showConflict();
+ renderNavigation(); renderStatus();
+}
+async function select(key) {
+ if (!key) { current = null; $('editor').disabled = true; renderStatus(); return; }
+ let block;
+ try { block = await api('/api/blocks/' + pathKey(key)); }
+ catch (error) {
+ if (error.status !== 404 || !drafts.has(key)) throw error;
+ block = {key, title: drafts.get(key).title || key, text: '', sha256: metadata.sha256, missing: true};
+ }
+ current = block;
+ if (block.draft && !drafts.has(key)) drafts.set(key, {...block.draft, dirty: false});
+ const draft = drafts.get(key);
+ if (draft && block.draft && !draft.dirty && draft.version === block.draft.version) {
+ draft.sha256 = block.draft.sha256;
+ }
+ $('title').textContent = block.title;
+ $('editor').value = draft?.text ?? block.text; $('editor').disabled = false; $('editor').readOnly = !!block.missing;
+ renderPreview(); renderNavigation(); renderStatus(); renderComments();
+ if (draft && draft.sha256 !== block.sha256) showConflict(true);
+ if (block.missing) { $('conflict').textContent = t('missing'); $('conflict').hidden = false; }
+}
+function navigate(key) {
+ run(async () => {
+ clearTimeout(stageTimer);
+ if (current) await stage(current.key).catch(showError);
+ await select(key);
+ });
+}
+async function reload() {
+ const key = current?.key;
+ await refreshMetadata();
+ $('conflict').hidden = true;
+ const blocks = navigationBlocks();
+ await select(blocks.some(block => block.key === key) ? key : blocks[0]?.key);
+ await loadComments();
+ if ([...drafts.values()].some(draft => draft.sha256 !== metadata.sha256)) showConflict(true);
+}
+function localize() {
+ document.documentElement.lang = lang; $('language').value = lang;
+ document.querySelectorAll('[data-label]').forEach(element => { element.textContent = t(element.dataset.label); });
+ if (stopped) { $('stopped').textContent = t('stopped'); return; }
+ renderStatus(); renderNavigation(); renderPreview(); renderComments();
+ if (!$('conflict').hidden) showConflict();
+}
+
+$('language').addEventListener('change', () => {
+ lang = $('language').value;
+ try { localStorage.setItem('spec-review-language', lang); } catch (_) { /* Optional browser storage. */ }
+ localize();
+});
+$('source').addEventListener('click', () => { source = !source; renderPreview(); });
+$('reload').addEventListener('click', () => run(reload));
+$('exit').addEventListener('click', () => run(async () => {
+ await refreshMetadata();
+ if ((hasDrafts() || [...annotationBuffers.values()].some(Boolean)) && !window.confirm(t('exitConfirm'))) return;
+ clearTimeout(stageTimer);
+ await api('/api/shutdown', 'POST', {});
+ stopped = true; clearInterval(pollTimer);
+ document.querySelector('.workspace').hidden = true;
+ for (const id of ['hold', 'conflict', 'error', 'exit']) $(id).hidden = true;
+ $('fingerprint').textContent = '';
+ $('stopped').textContent = t('stopped'); $('stopped').hidden = false;
+}));
+$('scope').addEventListener('change', renderComments);
+$('annotation').addEventListener('input', () => annotationBuffers.set('new:' + annotationKey(), $('annotation').value));
+$('editor').addEventListener('input', () => {
+ if (!current) return;
+ const key = current.key;
+ const draft = drafts.get(key) || {sha256: current.sha256, version: null, title: current.title};
+ Object.assign(draft, {text: $('editor').value, dirty: true}); drafts.set(key, draft);
+ renderPreview(); renderStatus(); renderNavigation();
+ clearTimeout(stageTimer); stageTimer = setTimeout(() => run(() => stage(key)), 350);
+});
+$('apply').addEventListener('click', () => {
+ const key = current?.key; const draft = drafts.get(key);
+ if (!draft || applying) return;
+ const snapshot = {...draft};
+ applying = true; clearTimeout(stageTimer); renderStatus();
+ run(async () => {
+ try {
+ if (drafts.get(key) !== draft) { showConflict(true); return; }
+ // The queue awaits earlier stages; stage this click's text with their returned version.
+ const staged = await stage(key, snapshot.text); const base = staged.sha256;
+ const result = await api('/api/apply/' + pathKey(key), 'POST', {sha256: base, version: staged.version});
+ if (draft.text === snapshot.text) drafts.delete(key);
+ else Object.assign(draft, {version: null, dirty: true});
+ for (const other of drafts.values()) if (other.sha256 === base) other.sha256 = result.sha256;
+ $('validation-errors').textContent = result.validation_errors.join('\n');
+ $('validation').hidden = result.validation_errors.length === 0;
+ $('error').hidden = true; await reload();
+ if (current?.key === key && !drafts.has(key)) $('draft-status').textContent = t('saved');
+ } finally { applying = false; renderStatus(); }
+ });
+});
+$('undo').addEventListener('click', () => run(async () => {
+ const key = current.key; const draft = drafts.get(key);
+ const latest = current.missing && !draft?.version ? current : await api('/api/blocks/' + pathKey(key));
+ if (draft?.version && draft.version === latest.draft?.version) {
+ await api('/api/drafts/' + pathKey(key), 'DELETE', {version: draft.version});
+ }
+ drafts.delete(key); $('error').hidden = true; await reload();
+}));
+$('rebase').addEventListener('click', () => run(async () => {
+ if (!window.confirm(t('rebaseConfirm'))) return;
+ const draft = drafts.get(current.key);
+ const latest = await api('/api/blocks/' + pathKey(current.key));
+ if (latest.sha256 !== current.sha256 || (latest.draft?.version || null) !== (current.draft?.version || null)) {
+ await reload(); showConflict(true); return;
+ }
+ const text = draft.text;
+ const result = await api('/api/drafts/' + pathKey(current.key), 'PUT', {
+ text, sha256: latest.sha256, version: latest.draft?.version || null,
+ });
+ Object.assign(draft, {sha256: result.sha256, version: result.version, dirty: draft.text !== text});
+ $('error').hidden = true; await reload();
+}));
+$('add').addEventListener('click', () => {
+ const key = annotationKey(); const body = annotationBuffers.get('new:' + key) || '';
+ run(async () => {
+ await api('/api/annotations', 'POST', {key, body});
+ if (annotationBuffers.get('new:' + key) === body) annotationBuffers.delete('new:' + key);
+ await refreshMetadata(); await loadComments();
+ });
+});
+function step(direction) {
+ const blocks = navigationBlocks();
+ const index = blocks.findIndex(block => block.key === current?.key);
+ const next = direction === 'first' ? 0 : (direction === 'last' ? blocks.length - 1 : index + direction);
+ if (blocks[next]) navigate(blocks[next].key);
+}
+for (const [id, direction] of [['first', 'first'], ['prev', -1], ['next', 1], ['last', 'last']]) {
+ $(id).addEventListener('click', () => step(direction));
+}
+document.addEventListener('keydown', event => {
+ if (stopped) return;
+ if (event.target.closest('input, textarea, select, [contenteditable]') || event.ctrlKey || event.metaKey || event.altKey) return;
+ const action = {ArrowLeft: -1, ArrowRight: 1, Home: 'first', End: 'last'}[event.key];
+ if (action !== undefined) { event.preventDefault(); step(action); }
+});
+window.addEventListener('beforeunload', event => {
+ if (!stopped && (hasDrafts() || [...annotationBuffers.values()].some(Boolean))) {
+ event.preventDefault(); event.returnValue = '';
+ }
+});
+let polling = false;
+const pollTimer = setInterval(async () => {
+ if (polling || stopped) return;
+ polling = true;
+ try {
+ const state = await api('/api/state');
+ if (stopped) return;
+ const released = !state.hold && state.hold_revision !== metadata.hold_revision;
+ metadata.hold = state.hold; metadata.hold_revision = state.hold_revision;
+ renderStatus();
+ if (released) await run(reload);
+ else if (state.sha256 !== (current?.sha256 ?? metadata.sha256)) showConflict();
+ } catch (error) { if (!stopped) showError(error); }
+ finally { polling = false; }
+}, 2000);
+localize(); run(reload);
diff --git a/skills/ppt-master/scripts/spec_review/static/index.html b/skills/ppt-master/scripts/spec_review/static/index.html
new file mode 100644
index 00000000..6dccd4a3
--- /dev/null
+++ b/skills/ppt-master/scripts/spec_review/static/index.html
@@ -0,0 +1,60 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>PPT Master · Spec Review</title>
+ <link rel="stylesheet" href="/static/style.css">
+ <script src="/static/app.js" defer></script>
+</head>
+<body>
+ <header><strong>PPT Master · Spec Review</strong><span id="fingerprint"></span>
+ <select id="language" aria-label="Language">
+ <option value="zh">中文</option><option value="zh-TW">繁體中文</option>
+ <option value="en">English</option><option value="ja">日本語</option>
+ </select>
+ <button id="exit" data-label="exit"></button>
+ </header>
+ <p id="stopped" class="banner" role="status" hidden></p>
+ <div id="hold" class="banner" role="status" hidden></div>
+ <div id="conflict" class="banner" role="status" hidden></div>
+ <div id="error" class="banner error" role="alert" hidden></div>
+ <div class="workspace">
+ <aside class="navigation">
+ <div class="navigation-buttons">
+ <button id="first" data-label="first"></button><button id="prev" data-label="prev"></button>
+ <button id="next" data-label="next"></button><button id="last" data-label="last"></button>
+ </div>
+ <div id="position"></div><nav id="blocks" aria-label="Spec blocks"></nav>
+ </aside>
+ <main>
+ <div class="toolbar"><h1 id="title"></h1>
+ <button id="source" data-label="source" aria-pressed="false"></button>
+ <button id="reload" data-label="reload"></button>
+ </div>
+ <article id="preview" class="markdown"></article>
+ <pre id="raw" hidden></pre>
+ <section class="editor">
+ <label for="editor" data-label="editor"></label>
+ <p class="hint" data-label="structureHint"></p>
+ <textarea id="editor" spellcheck="false"></textarea>
+ <div class="toolbar"><span id="draft-status" role="status"></span>
+ <button id="undo" data-label="undo"></button><button id="rebase" data-label="rebase" hidden></button>
+ <button id="apply" class="primary" data-label="apply"></button>
+ </div>
+ <div id="validation" hidden><h2 data-label="validation"></h2><pre id="validation-errors"></pre></div>
+ </section>
+ </main>
+ <aside class="annotations">
+ <h2 data-label="annotations"></h2>
+ <select id="scope" aria-label="Annotation scope"><option value="block" data-label="thisBlock"></option>
+ <option value="global" data-label="global"></option></select>
+ <div id="comments"></div>
+ <label for="annotation" data-label="newAnnotation"></label>
+ <textarea id="annotation" rows="6"></textarea>
+ <button id="add" class="primary" data-label="saveAnnotation"></button>
+ <p class="hint" data-label="annotationHint"></p>
+ </aside>
+ </div>
+</body>
+</html>
diff --git a/skills/ppt-master/scripts/spec_review/static/style.css b/skills/ppt-master/scripts/spec_review/static/style.css
new file mode 100644
index 00000000..bfbf94f0
--- /dev/null
+++ b/skills/ppt-master/scripts/spec_review/static/style.css
@@ -0,0 +1,74 @@
+:root {
+ color-scheme: dark;
+ --bg: #12121f;
+ --panel: #1a1a2e;
+ --line: #34344c;
+ --text: #e4e5ef;
+ --muted: #a4a7bf;
+ --accent: #4a9eff;
+}
+* { box-sizing: border-box; }
+[hidden] { display: none !important; }
+body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.6 system-ui, sans-serif; }
+header { padding: 12px 20px; border-bottom: 1px solid var(--line); display: flex; gap: 20px; align-items: center; }
+header strong { color: var(--accent); }
+#fingerprint { flex: 1; color: var(--muted); font-family: monospace; overflow-wrap: anywhere; }
+button, select, textarea { font: inherit; color: inherit; background: #23233b; border: 1px solid var(--line); border-radius: 5px; }
+button { cursor: pointer; padding: 6px 10px; }
+button:hover { border-color: var(--accent); }
+button:disabled { opacity: .45; cursor: default; }
+button.primary { color: #07192f; background: var(--accent); font-weight: 600; }
+select { padding: 6px; }
+textarea { width: 100%; resize: vertical; padding: 12px; }
+button:focus-visible, select:focus-visible, textarea:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.workspace { display: grid; grid-template-columns: 245px minmax(320px, 1fr) 300px; height: calc(100vh - 60px); }
+aside, main { overflow: auto; min-width: 0; padding: 16px; }
+aside { background: var(--panel); }
+.navigation { border-right: 1px solid var(--line); }
+.annotations { border-left: 1px solid var(--line); }
+.navigation-buttons { display: flex; flex-wrap: wrap; gap: 4px; }
+#position { color: var(--muted); padding: 10px 0; }
+#blocks { display: flex; flex-direction: column; gap: 4px; }
+#blocks button { text-align: left; border-color: transparent; background: transparent; overflow-wrap: anywhere; }
+#blocks button.slide { padding-left: 22px; }
+#blocks button.part { margin-top: 12px; border-top: 1px solid var(--line); border-radius: 0; font-weight: 700; color: var(--accent); }
+#blocks button.selected { background: #273552; border-color: var(--accent); }
+.badge { color: #eabd64; margin-left: 7px; font-size: 11px; }
+.toolbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
+.toolbar h1 { font-size: 19px; flex: 1 1 100%; margin: 0 0 8px; }
+.toolbar span { flex: 1; }
+.hint { color: var(--muted); font-size: 12px; }
+.banner { padding: 8px 20px; background: #4b3a20; white-space: pre-wrap; }
+.banner.error { background: #552933; }
+.editor { margin-top: 24px; border-top: 1px solid var(--line); padding-top: 18px; }
+#editor { min-height: 300px; font: 13px/1.6 ui-monospace, monospace; tab-size: 4; }
+#draft-status { color: #eabd64; }
+#validation { color: #edbd6c; }
+.annotations h2 { margin-top: 0; font-size: 17px; }
+.annotations label { display: block; margin-top: 18px; }
+.comment { padding: 14px 0; border-bottom: 1px solid var(--line); }
+.comment small { display: block; color: var(--muted); overflow-wrap: anywhere; }
+.comment .toolbar { margin-top: 6px; }
+.markdown { margin-top: 24px; overflow-wrap: anywhere; }
+.markdown h1, .markdown h2, .markdown h3, .markdown h4 { line-height: 1.35; }
+.markdown h2 { border-bottom: 1px solid var(--line); padding-bottom: 8px; font-size: 22px; }
+.markdown h4 { color: #b8d7ff; font-size: 20px; }
+.markdown li { margin: 5px 0; }
+.markdown blockquote { border-left: 3px solid var(--accent); margin-left: 0; padding: 1px 16px; color: var(--muted); }
+.markdown table { border-collapse: collapse; width: 100%; font-size: 13px; margin: 18px 0; }
+.markdown th, .markdown td { border: 1px solid var(--line); padding: 7px 10px; text-align: left; }
+.markdown th { background: var(--panel); }
+pre, code { font-family: ui-monospace, monospace; background: #0e101c; }
+pre { padding: 14px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; tab-size: 4; }
+code { padding: 2px 4px; border-radius: 3px; }
+pre code { padding: 0; }
+hr { border: 0; border-top: 1px solid var(--line); margin: 24px 0; }
+@media (max-width: 1000px) {
+ .workspace { grid-template-columns: 190px minmax(300px, 1fr); height: auto; }
+ .annotations { grid-column: 1 / -1; border-top: 1px solid var(--line); }
+}
+@media (max-width: 600px) {
+ header { flex-wrap: wrap; }
+ .workspace { display: block; }
+ .navigation { max-height: 240px; }
+}
diff --git a/skills/ppt-master/scripts/spec_review/store.py b/skills/ppt-master/scripts/spec_review/store.py
new file mode 100644
index 00000000..32a10f5f
--- /dev/null
+++ b/skills/ppt-master/scripts/spec_review/store.py
@@ -0,0 +1,352 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Spec Review Storage
+
+Serialize annotation transactions and stage lossless edits of one Design Spec.
+See scripts/docs/spec_review.md for the sidecars and HTTP contract.
+
+Usage:
+ Import ReviewStore from this module.
+
+Examples:
+ store = ReviewStore(project_path)
+
+Dependencies:
+ None (only uses the standard library and local project modules)
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import stat
+import tempfile
+import threading
+import uuid
+from contextlib import contextmanager
+from dataclasses import asdict
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Iterator
+
+from project_management.project_specs import SCHEMA_DIR, validate_markdown_text
+from project_management.spec_blocks import replace_spec_block, split_spec_blocks
+
+
+class ReviewError(ValueError):
+ """Report an actionable HTTP/CLI conflict without losing pending work."""
+
+ def __init__(self, message: str, status: int = 400):
+ super().__init__(message)
+ self.status = status
+
+
+def sha256(data: bytes) -> str:
+ """Hash exactly the bytes on disk."""
+ return hashlib.sha256(data).hexdigest()
+
+
+def timestamp() -> str:
+ """Return an unambiguous UTC event time."""
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _annotation_fingerprint(item: dict) -> str:
+ return sha256(json.dumps(item, sort_keys=True, ensure_ascii=False).encode("utf-8"))
+
+
+@contextmanager
+def file_mutex(path: Path) -> Iterator[None]:
+ """Hold a cross-process lock, released by the OS even after a crash."""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("a+b") as handle:
+ if os.name == "nt":
+ import msvcrt
+
+ if handle.tell() == 0:
+ handle.write(b"\0")
+ handle.flush()
+ handle.seek(0)
+ msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
+ try:
+ yield
+ finally:
+ handle.seek(0)
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
+ try:
+ yield
+ finally:
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
+
+
+def atomic_write(path: Path, data: bytes) -> None:
+ """Flush a sibling temporary file and atomically replace its destination."""
+ descriptor, name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
+ temporary = Path(name)
+ try:
+ with os.fdopen(descriptor, "wb") as handle:
+ handle.write(data)
+ handle.flush()
+ os.fsync(handle.fileno())
+ if path.exists():
+ temporary.chmod(stat.S_IMODE(path.stat().st_mode))
+ os.replace(temporary, path)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+class ReviewStore:
+ """Keep drafts in memory and comments in one process-safe sidecar."""
+
+ def __init__(self, project: Path):
+ self.project = project.resolve()
+ self.path = self.project / "design_spec.md"
+ self.runtime = self.project / "spec_review"
+ self.mutex = threading.RLock()
+ self.drafts: dict[str, dict] = {}
+ self.hold = False
+ self.hold_revision = 0
+
+ def _read(self) -> tuple[bytes, str, str]:
+ raw = self.path.read_bytes()
+ return raw, raw.decode("utf-8"), sha256(raw)
+
+ def _append(self, filename: str, record: dict) -> None:
+ self.runtime.mkdir(parents=True, exist_ok=True)
+ with (self.runtime / filename).open("a", encoding="utf-8", newline="\n") as handle:
+ handle.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+
+ @contextmanager
+ def _annotations(self) -> Iterator[dict]:
+ with self.mutex, file_mutex(self.runtime / "storage.guard"):
+ path = self.runtime / "annotations.json"
+ data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {"items": [], "listed": {}}
+ if not isinstance(data, dict) or not isinstance(data.get("items"), list) or not isinstance(
+ data.get("listed"), dict
+ ):
+ raise ValueError("Invalid annotations.json; repair the sidecar before continuing.")
+ yield data
+
+ def _save_annotations(self, data: dict) -> None:
+ atomic_write(
+ self.runtime / "annotations.json",
+ (json.dumps(data, ensure_ascii=False, indent=2) + "\n").encode("utf-8"),
+ )
+
+ def state(self) -> dict:
+ """Return the current disk hash and handoff state."""
+ with self.mutex:
+ _, _, digest = self._read()
+ return {"sha256": digest, "hold": self.hold, "hold_revision": self.hold_revision}
+
+ def snapshot(self) -> dict:
+ """Return ordered block metadata and per-block pending status."""
+ with self.mutex, self._annotations() as data:
+ _, text, digest = self._read()
+ pending = {item["key"] for item in data["items"]}
+ blocks = [
+ {**asdict(block), "has_annotations": block.key in pending, "has_draft": block.key in self.drafts}
+ for block in split_spec_blocks(text).blocks
+ ]
+ live_keys = {block["key"] for block in blocks}
+ orphans = [
+ {"key": key, "title": draft["title"], "kind": "missing", "has_draft": True,
+ "has_annotations": key in pending}
+ for key, draft in self.drafts.items() if key not in live_keys
+ ]
+ return {
+ "sha256": digest, "hold": self.hold, "hold_revision": self.hold_revision,
+ "blocks": blocks, "global_annotations": "global" in pending,
+ "draft_keys": list(self.drafts),
+ "orphan_drafts": orphans,
+ }
+
+ def document(self) -> dict:
+ """Read the full raw spec without universal-newline translation."""
+ with self.mutex:
+ _, text, digest = self._read()
+ return {"text": text, "sha256": digest}
+
+ def block(self, key: str) -> dict:
+ """Return original block text and its separate in-memory draft."""
+ with self.mutex:
+ _, text, digest = self._read()
+ block = next((block for block in split_spec_blocks(text).blocks if block.key == key), None)
+ if block is None:
+ if key in self.drafts:
+ draft = self.drafts[key]
+ return {"key": key, "title": draft["title"], "text": "", "sha256": digest,
+ "draft": draft, "missing": True}
+ raise ReviewError("Block no longer exists; reload the spec.", 404)
+ return {**asdict(block), "text": text[block.start:block.end], "sha256": digest,
+ "draft": self.drafts.get(key)}
+
+ def stage(self, key: str, text: str, base: str, version: str | None) -> dict:
+ """Stage text without touching the spec; preserve stale drafts for review."""
+ with self.mutex:
+ block = self.block(key)
+ current = self.drafts.get(key)
+ if (current or {}).get("version") != version:
+ raise ReviewError("Another tab changed this draft; reload before editing it.", 409)
+ if base != block["sha256"] and (not current or current["sha256"] != base):
+ raise ReviewError("The spec changed on disk; reload. Your local draft is retained.", 409)
+ draft = {"text": text, "sha256": base, "version": uuid.uuid4().hex, "title": block["title"]}
+ self.drafts[key] = draft
+ return draft
+
+ def discard(self, key: str, version: str | None) -> None:
+ """Discard only the draft version the browser actually saw."""
+ with self.mutex:
+ if (self.drafts.get(key) or {}).get("version") != version:
+ raise ReviewError("Another tab changed this draft; reload before discarding it.", 409)
+ self.drafts.pop(key, None)
+
+ def set_hold(self, enabled: bool) -> dict:
+ """Wait for any active Apply, then switch the write handoff state."""
+ with self.mutex:
+ if self.hold != enabled:
+ self.hold_revision += 1
+ self.hold = enabled
+ return self.state()
+
+ def apply(self, key: str, base: str, version: str) -> dict:
+ """Compare, validate, and atomically replace one byte range under a lock."""
+ with self.mutex, file_mutex(self.runtime / "storage.guard"):
+ if self.hold:
+ raise ReviewError("AI is editing; Apply is paused until hold is off.", 423)
+ raw, text, digest = self._read()
+ draft = self.drafts.get(key)
+ if base != digest or (draft and draft["sha256"] != digest):
+ raise ReviewError("The spec changed on disk; reload. The draft is retained.", 409)
+ if not draft or draft["version"] != version:
+ raise ReviewError("The staged draft changed; reload before applying it.", 409)
+ try:
+ candidate = replace_spec_block(text, key, draft["text"])
+ except ValueError as exc:
+ raise ReviewError(str(exc)) from exc
+ blocks = split_spec_blocks(text).blocks
+ before = next(block for block in blocks if block.key == key)
+ after = next(block for block in split_spec_blocks(candidate).blocks if block.key == key)
+ new_text = candidate[after.start:after.end]
+ payload = raw[:before.byte_start] + new_text.encode("utf-8") + raw[before.byte_end:]
+ errors = validate_markdown_text(candidate, SCHEMA_DIR / "design_spec.schema.json", markdown_path=self.path)
+ if sha256(self.path.read_bytes()) != digest:
+ raise ReviewError("The spec changed during validation; reload. The draft is retained.", 409)
+ new_digest = sha256(payload)
+ if payload != raw:
+ atomic_write(self.path, payload)
+ self._append("edits.jsonl", {
+ "ts": timestamp(), "key": key, "title": after.title,
+ "before": text[before.start:before.end], "after": new_text,
+ "before_sha256": digest, "after_sha256": new_digest,
+ })
+ del self.drafts[key]
+ # Other blocks were byte-identical; our own successful edit does not
+ # invalidate their drafts. External edits never take this path.
+ for remaining in self.drafts.values():
+ if remaining["sha256"] == digest:
+ remaining["sha256"] = new_digest
+ return {"sha256": new_digest, "validation_errors": errors, "saved": True}
+
+ def annotations(self) -> list[dict]:
+ """Read comments without acknowledging them on behalf of an agent."""
+ with self._annotations() as data:
+ _, text, digest = self._read()
+ return self._current_annotations(data, text, digest)
+
+ def _current_annotations(self, data: dict, text: str, digest: str) -> list[dict]:
+ block_hashes = {
+ block.key: sha256(text[block.start:block.end].encode("utf-8"))
+ for block in split_spec_blocks(text).blocks
+ }
+ items = []
+ for item in data["items"]:
+ if item["key"] == "global":
+ status = {"base_current": item["spec_sha256"] == digest}
+ else:
+ current = block_hashes.get(item["key"])
+ base = item.get("block_sha256")
+ status = {"block_missing": current is None,
+ "block_changed": current != base if current is not None and base else None}
+ items.append({**item, **status})
+ return items
+
+ def save_annotation(self, key: str, body: str, item_id: str | None = None, revision: str | None = None) -> dict:
+ """Create or update a comment, keeping its creation-time fingerprints."""
+ if not body.strip():
+ raise ReviewError("Enter an annotation before saving.")
+ with self._annotations() as data:
+ if item_id:
+ item = next((item for item in data["items"] if item["id"] == item_id), None)
+ if item is None or item["revision"] != revision:
+ raise ReviewError("The annotation changed or was removed; reload it.", 409)
+ event = "updated"
+ else:
+ block = self.block(key) if key != "global" else {"title": "Global", **self.document()}
+ item = {"id": uuid.uuid4().hex, "key": key, "title": block["title"],
+ "spec_sha256": block["sha256"], "created_at": timestamp()}
+ if key != "global" and not block.get("missing"):
+ item["block_sha256"] = sha256(block["text"].encode("utf-8"))
+ data["items"].append(item)
+ event = "saved"
+ item.update(body=body, updated_at=timestamp(), revision=uuid.uuid4().hex)
+ self._save_annotations(data)
+ self._append("annotations.jsonl", {"event": event, "ts": timestamp(), **item})
+ return item
+
+ def remove_annotation(self, item_id: str, revision: str | None = None, *, applied: bool = False) -> None:
+ """Clear a comment only if its browser/listed version still matches."""
+ with self._annotations() as data:
+ item = next((item for item in data["items"] if item["id"] == item_id), None)
+ expected = data["listed"].get(item_id) if applied else revision
+ actual = _annotation_fingerprint(item) if applied and item is not None else (item or {}).get("revision")
+ if item is None or actual != expected:
+ raise ReviewError(
+ "Annotation changed since it was listed, or was not listed; retained. List again.", 409,
+ )
+ data["items"].remove(item)
+ data["listed"].pop(item_id, None)
+ self._save_annotations(data)
+ self._append("annotations.jsonl", {
+ "event": "annotation_applied" if applied else "removed", "ts": timestamp(), **item,
+ })
+
+ def list_todo(self) -> dict:
+ """Record listed comment revisions and the last unread edit's byte offset."""
+ with self._annotations() as data:
+ _, text, digest = self._read()
+ fields = ("id", "key", "title", "body", "spec_sha256", "block_sha256",
+ "base_current", "block_changed", "block_missing")
+ items = [{key: item[key] for key in fields if key in item}
+ for item in self._current_annotations(data, text, digest)]
+ edits_path = self.runtime / "edits.jsonl"
+ edits = []
+ cursor = data.get("edits_cursor", 0)
+ if edits_path.exists():
+ with edits_path.open("rb") as handle:
+ handle.seek(cursor)
+ for line in handle:
+ event = json.loads(line)
+ edits.append({**{key: event[key] for key in ("ts", "key", "title")},
+ **{key: event[key][:12] for key in ("before_sha256", "after_sha256")}})
+ cursor = handle.tell()
+ data["listed"] = {item["id"]: _annotation_fingerprint(item) for item in data["items"]}
+ data["listed_edits_cursor"] = cursor
+ self._save_annotations(data)
+ return {"sha256": digest, "annotations": items, "edits": edits}
+
+ def ack_edits(self) -> int:
+ """Consume only edits included in the last CLI listing, preserving the log."""
+ with self._annotations() as data:
+ if "listed_edits_cursor" not in data:
+ raise ReviewError("List direct edits before acknowledging them.", 409)
+ data["edits_cursor"] = data["listed_edits_cursor"]
+ self._save_annotations(data)
+ return data["edits_cursor"]
diff --git a/skills/ppt-master/scripts/tests/test_spec_review.py b/skills/ppt-master/scripts/tests/test_spec_review.py
new file mode 100644
index 00000000..4f275802
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_spec_review.py
@@ -0,0 +1,585 @@
+#!/usr/bin/env python3
+"""Regression tests for lossless spec review, concurrent edits, and comment receipts."""
+
+from __future__ import annotations
+
+import io
+import json
+import sys
+import tempfile
+import unittest
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+from unittest.mock import Mock, patch
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+
+from check_spec_annotations import main as check_main # noqa: E402
+from project_management.spec_blocks import replace_spec_block, split_spec_blocks # noqa: E402
+from project_specs import SCHEMA_DIR, validate_markdown_schema, validate_markdown_text # noqa: E402
+from spec_review.server import create_app, main as server_main # noqa: E402
+from spec_review.store import ReviewError, ReviewStore, sha256 # noqa: E402
+
+
+SPEC = """<!-- ppt-master-schema: design-spec/v1 -->
+# Complete 深度 - Design Spec
+
+## I. Project Information
+| Item | Value |
+| --- | --- |
+| Page Count | 2 |
+| Design Spec Depth | complete |
+
+## II. Canvas Specification
+1280 × 720
+
+## III. Visual Theme
+### Theme Style
+Long prose **with emphasis**.
+
+## IV. Typography System
+| Role | Font |
+| --- | --- |
+| Body | Arial |
+
+## V. Layout Principles
+Whitespace.
+
+## VI. Icon Usage Specification
+None.
+
+## VIII. Image Resource List
+None.
+
+## IX. Content Outline
+Introduction.
+### Part 1 - Opening
+
+#### Slide 01 - 开篇
+- **Audience move**: Understand.
+- **Relationships**: none
+- A complete paragraph that can be changed.
+ - A nested list.
+
+| Region | Value |
+| --- | --- |
+| North | 12 |
+
+### Part 2 - Closing
+
+#### Slide 02 - Close
+- **Audience move**: Decide.
+- **Relationships**: none
+- Closing paragraph.
+
+## X. Speaker Notes Requirements
+None.
+
+"""
+SCHEMA = SCHEMA_DIR / "design_spec.schema.json"
+
+
+class SpecBlocksTests(unittest.TestCase):
+ def test_lossless_round_trips(self):
+ fenced = SPEC.replace("| Region | Value |", "```md\n## x\n#### Slide 99 - fake\n```\n\n| Region | Value |")
+ tilde = SPEC.replace(
+ "| Region | Value |", "~~~~md\n## x\n#### Slide 99 - fake\n~~~\n~~~~\n\n| Region | Value |",
+ )
+ for text in (SPEC, SPEC.replace("\n", "\r\n"), SPEC.rstrip("\n"), fenced, tilde, "preamble only"):
+ with self.subTest(ending=repr(text[-8:]), fenced="fake" in text):
+ layout = split_spec_blocks(text)
+ joined = layout.preamble + "".join(text[block.start:block.end] for block in layout.blocks)
+ self.assertEqual(joined.encode("utf-8"), text.encode("utf-8"))
+ raw = text.encode("utf-8")
+ for block in layout.blocks:
+ self.assertEqual(raw[block.byte_start:block.byte_end], text[block.start:block.end].encode("utf-8"))
+ self.assertNotIn("slide:99", [block.key for block in layout.blocks])
+
+ def test_block_order_and_part_ownership(self):
+ layout = split_spec_blocks(SPEC)
+ self.assertEqual([block.key for block in layout.blocks][-6:],
+ ["section:IX", "part:01", "slide:01", "part:02", "slide:02", "section:X"])
+ parts = [block for block in layout.blocks if block.kind == "part"]
+ self.assertEqual([SPEC[block.start:block.end] for block in parts],
+ ["### Part 1 - Opening\n\n", "### Part 2 - Closing\n\n"])
+ slide = next(block for block in layout.blocks if block.key == "slide:01")
+ self.assertNotIn("### Part 2", SPEC[slide.start:slide.end])
+ self.assertEqual(slide.title, "#### Slide 01 - 开篇")
+
+ def test_slide_headings_at_every_supported_level(self):
+ for level in range(3, 7):
+ with self.subTest(level=level):
+ text = SPEC.replace("#### Slide 01", "#" * level + " Slide 01")
+ layout = split_spec_blocks(text)
+ slide = next(block for block in layout.blocks if block.key == "slide:01")
+ self.assertEqual(slide.kind, "slide")
+ self.assertEqual(len([block for block in layout.blocks if block.kind == "part"]), 2)
+ self.assertEqual(layout.preamble + "".join(text[b.start:b.end] for b in layout.blocks), text)
+ draft = text[slide.start:slide.end].replace("开篇", "New title")
+ self.assertEqual(replace_spec_block(text, slide.key, draft), text.replace("开篇", "New title"))
+
+ def test_non_slide_h3_is_part_regardless_of_title(self):
+ text = SPEC.replace("### Part 1 - Opening", "### Introduction")
+ block = next(block for block in split_spec_blocks(text).blocks if block.key == "part:01")
+ self.assertEqual(block.kind, "part")
+ self.assertEqual(text[block.start:block.end], "### Introduction\n\n")
+
+ def test_replacement_changes_only_target_bytes(self):
+ for text in (SPEC, SPEC.replace("\n", "\r\n"), SPEC.rstrip("\n")):
+ with self.subTest(crlf="\r" in text):
+ old = next(block for block in split_spec_blocks(text).blocks if block.key == "slide:01")
+ draft = text[old.start:old.end].replace("开篇", "新的页名").replace("can be changed", "was changed")
+ candidate = replace_spec_block(text, old.key, draft.replace("\r\n", "\n"))
+ new = next(block for block in split_spec_blocks(candidate).blocks if block.key == old.key)
+ self.assertEqual(text.encode()[:old.byte_start], candidate.encode()[:new.byte_start])
+ self.assertEqual(text.encode()[old.byte_end:], candidate.encode()[new.byte_end:])
+ if "\r" in text:
+ self.assertNotIn("\n", candidate.replace("\r\n", ""))
+
+ def test_noop_preserves_mixed_endings_and_terminal_whitespace(self):
+ text = SPEC.replace("Whitespace.\n", "Whitespace.\r\n")
+ block = next(block for block in split_spec_blocks(text).blocks if block.key == "section:V")
+ self.assertEqual(replace_spec_block(text, block.key, text[block.start:block.end].replace("\r\n", "\n")), text)
+ for tail in ("", "\n", "\n\n", "\r\n \r\n"):
+ text = SPEC.rstrip() + tail
+ block = split_spec_blocks(text).blocks[-1]
+ candidate = replace_spec_block(text, block.key, "## X. Speaker Notes Requirements\nChanged.\n\n\n")
+ self.assertEqual(candidate[block.start:], "## X. Speaker Notes Requirements\nChanged." + tail)
+
+ def test_structural_injection_and_heading_changes_rejected(self):
+ block = next(block for block in split_spec_blocks(SPEC).blocks if block.key == "slide:02")
+ original = SPEC[block.start:block.end]
+ changes = [original + heading for heading in (
+ "## Extra", "#### Slide 99 - Injected", "#### Slide 99 ", "### Part 3",
+ "### Slide 99", "##### Slide 99 - Injected", "###### Slide 99 - Injected",
+ )]
+ changes += [original.replace("Slide 02", "Slide 03"), original.replace("#### Slide", "### Slide"),
+ "prefix\n" + original, original + "```\n"]
+ for draft in changes:
+ with self.subTest(draft=draft[-40:]), self.assertRaises(ValueError):
+ replace_spec_block(SPEC, block.key, draft)
+
+ def test_part_allows_only_title_text_edits(self):
+ text = SPEC.replace("### Part 2 - Closing\n", "### Part 2 - Closing\nExisting part description.\n")
+ for text in (text, text.replace("\n", "\r\n")):
+ block = next(block for block in split_spec_blocks(text).blocks if block.key == "part:02")
+ original = text[block.start:block.end]
+ renamed = original.replace("Closing", "Final decisions").replace("\r\n", "\n")
+ expected = text.replace("### Part 2 - Closing", "### Part 2 - Final decisions")
+ self.assertEqual(replace_spec_block(text, block.key, renamed), expected)
+ changes = [original + heading for heading in (
+ "## Extra", "### Another part", "### Slide 99", "#### Slide 99", "New body text",
+ )]
+ changes += [
+ original.replace("### Part", "#### Part"), original.replace("### Part 2 - Closing", "### Slide 99"),
+ original.replace("Existing part description.", "Changed body."),
+ ]
+ for draft in changes:
+ with self.subTest(draft=draft), self.assertRaises(ValueError):
+ replace_spec_block(text, block.key, draft)
+ with self.assertRaisesRegex(ValueError, "section heading"):
+ replace_spec_block(SPEC, "section:V", "## V. Renamed\nBody\n")
+
+ def test_slide_injection_outside_ix_is_rejected(self):
+ block = next(block for block in split_spec_blocks(SPEC).blocks if block.key == "section:V")
+ for level in range(3, 7):
+ with self.subTest(level=level), self.assertRaisesRegex(ValueError, "Structural heading"):
+ replace_spec_block(SPEC, block.key, SPEC[block.start:block.end] + "#" * level + " Slide 99\n")
+
+ def test_headings_inside_both_fences_can_be_edited(self):
+ block = next(block for block in split_spec_blocks(SPEC).blocks if block.key == "slide:02")
+ for fence in ("```", "~~~"):
+ draft = SPEC[block.start:block.end] + (
+ f"{fence}\n## x\n### Slide 99\n#### Slide 99 - fake\n### Part\n{fence}\n"
+ )
+ candidate = replace_spec_block(SPEC, block.key, draft)
+ self.assertEqual(len(split_spec_blocks(candidate).blocks), len(split_spec_blocks(SPEC).blocks))
+
+
+class ReviewServiceTests(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ self.path = self.root / "design_spec.md"
+ self.path.write_bytes(SPEC.encode())
+ self.app = create_app(str(self.root), idle_timeout=0)
+ self.client = self.app.test_client()
+ self.store = self.app.extensions["review_store"]
+
+ def draft(self, key="slide:02", text=None):
+ block = self.client.get(f"/api/blocks/{key}").get_json()
+ response = self.client.put(f"/api/drafts/{key}", json={
+ "sha256": block["sha256"], "text": text or block["text"].replace("Closing paragraph", "Edited paragraph"),
+ })
+ self.assertEqual(response.status_code, 200, response.get_json())
+ return response.get_json()
+
+ def check(self, *args):
+ stdout, stderr = io.StringIO(), io.StringIO()
+ with redirect_stdout(stdout), redirect_stderr(stderr):
+ code = check_main([str(self.root), *args])
+ return code, stdout.getvalue(), stderr.getvalue()
+
+ def test_read_api_returns_raw_crlf_and_metadata(self):
+ raw = SPEC.replace("\n", "\r\n").encode()
+ self.path.write_bytes(raw)
+ self.assertEqual(self.client.get("/api/health").get_json()["service"], "spec_review")
+ document = self.client.get("/api/spec").get_json()
+ self.assertEqual(document["text"].encode(), raw)
+ self.assertEqual(document["sha256"], sha256(raw))
+ blocks = self.client.get("/api/blocks").get_json()
+ self.assertEqual(blocks["blocks"][-2]["key"], "slide:02")
+ self.assertFalse(any(block["has_draft"] for block in blocks["blocks"]))
+
+ def test_staging_and_discard_never_write_spec(self):
+ before = self.path.read_bytes()
+ draft = self.draft()
+ self.assertEqual(self.path.read_bytes(), before)
+ self.assertFalse((self.root / "spec_review" / "edits.jsonl").exists())
+ result = self.client.delete("/api/drafts/slide:02", json={"version": draft["version"]})
+ self.assertEqual(result.status_code, 200)
+ self.assertFalse(self.client.get("/api/blocks/slide:02").get_json()["draft"])
+ self.assertEqual(self.path.read_bytes(), before)
+
+ def test_apply_crlf_and_history(self):
+ self.path.write_bytes(SPEC.replace("\n", "\r\n").encode())
+ block = self.client.get("/api/blocks/slide:02").get_json()
+ draft = self.draft(text=block["text"].replace("Closing", "Edited").replace("\r\n", "\n"))
+ result = self.client.post("/api/apply/slide:02", json=draft)
+ self.assertEqual(result.status_code, 200, result.get_json())
+ self.assertEqual(result.get_json()["validation_errors"], [])
+ self.assertNotIn(b"\n", self.path.read_bytes().replace(b"\r\n", b""))
+ log = json.loads((self.root / "spec_review/edits.jsonl").read_text())
+ self.assertEqual(log["before_sha256"], draft["sha256"])
+ self.assertEqual(log["after_sha256"], sha256(self.path.read_bytes()))
+ self.assertIn("Edited", log["after"])
+
+ def test_apply_append_to_last_slide_of_part(self):
+ block = self.client.get("/api/blocks/slide:01").get_json()
+ self.assertNotIn("### Part 2", block["text"])
+ draft = self.draft("slide:01", block["text"].rstrip() + "\nAdded at page end.\n\n")
+ response = self.client.post("/api/apply/slide:01", json=draft)
+ self.assertEqual(response.status_code, 200, response.get_json())
+ self.assertEqual(self.path.read_bytes(),
+ SPEC.replace("| North | 12 |\n", "| North | 12 |\nAdded at page end.\n").encode())
+
+ def test_sha_mismatch_is_409_and_draft_survives(self):
+ draft = self.draft()
+ self.path.write_bytes(self.path.read_bytes() + b"External change\n")
+ before = self.path.read_bytes()
+ result = self.client.post("/api/apply/slide:02", json=draft)
+ self.assertEqual(result.status_code, 409)
+ self.assertEqual(self.path.read_bytes(), before)
+ self.assertEqual(self.client.get("/api/blocks/slide:02").get_json()["draft"], draft)
+
+ def test_external_block_removal_keeps_draft_accessible(self):
+ draft = self.draft()
+ block = next(block for block in split_spec_blocks(SPEC).blocks if block.key == "slide:02")
+ self.path.write_bytes((SPEC[:block.start] + SPEC[block.end:]).encode())
+ listing = self.client.get("/api/blocks").get_json()
+ self.assertEqual(listing["orphan_drafts"][0]["key"], "slide:02")
+ missing = self.client.get("/api/blocks/slide:02").get_json()
+ self.assertTrue(missing["missing"])
+ self.assertEqual(missing["draft"], draft)
+ self.assertEqual(self.client.post("/api/apply/slide:02", json=draft).status_code, 409)
+ discarded = self.client.delete("/api/drafts/slide:02", json={"version": draft["version"]})
+ self.assertEqual(discarded.status_code, 200)
+
+ def test_hold_is_423_and_resume_reports_revision(self):
+ draft = self.draft()
+ self.assertEqual(self.client.post("/api/hold", json={"hold": True}).status_code, 200)
+ self.assertEqual(self.client.post("/api/apply/slide:02", json=draft).status_code, 423)
+ released = self.client.post("/api/hold", json={"hold": False}).get_json()
+ self.assertEqual(released["hold_revision"], 2)
+ self.assertEqual(self.client.post("/api/apply/slide:02", json=draft).status_code, 200)
+
+ def test_apply_rejects_structure_without_mutation(self):
+ for heading in ("## Injected", "### Slide 99"):
+ with self.subTest(heading=heading):
+ draft = self.draft(text=f"#### Slide 02 - Close\n{heading}\nBody\n")
+ before = self.path.read_bytes()
+ result = self.client.post("/api/apply/slide:02", json=draft)
+ self.assertEqual(result.status_code, 400)
+ self.assertIn("Structural heading", result.get_json()["error"])
+ self.assertEqual(self.path.read_bytes(), before)
+ self.assertEqual(self.client.delete("/api/drafts/slide:02", json=draft).status_code, 200)
+
+ def test_schema_errors_are_advisory_and_returned_unchanged(self):
+ draft = self.draft(text="#### Slide 02 - Close\nMissing schema fields.\n")
+ result = self.client.post("/api/apply/slide:02", json=draft)
+ self.assertEqual(result.status_code, 200)
+ errors = result.get_json()["validation_errors"]
+ self.assertTrue(errors)
+ self.assertEqual(errors, validate_markdown_schema(self.path, SCHEMA))
+ self.assertIn(b"Missing schema fields.", self.path.read_bytes())
+ self.assertFalse((self.root / "spec_lock.md").exists())
+
+ def test_candidate_and_file_validation_match_without_reading_spec_lock(self):
+ variants = (SPEC, SPEC.replace("\n", "\r\n"), "\ufeff" + SPEC,
+ "\ufeff\ufeff" + SPEC, SPEC.replace("design-spec/v1", "bad"))
+ for text in variants:
+ self.path.write_bytes(text.encode())
+ disk = validate_markdown_schema(self.path, SCHEMA)
+ if text.startswith("\ufeff\ufeff"):
+ self.assertTrue(any("missing ppt-master-schema marker" in error for error in disk))
+ read_text = Path.read_text
+
+ def guarded(path, *args, **kwargs):
+ self.assertNotIn(path.name, ("spec_lock.md", "design_spec.md"))
+ return read_text(path, *args, **kwargs)
+
+ with patch.object(Path, "read_text", guarded):
+ self.assertEqual(validate_markdown_text(text, SCHEMA, markdown_path=self.path), disk)
+ missing = self.root / "missing.schema.json"
+ self.assertEqual(validate_markdown_text(text, missing, markdown_path=self.path),
+ validate_markdown_schema(self.path, missing))
+
+ def test_comment_crud_is_sidecar_only(self):
+ before = self.path.read_bytes()
+ saved = self.client.post("/api/annotations", json={"key": "global", "body": "Full deck feedback"})
+ self.assertEqual(saved.status_code, 201)
+ item = saved.get_json()
+ changed = self.client.put(
+ f"/api/annotations/{item['id']}", json={"revision": item["revision"], "body": "New text"},
+ )
+ updated = changed.get_json()
+ self.assertEqual(updated["spec_sha256"], sha256(before))
+ self.assertNotEqual(updated["revision"], item["revision"])
+ self.assertEqual(self.client.delete(f"/api/annotations/{item['id']}",
+ json={"revision": item["revision"]}).status_code, 409)
+ self.assertEqual(self.client.delete(f"/api/annotations/{item['id']}",
+ json={"revision": updated["revision"]}).status_code, 200)
+ self.assertEqual(self.path.read_bytes(), before)
+ events = [json.loads(line)["event"] for line in
+ (self.root / "spec_review/annotations.jsonl").read_text().splitlines()]
+ self.assertEqual(events, ["saved", "updated", "removed"])
+
+ def test_applied_unchanged_comment_is_removed_and_logged(self):
+ item = self.store.save_annotation("slide:01", "Change the opening")
+ self.assertEqual(self.check()[0], 0)
+ self.assertEqual(self.check("--applied", item["id"])[0], 0)
+ self.assertEqual(self.store.annotations(), [])
+ self.assertIn('"event":"annotation_applied"', (self.root / "spec_review/annotations.jsonl").read_text())
+
+ def test_applied_changed_comment_is_retained(self):
+ item = self.store.save_annotation("slide:01", "Original")
+ self.check()
+ self.store.save_annotation("", "Updated", item["id"], item["revision"])
+ code, output, errors = self.check("--applied", item["id"])
+ self.assertEqual(code, 1)
+ self.assertEqual(output, "")
+ self.assertIn("changed since it was listed", errors)
+ self.assertEqual(self.store.annotations()[0]["body"], "Updated")
+
+ def test_applied_unlisted_and_same_text_revisions_are_rejected(self):
+ item = self.store.save_annotation("global", "Same text")
+ self.assertEqual(self.check("--applied", item["id"])[0], 1)
+ self.check()
+ self.store.save_annotation("", item["body"], item["id"], item["revision"])
+ self.assertEqual(self.check("--applied", item["id"])[0], 1)
+
+ def test_applied_detects_manual_sidecar_change_without_revision_bump(self):
+ item = self.store.save_annotation("global", "Original")
+ self.check()
+ path = self.root / "spec_review/annotations.json"
+ data = json.loads(path.read_text())
+ data["items"][0]["body"] = "Manually changed"
+ path.write_text(json.dumps(data), encoding="utf-8")
+ self.assertEqual(self.check("--applied", item["id"])[0], 1)
+ self.assertEqual(self.store.annotations()[0]["body"], "Manually changed")
+
+ def test_todo_includes_hash_status_and_edit_summary_without_full_text(self):
+ self.store.save_annotation("slide:02", "Review it")
+ draft = self.draft()
+ self.client.post("/api/apply/slide:02", json=draft)
+ code, output, errors = self.check()
+ self.assertEqual((code, errors), (0, ""))
+ result = json.loads(output)
+ self.assertTrue(result["annotations"][0]["block_changed"])
+ self.assertFalse(result["annotations"][0]["block_missing"])
+ self.assertEqual(set(result["edits"][0]), {"ts", "key", "title", "before_sha256", "after_sha256"})
+ self.assertEqual(result["edits"][0]["before_sha256"], draft["sha256"][:12])
+ self.assertEqual(result["edits"][0]["after_sha256"], sha256(self.path.read_bytes())[:12])
+ self.assertNotIn("Edited paragraph", output)
+
+ def test_ack_edits_consumes_only_last_listing_and_preserves_history(self):
+ self.store.save_annotation("global", "Keep pending")
+ draft = self.draft()
+ self.assertEqual(self.client.post("/api/apply/slide:02", json=draft).status_code, 200)
+ for _ in range(2):
+ self.assertEqual(len(json.loads(self.check()[1])["edits"]), 1)
+ # A new Apply after the listing must survive acknowledgement of that listing.
+ draft = self.draft(text=self.store.block("slide:02")["text"].replace("Edited", "Edited again"))
+ self.assertEqual(self.client.post("/api/apply/slide:02", json=draft).status_code, 200)
+ log = self.root / "spec_review/edits.jsonl"
+ history = log.read_bytes()
+ self.assertEqual(self.check("--ack-edits")[0], 0)
+ result = json.loads(self.check()[1])
+ self.assertEqual(len(result["annotations"]), 1)
+ self.assertEqual(len(result["edits"]), 1)
+ self.assertEqual(result["edits"][0]["before_sha256"], draft["sha256"][:12])
+ self.assertEqual(self.check("--ack-edits")[0], 0)
+ self.assertEqual(json.loads(self.check()[1])["edits"], [])
+ self.assertEqual(log.read_bytes(), history)
+ self.assertEqual(ReviewStore(self.root).list_todo()["edits"], [])
+
+ def test_ack_edits_requires_cli_listing(self):
+ self.client.get("/api/annotations")
+ code, output, errors = self.check("--ack-edits")
+ self.assertEqual((code, output), (1, ""))
+ self.assertIn("List direct edits before acknowledging", errors)
+
+ def test_block_comment_baselines_ignore_edits_to_other_blocks(self):
+ self.path.write_bytes(SPEC.replace("\n", "\r\n").encode())
+ first = self.store.save_annotation("slide:01", "Opening feedback")
+ second = self.store.save_annotation("slide:02", "Closing feedback")
+ self.store.save_annotation("global", "Whole spec feedback")
+ self.assertEqual(first["block_sha256"], sha256(self.store.block("slide:01")["text"].encode()))
+ before = self.client.get("/api/annotations").get_json()["annotations"]
+ self.assertFalse(before[0]["block_changed"])
+ self.assertFalse(before[1]["block_changed"])
+ self.assertTrue(before[2]["base_current"])
+ draft = self.draft()
+ self.assertEqual(self.client.post("/api/apply/slide:02", json=draft).status_code, 200)
+ updated = self.store.save_annotation("", "Updated feedback", second["id"], second["revision"])
+ self.assertEqual(updated["block_sha256"], second["block_sha256"])
+ for items in (self.client.get("/api/annotations").get_json()["annotations"],
+ json.loads(self.check()[1])["annotations"]):
+ self.assertFalse(items[0]["block_changed"])
+ self.assertTrue(items[1]["block_changed"])
+ self.assertFalse(items[0]["block_missing"])
+ self.assertNotIn("base_current", items[0])
+ self.assertFalse(items[2]["base_current"])
+ self.assertNotIn("block_changed", items[2])
+
+ def test_block_comment_unknown_and_missing_baselines(self):
+ self.store.save_annotation("slide:01", "Legacy feedback")
+ self.store.save_annotation("slide:02", "Missing block feedback")
+ sidecar = self.root / "spec_review/annotations.json"
+ data = json.loads(sidecar.read_text())
+ del data["items"][0]["block_sha256"]
+ sidecar.write_text(json.dumps(data), encoding="utf-8")
+ block = next(block for block in split_spec_blocks(SPEC).blocks if block.key == "slide:02")
+ self.path.write_bytes((SPEC[:block.start] + SPEC[block.end:]).encode())
+ for items in (self.client.get("/api/annotations").get_json()["annotations"],
+ json.loads(self.check()[1])["annotations"]):
+ self.assertIsNone(items[0]["block_changed"])
+ self.assertFalse(items[0]["block_missing"])
+ self.assertIsNone(items[1]["block_changed"])
+ self.assertTrue(items[1]["block_missing"])
+
+ def test_polling_and_health_do_not_refresh_activity(self):
+ self.app.config["LAST_ACTIVITY"] = 10.0
+ with patch("spec_review.server.time.monotonic", return_value=8000.0):
+ for path in ("/api/state", "/api/state?poll=1", "/api/health"):
+ for _ in range(2):
+ self.assertEqual(self.client.get(path).status_code, 200)
+ self.assertEqual(self.app.config["LAST_ACTIVITY"], 10.0)
+ self.assertEqual(self.client.get("/api/blocks").status_code, 200)
+ self.assertEqual(self.app.config["LAST_ACTIVITY"], 8000.0)
+ with patch("spec_review.server.time.monotonic", return_value=9000.0):
+ response = self.client.post("/api/annotations", json={"key": "global", "body": "Active"})
+ self.assertEqual(response.status_code, 201)
+ self.assertEqual(self.app.config["LAST_ACTIVITY"], 9000.0)
+
+ def test_shutdown_stops_service_without_applying_pending_draft(self):
+ self.draft()
+ before = self.path.read_bytes()
+ response = self.client.post("/api/shutdown", json={})
+ self.assertEqual(response.status_code, 200)
+ self.assertTrue(self.app.extensions["stop_event"].is_set())
+ self.assertTrue(self.store.hold)
+ self.assertEqual(self.path.read_bytes(), before)
+
+ def test_two_applies_have_one_winner(self):
+ draft = self.draft()
+
+ def apply():
+ try:
+ self.store.apply("slide:02", draft["sha256"], draft["version"])
+ return 200
+ except ReviewError as exc:
+ return exc.status
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ results = list(pool.map(lambda _: apply(), range(2)))
+ self.assertEqual(sorted(results), [200, 409])
+ self.assertEqual(len((self.root / "spec_review/edits.jsonl").read_text().splitlines()), 1)
+
+ def test_other_block_draft_rebases_only_after_own_edit(self):
+ first = self.draft("slide:01")
+ second = self.draft("slide:02")
+ result = self.client.post("/api/apply/slide:02", json=second).get_json()
+ remaining = self.store.block("slide:01")["draft"]
+ self.assertEqual(remaining["sha256"], result["sha256"])
+ self.assertEqual(remaining["version"], first["version"])
+ self.path.write_bytes(self.path.read_bytes() + b"external\n")
+ self.assertNotEqual(self.store.block("slide:01")["sha256"], remaining["sha256"])
+
+ def test_atomic_replace_failure_preserves_file_and_draft(self):
+ draft = self.draft()
+ before = self.path.read_bytes()
+ with patch("spec_review.store.os.replace", side_effect=OSError("Replace failed")):
+ response = self.client.post("/api/apply/slide:02", json=draft)
+ self.assertEqual(response.status_code, 500)
+ self.assertEqual(self.path.read_bytes(), before)
+ self.assertIsNotNone(self.store.block("slide:02")["draft"])
+ self.assertEqual(list(self.root.glob(".design_spec.md.*")), [])
+
+ def test_draft_versions_prevent_cross_tab_overwrite(self):
+ draft = self.draft()
+ response = self.client.put("/api/drafts/slide:02", json={"text": "lost", "sha256": draft["sha256"]})
+ self.assertEqual(response.status_code, 409)
+ self.assertEqual(self.store.block("slide:02")["draft"], draft)
+
+ def test_host_origin_and_json_guards(self):
+ for headers in ({"Host": "attacker.example"}, {"Origin": "null"}, {"Origin": "http://attacker.example"},
+ {"Origin": "http://localhost:7777"}):
+ self.assertEqual(self.client.get("/api/state", headers=headers).status_code, 403)
+ self.assertEqual(self.client.get("/api/state", headers={"Origin": "http://localhost"}).status_code, 200)
+ self.assertEqual(self.client.post("/api/annotations", json=[]).status_code, 400)
+ self.assertEqual(self.client.post("/api/hold", json={"hold": "on"}).status_code, 400)
+ response = self.client.get("/")
+ self.assertEqual(response.status_code, 200)
+ self.assertIn("default-src 'none'", response.headers["Content-Security-Policy"])
+ response.close()
+
+ def test_cli_help_and_invalid_port_have_no_runtime_side_effect(self):
+ with redirect_stdout(io.StringIO()), self.assertRaises(SystemExit) as result:
+ server_main(["--help"])
+ self.assertEqual(result.exception.code, 0)
+ self.assertEqual(server_main([str(self.root), "--port", "0"]), 1)
+ self.assertFalse((self.root / "spec_review").exists())
+
+ def test_explicit_port_is_strict_and_foreground_releases_lock(self):
+ httpd = Mock()
+ with patch("spec_review.server._running", return_value=None), patch(
+ "spec_review.server.make_server", return_value=httpd,
+ ) as bind, patch("spec_review.server.find_free_port") as scan, patch(
+ "spec_review.server.threading.Thread.start",
+ ), patch("spec_review.server.signal.signal"), redirect_stdout(io.StringIO()):
+ self.assertEqual(server_main([str(self.root), "--port", "6077", "--no-browser"]), 0)
+ scan.assert_not_called()
+ self.assertEqual(bind.call_args.args[:2], ("127.0.0.1", 6077))
+ httpd.server_close.assert_called_once()
+ self.assertFalse((self.root / "spec_review/lock.json").exists())
+
+ def test_explicit_port_bind_failure_does_not_fall_back(self):
+ with patch("spec_review.server._running", return_value=None), patch(
+ "spec_review.server.make_server", side_effect=OSError("Address already in use"),
+ ), patch("spec_review.server.find_free_port") as scan:
+ self.assertEqual(server_main([str(self.root), "--port", "6077", "--no-browser"]), 1)
+ scan.assert_not_called()
+ self.assertFalse((self.root / "spec_review/lock.json").exists())
+
+ def test_hold_cli_and_running_port_mismatch(self):
+ with patch("spec_review.server._running", return_value={"pid": 1234, "port": 6077}), patch(
+ "spec_review.server._call", return_value={"hold": True},
+ ) as call, redirect_stdout(io.StringIO()):
+ self.assertEqual(server_main([str(self.root), "--hold", "on"]), 0)
+ call.assert_called_once_with(6077, "/api/hold", {"hold": True})
+ self.assertEqual(server_main([str(self.root), "--port", "6088", "--no-browser"]), 1)