diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..4481756 --- /dev/null +++ b/build.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Builds patched JOE. Does not touch anything outside this repo -- run +# install.sh afterward to actually put the binary somewhere on PATH. +# +# Usage: ./build.sh [--clean] +# --clean Remove any existing checkout under joe-patch/build/ first +# (use if a previous build is in a bad state). +# +# Env overrides: +# JOE_SRC_DIR Use an existing joe source tree instead of cloning one. +# Must be named .../joe-4.8 (the patch is rooted on that +# directory name) and be a clean, unpatched checkout. +# PREFIX configure --prefix (default: $HOME/.local) +set -euo pipefail + +SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" +PATCH_FILE="$SCRIPT_DIR/joe-patch/joe-4.8-hedgedoc-0.7.13.patch" +BUILD_ROOT="$SCRIPT_DIR/joe-patch/build" +JOE_SRC_DIR="${JOE_SRC_DIR:-$BUILD_ROOT/joe-4.8}" +PREFIX="${PREFIX:-$HOME/.local}" + +if [ "${1:-}" = "--clean" ]; then + echo "==> --clean: removing $BUILD_ROOT" + rm -rf "$BUILD_ROOT" +fi + +echo "==> Checking build tools" +missing="" +for cmd in git patch autoreconf automake make gcc; do + command -v "$cmd" >/dev/null 2>&1 || missing="$missing $cmd" +done +if [ -n "$missing" ]; then + echo "Missing:$missing" >&2 + echo "On Debian/Ubuntu: sudo apt install build-essential autoconf automake git" >&2 + exit 1 +fi +if [ ! -f /usr/include/ncurses.h ] && [ ! -f /usr/include/ncursesw/ncurses.h ]; then + echo "Warning: ncurses headers not found in the usual places -- the build" >&2 + echo "may fail linking -lncurses. On Debian/Ubuntu: sudo apt install libncurses-dev" >&2 +fi + +if [ ! -d "$JOE_SRC_DIR" ]; then + echo "==> Cloning joe 4.8 source into $JOE_SRC_DIR" + mkdir -p "$BUILD_ROOT" + git clone --quiet https://github.com/joe-editor/joe.git "$JOE_SRC_DIR" + git -C "$JOE_SRC_DIR" checkout --quiet releases/joe-4.8 +else + echo "==> Using existing source at $JOE_SRC_DIR" +fi + +if [ -f "$JOE_SRC_DIR/joe/hd_ipc.c" ]; then + echo "==> Patch already applied (hd_ipc.c exists) -- skipping" +else + echo "==> Applying $(basename "$PATCH_FILE")" + ( cd "$(dirname "$JOE_SRC_DIR")" && patch -p1 < "$PATCH_FILE" ) +fi + +echo "==> autoreconf (required: the patch touches Makefile.am, not Makefile.in)" +( cd "$JOE_SRC_DIR" && autoreconf -fi ) + +echo "==> configure --prefix=$PREFIX" +( cd "$JOE_SRC_DIR" && ./configure --prefix="$PREFIX" ) + +echo "==> make" +JOBS="$(command -v nproc >/dev/null 2>&1 && nproc || echo 1)" +( cd "$JOE_SRC_DIR" && make -j"$JOBS" ) + +BUILT="$JOE_SRC_DIR/joe/joe" +if [ ! -x "$BUILT" ]; then + echo "Build finished but $BUILT isn't executable -- something's wrong." >&2 + exit 1 +fi +if [ ! -f "$JOE_SRC_DIR/joe/hd_ipc.o" ]; then + echo "Warning: $BUILT was built WITHOUT hd_ipc.o -- it's plain upstream" >&2 + echo "joe, not the patched version. Check the autoreconf step ran." >&2 + exit 1 +fi + +echo +echo "Built: $BUILT" +echo "Next: ./install.sh" diff --git a/hd-cli/README.md b/hd-cli/README.md new file mode 100644 index 0000000..85011f5 --- /dev/null +++ b/hd-cli/README.md @@ -0,0 +1,149 @@ +# hdc -- HedgeDoc as a tag-organized local folder + +Run `../install.sh` from the repo root first (builds patched JOE, sets up a +venv, links `hdc` and `hd-joe` onto your PATH). This README covers `hdc` +specifically once that's done; see the top-level README for the whole repo. + +## Setup + + hdc init https://your-hedgedoc.example --dir ~/notes + +Interactive dialog: email, then password (not echoed), logs in against +`/login`, keeps only the resulting session cookie. SSO/LDAP servers: use +`--cookie 'connect.sid=...'` instead (copied from your browser). + + hdc sync # one-shot pull + reconcile + hdc sync --watch # poll every 30s (--interval to change) + hdc tag # add a tag -- writes to HedgeDoc + hdc untag # remove a tag -- writes to HedgeDoc + +`--dir` is optional on `sync`/`tag`/`untag`: standing anywhere inside an +hd-managed folder (not just at its root) is enough -- `hdc` walks up +looking for `.hd/`, the same discovery `hd-joe` already does, falling +back to `~/notes` if that finds nothing. Pass `--dir` explicitly to +override this (e.g. managing more than one hd-managed folder). + +`` in `tag`/`untag` accepts a note id, or a path to one of its +existing symlinks -- resolved from wherever you're actually standing, the +same way a shell resolves any other path: a bare `FOI` means the symlink +named `FOI` right here, `../work/FOI` means the one in `../work`. This +takes priority over title matching, so a same-named note elsewhere never +gets picked by accident. Only if no symlink matches at all does it fall +back to searching by title (must be unique) across every note. + +## Layout under --dir (default: auto-detected, see above; ~/notes if nothing is found) + + .hd/config.json server URL (+ email if you logged in). No secrets. + .hd/cookies.json session cookie, mode 0600. + .hd/state.json what the reconciler believes is true right now. + .hd/problems.json things sync noticed but can't safely fix itself. + .hd/.lock real interprocess lock (fcntl.flock) shared by + every command that touches state/symlinks. + .hd/notes/.md cached content -- read-only, do not edit directly. + / symlink into .hd/notes/<id>.md, one per tag. + No .md on the symlink itself -- it's named + after the note's title, not a file. + untagged/<title> symlink for notes with no tags. + +## What `sync` does + +`GET /history` (cookie-authenticated) is the only source of truth for which +notes exist and what tags they have -- confirmed against HedgeDoc 1.12.0's +own `lib/history.js`, not guessed. Content is only re-fetched via +`/<id>/download` when `/history`'s `time` field has actually moved since +last sync (skips the network round trip entirely otherwise). Every sync +pass also runs a cheap structural check over the tag directories and writes +whatever it finds to `.hd/problems.json`: + +- a real directory where a tag symlink was expected (nested tag folders + aren't supported -- one tag is always exactly one directory level) +- a plain file where a symlink was expected (the classic `cp` without `-P` + mistake) -- its checksum is looked up against the cache; a match names + the note and the exact fix command, no match says so plainly +- a broken symlink (target no longer exists) +- a symlink pointing outside `.hd/notes/` entirely (created by hand) + +## What `tag`/`untag` do + +There is no plain HTTP save endpoint for an existing note's content +(checked against the router source) -- the only way to change a note at +all is the realtime Socket.IO channel, same as any live edit. `hdc tag`/`hdc +untag` open a short-lived connection, fetch the document **fresh** (never +from the local cache, which can be hours old), parse the YAML frontmatter +exactly the way HedgeDoc itself does (`lib/models/note.js`'s +`splitFrontmatter`: must start with literal `---`, closed by the first +`\n---` or `\n...`), edit only the `tags:` line, and send the minimal patch +-- title and everything else in the frontmatter, and the entire body, are +left untouched. Tags are always written as a comma-separated string, never +a YAML list -- a list is silently ignored by the real server's own tag +parser. Untagging down to zero removes the `tags` key entirely rather than +leaving it empty. A note with no frontmatter at all gets a fresh block +inserted at the very top. + +If the existing frontmatter doesn't parse as valid YAML, or parses to +something that isn't a mapping, `hdc tag`/`hdc untag` refuse to touch it +rather than risk destroying whatever's actually there. + +After a successful write, the command immediately runs a normal sync pass +so the local symlinks catch up right away instead of waiting for the next +scheduled sync. + +## Known gaps + +- **No filesystem watcher.** Moving a symlink between tag folders yourself + doesn't do anything -- only the explicit `hdc tag`/`hdc untag` commands, + and hd-joe's note creation, write to the server. `ReconcileLock` (a real + `fcntl.flock` on `.hd/.lock`) is already shared by all three, so a future + watcher has something correct to coordinate with -- the watcher itself + isn't built. +- **`/history` is the most fragile dependency in this whole system** -- it's + HedgeDoc's internal "recently visited" feature, not an API designed for + this purpose. It only lists notes the account has opened at least once, + and a note's tags there only refresh while someone is actively viewing + or editing it server-side. +- **No protection against two truly simultaneous tag edits** to the same + note landing at the same moment -- the OT layer resolves the byte + positions correctly either way, but a genuine semantic race (both edits + reading the same "current tags" before either's write lands) isn't + specially detected. Rare in practice for a single-user tool; worth + revisiting if `hdc tag` ever gets called from automation. + +## Tests + + cd hd-cli + python3 test_hd_core.py # reconciliation: create/retag/rename/ + # collision/deletion/idempotency (34) + python3 test_hd_cli.py # hdc init/sync via subprocess, login flow, + # file permissions, --dir auto-detection (30) + python3 test_hd_tags.py # frontmatter parsing/patching, note + # reference resolution incl. cwd-relative + # path priority over title matching (31) + python3 test_hd_problems.py # stray/nested/broken/foreign detection, + # real flock mutual exclusion (16) + python3 test_hd_write.py # write_tags against a fake realtime + # server: minimal edits, no-op skip (13) + python3 test_hd_tag_cli.py # hdc tag/untag via subprocess against a + # combined history+download+realtime + # fake server (13) + python3 test_hd_tag_stale_history.py # tag/untag against a fake server + # that deliberately delays /history's + # view of a write, like real HedgeDoc's + # own DB-flush lag (9) + +148 checks total. Three real bugs were found and fixed by these tests +during development, not just by reading the code: `write_tags` originally +had a "retry if revision moved" check that couldn't tell its own +successful write's natural revision bump apart from a genuine concurrent +edit, `hdc tag`/`hdc untag`'s immediate re-sync could be fooled by +`/history`'s own delayed view of the write it had just made (found only +once a fake server was built that actually reproduces that delay, instead +of the instant consistency every other fake server here gives for free -- +see CHANGES-0.7.28.md), and +replayed the tag mutation a second time on top of itself -- caught by +`test_hd_write.py` producing `['urgent', 'urgent']` instead of `['urgent']`. +Separately, `test_hd_tag_cli.py`'s own fake server hung on every `hdc tag` +call at first, from constructing a fresh `socketio.WSGIApp` per HTTP +request and from parsing `QUERY_STRING` through `urlparse()` a second time +(which returns nothing, since `QUERY_STRING` isn't a full URL) -- both bugs +were in the test's own scaffolding, not in `hdc`, but neither test would +have caught anything real until both were fixed. diff --git a/hd-cli/hdc b/hd-cli/hdc new file mode 100755 index 0000000..4bd1136 --- /dev/null +++ b/hd-cli/hdc @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +"""hdc -- local filesystem mirror of a HedgeDoc account, organized by tag. + +(Named hdc, not hd: hd already means hexdump on Debian/Ubuntu -- +bsdextrautils ships it as a standard alias, and it beat us to the name.) + + hdc init [<hedgedoc-url>] [--email E] [--cookie '...'] [--dir ~/notes] + hdc sync [--dir ~/notes] [-v] [--watch [--interval SECONDS]] + hdc tag <note> <tag> [--dir ~/notes] + hdc untag <note> <tag> [--dir ~/notes] + +Layout created under --dir (default: ~/notes): + .hd/config.json server url (+ email, if you logged in), mode 0600 + .hd/cookies.json session cookie, mode 0600 -- kept separate from + config.json since this is the actual credential + .hd/state.json what the reconciler believes is true + .hd/problems.json things sync noticed but can't safely fix itself + .hd/notes/<id>.md cached note content (read-only cache -- do not edit) + <tag>/<title>.md symlink into .hd/notes/<id>.md, one per tag + untagged/<title>.md symlink for notes with no tags + +`sync` only ever pulls from HedgeDoc. `tag`/`untag` are the only commands +that write back -- they edit the note's own YAML frontmatter over the +realtime channel (there's no plain HTTP save endpoint for existing notes) +and then re-run a sync pass so the local symlinks catch up immediately. +""" +from __future__ import annotations + +import argparse +import getpass +import logging +import sys +import time +from pathlib import Path +from typing import Optional + +# hd_core.py/hd_client.py live in ../hd_common, shared verbatim with hd-joe +# (see hd_common/README.md) -- add it to sys.path before importing either, +# regardless of where this script is actually invoked from. +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common")) + +from hd_core import ( + Config, Cookies, HedgeDocSource, LoginError, State, + find_hd_root, login, reconcile, resolve_note_ref, update_note_tags_locally, write_tags, +) + +logger = logging.getLogger("hdc") + + +def cmd_init(args: argparse.Namespace) -> int: + root = Path(args.dir).expanduser() + hd_dir = root / ".hd" + if hd_dir.exists(): + print(f"{hd_dir} already exists -- refusing to overwrite. " + f"Delete it yourself first if you really want to re-init.", file=sys.stderr) + return 1 + + url = args.url or input("HedgeDoc server URL: ").strip() + if not url: + print("A server URL is required.", file=sys.stderr) + return 1 + + email: str | None = None + if args.cookie: + cookie_header = args.cookie + else: + # Interactive login dialog: server (above), then email + password. + email = args.email or input("Email: ").strip() + if not email: + print("An email address is required for login " + "(or pass --cookie if this server uses SSO/LDAP instead).", file=sys.stderr) + return 1 + password = getpass.getpass("Password: ") + try: + cookie_header = login(url, email, password) + except LoginError as exc: + print(f"Login failed: {exc}", file=sys.stderr) + return 1 + + root.mkdir(parents=True, exist_ok=True) + hd_dir.mkdir(parents=True, exist_ok=True) + (hd_dir / "notes").mkdir(parents=True, exist_ok=True) + + config = Config(url=url.rstrip("/"), email=email) + config.save(hd_dir) + Cookies(header=cookie_header).save(hd_dir) + + print(f"Initialized {root}. Running first sync...") + return _do_sync(root) + + +def _resolve_root(dir_arg: Optional[str]) -> Path: + """--dir was given explicitly: use it, unchanged from before. Otherwise + walk up from the current directory looking for .hd/ -- same discovery + hd-joe already does -- so standing anywhere inside an hd-managed + folder (not just its root) just works, without needing --dir spelled + out every time. Falls back to the old hardcoded ~/notes only if that + search finds nothing, so running these commands from somewhere + unrelated still behaves the way it always has.""" + if dir_arg is not None: + return Path(dir_arg).expanduser() + found = find_hd_root(Path.cwd()) + if found is not None: + return found + return Path("~/notes").expanduser() + + +def _do_sync(root: Path) -> int: + hd_dir = root / ".hd" + if not hd_dir.exists(): + print(f"{hd_dir} does not exist -- run 'hdc init' first.", file=sys.stderr) + return 1 + config = Config.load(hd_dir) + cookies = Cookies.load(hd_dir) + state = State.load(hd_dir) + source = HedgeDocSource(config.url, cookies.header) + try: + result = reconcile(root, source, state) + except RuntimeError as exc: + print(str(exc), file=sys.stderr) + return 1 + state.save(hd_dir) + + if result.notes_updated: + print(f"Updated: {len(result.notes_updated)} note(s)") + if result.notes_removed: + print(f"Removed: {len(result.notes_removed)} note(s) no longer in your history") + if result.symlinks_created: + logger.info("Created %d symlink(s)", len(result.symlinks_created)) + if result.symlinks_removed: + logger.info("Removed %d symlink(s)", len(result.symlinks_removed)) + if not (result.notes_updated or result.notes_removed): + print("Up to date.") + if result.problems: + print(f"\n{len(result.problems)} problem(s) found:") + for p in result.problems: + print(f" - {p}") + return 0 + + +def cmd_sync(args: argparse.Namespace) -> int: + root = _resolve_root(args.dir) + if not args.watch: + return _do_sync(root) + print(f"Watching (polling every {args.interval}s). Ctrl-C to stop.") + try: + while True: + rc = _do_sync(root) + if rc != 0: + return rc + time.sleep(args.interval) + except KeyboardInterrupt: + return 0 + + +def _cmd_retag(args: argparse.Namespace, mutate) -> int: + root = _resolve_root(args.dir) + hd_dir = root / ".hd" + if not hd_dir.exists(): + print(f"{hd_dir} does not exist -- run 'hdc init' first.", file=sys.stderr) + return 1 + config = Config.load(hd_dir) + cookies = Cookies.load(hd_dir) + state = State.load(hd_dir) # read-only here; write_tags never touches local state + + try: + # cwd, not root: 'FOI' means the symlink named FOI in the + # directory the user is actually standing in, '../work/FOI' the + # one in ../work -- see resolve_note_ref's docstring. + note_id = resolve_note_ref(root, state, args.note, cwd=Path.cwd()) + except ValueError as exc: + print(str(exc), file=sys.stderr) + return 1 + + try: + new_tags = write_tags(config.url, cookies.header, note_id, mutate) + except Exception as exc: + print(f"Could not update tags for {note_id}: {exc}", file=sys.stderr) + return 1 + + print(f"{note_id}: tags now [{', '.join(new_tags) if new_tags else '(none)'}]") + # Apply the symlink change directly from the write's own confirmed + # result, before the /history-driven sync below -- /history can lag a + # just-completed write by a few seconds (HedgeDoc's DB-flush delay), + # which left a stale symlink in place after a real 'hdc untag'. This + # makes the CLI's own view correct immediately regardless of that; + # _do_sync() below still runs as the general catch-all for anything + # else that may have changed elsewhere since the last sync. + try: + update_note_tags_locally(root, note_id, new_tags) + except Exception as exc: + logger.warning("Could not apply the local symlink update directly (%s); " + "the sync below is still the safety net.", exc) + print("Syncing local symlinks...") + return _do_sync(root) # reconcile() takes its own lock; nothing held across this call + + +def cmd_tag(args: argparse.Namespace) -> int: + tag = args.tag + return _cmd_retag(args, lambda tags: tags if tag in tags else [*tags, tag]) + + +def cmd_untag(args: argparse.Namespace) -> int: + tag = args.tag + return _cmd_retag(args, lambda tags: [t for t in tags if t != tag]) + + +def main() -> int: + ap = argparse.ArgumentParser(prog="hdc", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("-v", "--verbose", action="store_true") + sub = ap.add_subparsers(dest="command", required=True) + + p_init = sub.add_parser("init", help="Set up a new hd-managed folder") + p_init.add_argument("url", nargs="?", help="HedgeDoc server URL (prompted for if omitted)") + p_init.add_argument("--email", help="Email to log in with (prompted for if omitted and no --cookie)") + p_init.add_argument("--cookie", help="Skip the login dialog: use this Cookie header directly " + "(needed for SSO/LDAP servers with no local password login)") + p_init.add_argument("--dir", default="~/notes", help="Target folder (default: ~/notes)") + p_init.set_defaults(func=cmd_init) + + dir_help = ("Target folder. Default: auto-detected by walking up from the " + "current directory looking for .hd/ (same as hd-joe), falling " + "back to ~/notes if that finds nothing.") + + p_sync = sub.add_parser("sync", help="Pull notes and reconcile tag symlinks") + p_sync.add_argument("--dir", default=None, help=dir_help) + p_sync.add_argument("--watch", action="store_true", help="Keep syncing in a loop instead of once") + p_sync.add_argument("--interval", type=float, default=30.0, help="Seconds between syncs with --watch") + p_sync.set_defaults(func=cmd_sync) + + p_tag = sub.add_parser("tag", help="Add a tag to a note (writes to HedgeDoc)") + p_tag.add_argument("note", help="Note id, or a path to one of its symlinks -- resolved from where " + "you're standing, like any other path (bare 'Title' means the symlink " + "named Title right here; '../work/Title' means the one in ../work) -- " + "or, only if no symlink matches, its (unique) title anywhere") + p_tag.add_argument("tag", help="Tag to add") + p_tag.add_argument("--dir", default=None, help=dir_help) + p_tag.set_defaults(func=cmd_tag) + + p_untag = sub.add_parser("untag", help="Remove a tag from a note (writes to HedgeDoc)") + p_untag.add_argument("note", help="Note id, or a path to one of its symlinks -- resolved from where " + "you're standing, like any other path (bare 'Title' means the symlink " + "named Title right here; '../work/Title' means the one in ../work) -- " + "or, only if no symlink matches, its (unique) title anywhere") + p_untag.add_argument("tag", help="Tag to remove") + p_untag.add_argument("--dir", default=None, help=dir_help) + p_untag.set_defaults(func=cmd_untag) + + args = ap.parse_args() + logging.basicConfig(level=logging.DEBUG if args.verbose else logging.WARNING, + format="%(levelname)s %(message)s") + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-cli/requirements.txt b/hd-cli/requirements.txt new file mode 100644 index 0000000..48bff9d --- /dev/null +++ b/hd-cli/requirements.txt @@ -0,0 +1,2 @@ +-r ../hd_common/requirements.txt +werkzeug>=3.0 # tests only, not needed to run hd itself diff --git a/hd-cli/test_hd_cli.py b/hd-cli/test_hd_cli.py new file mode 100644 index 0000000..4b7e4c0 --- /dev/null +++ b/hd-cli/test_hd_cli.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python3 +import json +import os +import shutil +import stat +import subprocess +import sys +import tempfile +import threading +from pathlib import Path + +sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common")) +from werkzeug.serving import make_server +from werkzeug.wrappers import Request, Response + +PASS = [] +FAIL = [] + + +def check(name, cond, detail=""): + if cond: + PASS.append(name) + else: + FAIL.append((name, detail)) + print(f"FAIL: {name} {detail}") + + +class FakeServer: + """Serves /history, /<id>/download, and a fake /login that accepts + exactly one email+password pair and sets a session cookie -- mirrors + real HedgeDoc's local-auth /login: always 302s, whether accepted or + rejected, and the caller must probe /history to find out which.""" + + VALID_EMAIL = "joakim@example.com" + VALID_PASSWORD = "correct horse battery staple" + + def __init__(self, port, notes): + self.notes = notes + self.port = port + self.valid_sessions = {"session=abc123"} + + def app(environ, start_response): + request = Request(environ) + if request.path == "/login" and request.method == "POST": + from urllib.parse import parse_qs + body = request.get_data(as_text=True) + fields = parse_qs(body) + email = (fields.get("email") or [""])[0] + password = (fields.get("password") or [""])[0] + resp = Response(status=302, headers={"Location": "/"}) + if email == self.VALID_EMAIL and password == self.VALID_PASSWORD: + resp.set_cookie("connect.sid", "loggedinsession") + self.valid_sessions.add("connect.sid=loggedinsession") + return resp(environ, start_response) + if request.path == "/history": + cookie = request.headers.get("Cookie", "") + if not any(v in cookie for v in self.valid_sessions): + resp = Response("forbidden", status=403) + else: + history = [{"id": nid, "text": n["title"], "tags": n["tags"], "time": 0} + for nid, n in self.notes.items()] + resp = Response(json.dumps({"history": history}), mimetype="application/json") + elif request.path.endswith("/download"): + nid = request.path.split("/")[1] + resp = Response(self.notes[nid]["content"], mimetype="text/markdown") + else: + resp = Response("not found", status=404) + return resp(environ, start_response) + + self.srv = make_server("127.0.0.1", port, app, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + + def stop(self): + self.srv.shutdown() + + +def free_port(): + import socket + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + p = s.getsockname()[1] + s.close() + return p + + +def run_hd(*args, cwd, input_text=None): + return subprocess.run( + [sys.executable, str(Path(__file__).parent / "hdc"), *args], + cwd=cwd, capture_output=True, text=True, timeout=15, input=input_text, + ) + + +def main(): + port = free_port() + notes = { + "n1": {"title": "Fox Hunt Notes", "tags": ["radio"], "content": "# Fox Hunt\nfrequencies here"}, + } + server = FakeServer(port, notes) + server.start() + + tmpdir = Path(tempfile.mkdtemp(prefix="hd-cli-test-")) + target = tmpdir / "notes" + + try: + # --- init with --cookie, wrong value: files saved, but sync fails --- + r = run_hd("init", f"http://127.0.0.1:{port}", "--cookie", "session=wrong", + "--dir", str(target), cwd=tmpdir) + check("init with bad cookie exits nonzero (sync fails)", r.returncode != 0, r.stderr) + check("init with bad cookie still saved cookies.json", + (target / ".hd" / "cookies.json").exists()) + + shutil.rmtree(target) + + # --- init with --cookie, correct value --- + r = run_hd("init", f"http://127.0.0.1:{port}", "--cookie", "session=abc123", + "--dir", str(target), cwd=tmpdir) + check("init with good cookie exits 0", r.returncode == 0, r.stderr) + check("config.json created", (target / ".hd" / "config.json").exists()) + check("cookies.json created", (target / ".hd" / "cookies.json").exists()) + for fname in ("config.json", "cookies.json"): + mode = stat.S_IMODE((target / ".hd" / fname).stat().st_mode) + check(f"{fname} is mode 0600", mode == 0o600, oct(mode)) + check("cookie not leaked into config.json", + "cookie" not in json.loads((target / ".hd" / "config.json").read_text())) + check("cookie present in cookies.json", + json.loads((target / ".hd" / "cookies.json").read_text())["cookie"] == "session=abc123") + check("state.json created", (target / ".hd" / "state.json").exists()) + check("radio/ created with symlink", (target / "radio" / "Fox Hunt Notes").is_symlink()) + check("symlinked content matches", (target / "radio" / "Fox Hunt Notes").read_text() + == "# Fox Hunt\nfrequencies here") + + # --- --dir auto-detection: standing anywhere inside the hd-managed + # tree, 'hdc sync' with no --dir at all should still find it --- + r_auto1 = run_hd("sync", cwd=target) # at the root itself + check("sync with no --dir, standing AT the hd root, auto-detects it", + r_auto1.returncode == 0, r_auto1.stdout + r_auto1.stderr) + + r_auto2 = run_hd("sync", cwd=target / "radio") # a subdirectory + check("sync with no --dir, standing in a SUBDIRECTORY, still auto-detects the root above it", + r_auto2.returncode == 0, r_auto2.stdout + r_auto2.stderr) + + # From somewhere with no .hd/ above it at all, and a controlled, + # guaranteed-empty $HOME so the ~/notes fallback can't accidentally + # succeed against whatever the real test machine happens to have -- + # this must fail cleanly, not silently do nothing or pick up an + # unrelated real folder. + fake_home = tmpdir / "fake-home-no-notes-here" + fake_home.mkdir() + r_nowhere = subprocess.run( + [sys.executable, str(Path(__file__).parent / "hdc"), "sync"], + cwd=tmpdir, capture_output=True, text=True, timeout=15, + env={**os.environ, "HOME": str(fake_home)}, + ) + check("sync with no --dir and nothing discoverable anywhere fails cleanly, not silently", + r_nowhere.returncode != 0, r_nowhere.stdout + r_nowhere.stderr) + + # --- re-init refuses to clobber --- + r2 = run_hd("init", f"http://127.0.0.1:{port}", "--cookie", "session=abc123", + "--dir", str(target), cwd=tmpdir) + check("re-init refuses (nonzero exit)", r2.returncode != 0) + check("re-init leaves existing cookie untouched", + json.loads((target / ".hd" / "cookies.json").read_text())["cookie"] == "session=abc123") + + # --- sync after a server-side change --- + notes["n1"]["tags"] = ["radio", "reference"] + r3 = run_hd("sync", "--dir", str(target), cwd=tmpdir) + check("sync exits 0", r3.returncode == 0, r3.stderr) + check("sync picked up new tag", (target / "reference" / "Fox Hunt Notes").is_symlink()) + + # --- sync with no changes reports up to date --- + r4 = run_hd("sync", "--dir", str(target), cwd=tmpdir) + check("second sync exits 0", r4.returncode == 0) + check("second sync says up to date", "Up to date" in r4.stdout, r4.stdout) + + # --- sync against a nonexistent dir fails cleanly --- + r5 = run_hd("sync", "--dir", str(tmpdir / "nope"), cwd=tmpdir) + check("sync on uninitialized dir fails", r5.returncode != 0) + + shutil.rmtree(target) + + # --- login dialog: email prompted via --email, password via stdin --- + r6 = run_hd("init", f"http://127.0.0.1:{port}", "--email", FakeServer.VALID_EMAIL, + "--dir", str(target), cwd=tmpdir, input_text=FakeServer.VALID_PASSWORD + "\n") + check("login-flow init exits 0", r6.returncode == 0, r6.stderr) + check("login-flow saved email in config.json (no password)", + json.loads((target / ".hd" / "config.json").read_text()).get("email") == FakeServer.VALID_EMAIL) + check("login-flow config.json has no password field", + "password" not in json.loads((target / ".hd" / "config.json").read_text())) + check("login-flow captured the session cookie HedgeDoc actually set", + "connect.sid=loggedinsession" in json.loads((target / ".hd" / "cookies.json").read_text())["cookie"]) + check("login-flow ran first sync successfully", + (target / "radio" / "Fox Hunt Notes").is_symlink()) + + shutil.rmtree(target) + + # --- login dialog with wrong password: clean failure, nothing written --- + r7 = run_hd("init", f"http://127.0.0.1:{port}", "--email", FakeServer.VALID_EMAIL, + "--dir", str(target), cwd=tmpdir, input_text="wrong password\n") + check("wrong-password init exits nonzero", r7.returncode != 0) + check("wrong-password init did not create .hd", not (target / ".hd").exists()) + check("wrong-password init explains the failure", "Login failed" in r7.stderr, r7.stderr) + + finally: + server.stop() + shutil.rmtree(tmpdir, ignore_errors=True) + + print(f"\n{len(PASS)} passed, {len(FAIL)} failed") + return 0 if not FAIL else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-cli/test_hd_core.py b/hd-cli/test_hd_core.py new file mode 100644 index 0000000..445b7cb --- /dev/null +++ b/hd-cli/test_hd_core.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python3 +import json +import shutil +import sys +import tempfile +import threading +from pathlib import Path + +sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common")) +from werkzeug.serving import make_server +from werkzeug.wrappers import Request, Response + +from hd_core import HedgeDocSource, State, reconcile + +PASS = [] +FAIL = [] + + +def check(name, cond, detail=""): + if cond: + PASS.append(name) + else: + FAIL.append((name, detail)) + print(f"FAIL: {name} {detail}") + + +class FakeHistoryServer: + """Serves /history and /<id>/download from an in-memory dict this test + mutates directly between reconcile() calls, so each call sees the state + as it stood at that moment -- like a real server changing between syncs. + Each note dict may include "time" (default 0) -- tests bump it whenever + they simulate a real edit, mirroring how /history's own `time` field + actually moves on the real server; download_count tracks /download hits + so tests can assert the skip-fetch-when-unchanged optimization fires.""" + + def __init__(self, port): + self.notes = {} # id -> {"title":..., "tags":[...], "content":..., "time": int} + self.port = port + self.download_count = {} # id -> number of /download requests served + + def app(environ, start_response): + request = Request(environ) + if request.path == "/history": + history = [ + {"id": nid, "text": n["title"], "tags": n["tags"], "time": n.get("time", 0)} + for nid, n in self.notes.items() + ] + resp = Response(json.dumps({"history": history}), mimetype="application/json") + elif request.path.endswith("/download"): + nid = request.path.split("/")[1] + n = self.notes.get(nid) + self.download_count[nid] = self.download_count.get(nid, 0) + 1 + if n is None: + resp = Response("not found", status=404) + else: + resp = Response(n["content"], mimetype="text/markdown") + else: + resp = Response("not found", status=404) + return resp(environ, start_response) + + self.srv = make_server("127.0.0.1", port, app, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + + def stop(self): + self.srv.shutdown() + + +def free_port(): + import socket + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + p = s.getsockname()[1] + s.close() + return p + + +def listing(root: Path, tag: str): + d = root / tag + if not d.exists(): + return {} + return {p.name: p.resolve() for p in d.iterdir() if p.is_symlink()} + + +def main(): + port = free_port() + server = FakeHistoryServer(port) + server.start() + + tmpdir = Path(tempfile.mkdtemp(prefix="hd-test-")) + root = tmpdir / "notes" + hd_dir = root / ".hd" + (hd_dir / "notes").mkdir(parents=True) + source = HedgeDocSource(f"http://127.0.0.1:{port}", cookie="test=1") + state = State() + + try: + # --- 1. Two notes, one shared tag, one exclusive tag each --- + server.notes["id1"] = {"title": "Radio Log", "tags": ["radio", "work"], "content": "# Radio Log\ncontent A", "time": 1} + server.notes["id2"] = {"title": "Grocery List", "tags": ["personal"], "content": "# Grocery List\nmilk", "time": 1} + server.notes["id3"] = {"title": "Scratch", "tags": [], "content": "just some notes", "time": 1} + + r1 = reconcile(root, source, state) + check("initial: 3 notes updated", len(r1.notes_updated) == 3, r1.notes_updated) + check("radio/ has Radio Log", "Radio Log" in listing(root, "radio")) + check("work/ has Radio Log", "Radio Log" in listing(root, "work")) + check("personal/ has Grocery List", "Grocery List" in listing(root, "personal")) + check("untagged/ has Scratch", "Scratch" in listing(root, "untagged")) + check("cache file id1 has right content", + (hd_dir / "notes" / "id1.md").read_text() == "# Radio Log\ncontent A") + check("radio/Radio Log resolves to id1.md", + listing(root, "radio")["Radio Log"] == (hd_dir / "notes" / "id1.md").resolve()) + check("initial: each note fetched exactly once", + server.download_count == {"id1": 1, "id2": 1, "id3": 1}, server.download_count) + + # --- 2. Idempotent re-run: nothing changed, and /download is never + # called again since /history's `time` field didn't move --- + r2 = reconcile(root, source, state) + check("idempotent: no notes updated", r2.notes_updated == [], r2.notes_updated) + check("idempotent: no symlinks created", r2.symlinks_created == [], r2.symlinks_created) + check("idempotent: no symlinks removed", r2.symlinks_removed == [], r2.symlinks_removed) + check("idempotent: no re-fetch when time is unchanged", + server.download_count == {"id1": 1, "id2": 1, "id3": 1}, server.download_count) + + # --- 3. Retag: id1 loses 'work', gains 'reference' (a real retag + # edits the note's frontmatter, so /history's time moves too) --- + server.notes["id1"]["tags"] = ["radio", "reference"] + server.notes["id1"]["time"] = 2 + r3 = reconcile(root, source, state) + check("retag: id1 marked updated", "id1" in r3.notes_updated) + check("retag: work/ no longer has Radio Log", "Radio Log" not in listing(root, "work")) + check("retag: reference/ has Radio Log", "Radio Log" in listing(root, "reference")) + check("retag: radio/ still has Radio Log", "Radio Log" in listing(root, "radio")) + + # --- 4. Note becomes fully untagged --- + server.notes["id2"]["tags"] = [] + server.notes["id2"]["time"] = 2 + r4 = reconcile(root, source, state) + check("untag: personal/ no longer has Grocery List", "Grocery List" not in listing(root, "personal")) + check("untag: untagged/ has Grocery List", "Grocery List" in listing(root, "untagged")) + + # --- 5. Title change: symlink renamed, id mapping preserved --- + server.notes["id1"]["title"] = "Ham Radio Log" + server.notes["id1"]["time"] = 3 + r5 = reconcile(root, source, state) + check("rename: old name gone from radio/", "Radio Log" not in listing(root, "radio")) + check("rename: new name present in radio/", "Ham Radio Log" in listing(root, "radio")) + check("rename: still resolves to id1.md", + listing(root, "radio")["Ham Radio Log"] == (hd_dir / "notes" / "id1.md").resolve()) + check("rename: reference/ also renamed", "Ham Radio Log" in listing(root, "reference")) + + # --- 6. Filename collision: two notes, same title, same tag --- + server.notes["id4"] = {"title": "Ham Radio Log", "tags": ["radio"], "content": "different note, same title", "time": 1} + r6 = reconcile(root, source, state) + radio_files = listing(root, "radio") + check("collision: both variants present", len(radio_files) == 2, radio_files) + check("collision: deduped name uses id suffix", + any(name.startswith("Ham Radio Log-") for name in radio_files)) + + # --- 7. Content update without title/tag change: cache refreshes, symlink name stable --- + old_name = state.notes["id1"].symlinks["radio"] + server.notes["id1"]["content"] = "# Ham Radio Log\nupdated content" + server.notes["id1"]["time"] = 4 + r7 = reconcile(root, source, state) + check("content update: id1 flagged updated", "id1" in r7.notes_updated) + check("content update: symlink name unchanged", state.notes["id1"].symlinks["radio"] == old_name) + check("content update: cache file reflects new content", + (hd_dir / "notes" / "id1.md").read_text() == "# Ham Radio Log\nupdated content") + check("content update: id1 was actually re-fetched (time moved)", + server.download_count["id1"] == 4, server.download_count) + + # --- 8. Note deleted server-side: pruned locally --- + del server.notes["id3"] + r8 = reconcile(root, source, state) + check("deletion: id3 in notes_removed", "id3" in r8.notes_removed) + check("deletion: untagged/Scratch gone", "Scratch" not in listing(root, "untagged")) + check("deletion: cache file gone", not (hd_dir / "notes" / "id3.md").exists()) + check("deletion: state no longer tracks id3", "id3" not in state.notes) + + # --- 9. Re-persist state through JSON round-trip and re-sync: still idempotent --- + state.save(hd_dir) + state2 = State.load(hd_dir) + r9 = reconcile(root, source, state2) + check("post-reload idempotent: no updates", r9.notes_updated == [], r9.notes_updated) + check("post-reload idempotent: no symlink churn", + not r9.symlinks_created and not r9.symlinks_removed, + (r9.symlinks_created, r9.symlinks_removed)) + + finally: + server.stop() + shutil.rmtree(tmpdir, ignore_errors=True) + + test_update_note_cache() + + print(f"\n{len(PASS)} passed, {len(FAIL)} failed") + return 0 if not FAIL else 1 + + +def test_update_note_cache(): + """hd_core.update_note_cache: refreshes the local cache + hash after an + hd-joe edit session, without touching title/tags/symlinks, and is a + safe no-op for a note state.json doesn't know about yet.""" + import shutil, tempfile + from hd_core import NoteState, State, content_hash, update_note_cache + + tmpdir = Path(tempfile.mkdtemp(prefix="hd-cache-test-")) + root = tmpdir / "notes" + hd_dir = root / ".hd" + (hd_dir / "notes").mkdir(parents=True) + try: + old_text = "---\ntitle: Masten\ntags: sl6cv\n---\n\nold content" + (hd_dir / "notes" / "n1.md").write_text(old_text) + state = State() + state.notes["n1"] = NoteState( + title="Masten", tags=["sl6cv"], symlinks={"sl6cv": "Masten"}, + content_hash=content_hash(old_text), + ) + state.save(hd_dir) + + new_text = "---\ntitle: Masten\ntags: sl6cv\n---\n\nAllt är korrekt!\nedited at EOF" + updated = update_note_cache(root, "n1", new_text) + check("update_note_cache returns True for a known note", updated is True) + check("cache file reflects the new content", + (hd_dir / "notes" / "n1.md").read_text() == new_text) + + reloaded = State.load(hd_dir) + check("content_hash updated in state.json", + reloaded.notes["n1"].content_hash == content_hash(new_text)) + check("title untouched", reloaded.notes["n1"].title == "Masten") + check("tags untouched", reloaded.notes["n1"].tags == ["sl6cv"]) + check("symlinks untouched", reloaded.notes["n1"].symlinks == {"sl6cv": "Masten"}) + + # Unknown note id (opened via explicit url+note-id, never synced) -- safe no-op + result = update_note_cache(root, "never-seen-before", "whatever") + check("update_note_cache returns False for an unknown note", result is False) + check("no stray cache file created for the unknown note", + not (hd_dir / "notes" / "never-seen-before.md").exists()) + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-cli/test_hd_problems.py b/hd-cli/test_hd_problems.py new file mode 100644 index 0000000..762f2b7 --- /dev/null +++ b/hd-cli/test_hd_problems.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +import fcntl +import os +import shutil +import sys +import tempfile +import threading +import time +from pathlib import Path + +sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common")) +from hd_core import ( + NoteState, ReconcileLock, State, content_hash, detect_problems, + load_problems, save_problems, Problem, +) + +PASS = [] +FAIL = [] + + +def check(name, cond, detail=""): + if cond: + PASS.append(name) + else: + FAIL.append((name, detail)) + print(f"FAIL: {name} {detail}") + + +def main(): + tmpdir = Path(tempfile.mkdtemp(prefix="hd-problems-test-")) + root = tmpdir / "notes" + hd_dir = root / ".hd" + notes_dir = hd_dir / "notes" + notes_dir.mkdir(parents=True) + + try: + # --- set up a healthy note with a real cached copy + symlink --- + note_text = "# Fox Hunt\nfrequencies here" + (notes_dir / "id1.md").write_text(note_text) + state = State() + state.notes["id1"] = NoteState( + title="Fox Hunt", tags=["radio"], symlinks={"radio": "Fox Hunt.md"}, + content_hash=content_hash(note_text), + ) + radio_dir = root / "radio" + radio_dir.mkdir(parents=True) + (radio_dir / "Fox Hunt.md").symlink_to(Path("..") / ".hd" / "notes" / "id1.md") + + problems = detect_problems(root, state) + check("healthy symlink: no problems", problems == [], problems) + + # --- nested_dir: a real directory where a tag symlink is expected --- + (radio_dir / "subproject").mkdir() + problems = detect_problems(root, state) + kinds = {p.kind for p in problems} + check("nested directory flagged", "nested_dir" in kinds, problems) + nested = next(p for p in problems if p.kind == "nested_dir") + check("nested_dir path is correct", nested.path == "radio/subproject", nested.path) + shutil.rmtree(radio_dir / "subproject") + + # --- stray_file: cp without -P, content matches a known note --- + (radio_dir / "Accidental Copy.md").write_text(note_text) # same content as id1 + problems = detect_problems(root, state) + stray = next((p for p in problems if p.kind == "stray_file"), None) + check("stray file detected", stray is not None, problems) + check("stray file identified via checksum match", "id1" in (stray.detail if stray else ""), + stray.detail if stray else None) + check("stray file suggests a fix command", "hdc tag" in (stray.detail if stray else ""), + stray.detail if stray else None) + + # --- stray file with NO checksum match: says so plainly, no guess --- + (radio_dir / "Accidental Copy.md").unlink() + (radio_dir / "Unknown Content.md").write_text("this matches no cached note at all") + problems = detect_problems(root, state) + unknown_stray = next(p for p in problems if p.kind == "stray_file" and p.path.endswith("Unknown Content.md")) + check("unmatched stray file has no fabricated suggestion", unknown_stray.detail == "", unknown_stray.detail) + (radio_dir / "Unknown Content.md").unlink() + + # --- broken_symlink: target no longer exists --- + (radio_dir / "Ghost.md").symlink_to(Path("..") / ".hd" / "notes" / "does-not-exist.md") + problems = detect_problems(root, state) + check("broken symlink flagged", any(p.kind == "broken_symlink" for p in problems), problems) + (radio_dir / "Ghost.md").unlink() + + # --- foreign_symlink: points somewhere outside .hd/notes/ entirely --- + outside_target = tmpdir / "outside.md" + outside_target.write_text("not managed by hd") + (radio_dir / "Manual Link.md").symlink_to(outside_target) + problems = detect_problems(root, state) + check("foreign symlink flagged", any(p.kind == "foreign_symlink" for p in problems), problems) + (radio_dir / "Manual Link.md").unlink() + + # --- back to healthy: zero problems again --- + problems = detect_problems(root, state) + check("clean again after removing all the injected problems", problems == [], problems) + + # --- save_problems / load_problems round-trip --- + fake_problems = [Problem("stray_file", "radio/x.md", "content matches note 'id7'")] + save_problems(hd_dir, fake_problems) + check(".hd/problems.json was created", (hd_dir / "problems.json").exists()) + loaded = load_problems(hd_dir) + check("round-tripped problem matches", loaded == fake_problems, loaded) + check("Problem.__str__ produces a readable message", + "content matches note 'id7'" in str(fake_problems[0]), str(fake_problems[0])) + + # --- ReconcileLock actually provides mutual exclusion (real flock) --- + lock_path = hd_dir / ".lock" + held = threading.Event() + release = threading.Event() + + def holder(): + with ReconcileLock(hd_dir): + held.set() + release.wait(timeout=5) + + t = threading.Thread(target=holder, daemon=True) + t.start() + held.wait(timeout=5) + + # A second, independent file descriptor to the same lock file must + # NOT be acquirable non-blocking while the thread above holds it. + fd2 = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600) + try: + fcntl.flock(fd2, fcntl.LOCK_EX | fcntl.LOCK_NB) + check("flock actually blocks a concurrent holder", False, "acquired when it should have blocked") + fcntl.flock(fd2, fcntl.LOCK_UN) + except BlockingIOError: + check("flock actually blocks a concurrent holder", True) + finally: + os.close(fd2) + + release.set() + t.join(timeout=5) + + # Now that the thread released it, a fresh acquire must succeed. + fd3 = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600) + try: + fcntl.flock(fd3, fcntl.LOCK_EX | fcntl.LOCK_NB) + check("lock is acquirable again after release", True) + fcntl.flock(fd3, fcntl.LOCK_UN) + except BlockingIOError: + check("lock is acquirable again after release", False, "still blocked") + finally: + os.close(fd3) + + check("marker file is gone after the lock is released", not (hd_dir / ".reconciling.lock").exists()) + + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + print(f"\n{len(PASS)} passed, {len(FAIL)} failed") + return 0 if not FAIL else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-cli/test_hd_tag_cli.py b/hd-cli/test_hd_tag_cli.py new file mode 100644 index 0000000..c566795 --- /dev/null +++ b/hd-cli/test_hd_tag_cli.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +import json +import shutil +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common")) +import socketio +from werkzeug.serving import make_server +from werkzeug.wrappers import Request, Response + +from hd_client import apply_operation +from hd_core import parse_current_tags, parse_frontmatter + +PASS = [] +FAIL = [] + + +def check(name, cond, detail=""): + if cond: + PASS.append(name) + else: + FAIL.append((name, detail)) + print(f"FAIL: {name} {detail}") + + +def apply_operation_strict(text, op): + for c in op: + if isinstance(c, bool): + raise ValueError(f"unknown operation: {c!r}") + if isinstance(c, int) and c == 0: + raise ValueError(f"unknown operation: {c!r}") + return apply_operation(text, op) + + +class CombinedFakeServer: + """Serves /history, /<id>/download, AND the realtime Socket.IO channel + from one shared note store -- close enough to real HedgeDoc that `hd + sync` and `hd tag`/`hd untag` can both run against it in the same test, + the way they'd run against a real server.""" + + def __init__(self, port): + self.notes = {} # id -> {"title", "tags", "content", "time", "revision"} + self.port = port + self.lock = threading.Lock() + + self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") + + @self.sio.event + def connect(sid, environ, auth): + from urllib.parse import parse_qs + qs = parse_qs(environ.get("QUERY_STRING", "")) + note_id = (qs.get("noteId") or [None])[0] + with self.lock: + n = self.notes.get(note_id) + if n is None: + return + self.sio.save_session(sid, {"note_id": note_id}) + self.sio.emit("doc", {"str": n["content"], "revision": n["revision"], "clients": []}, to=sid) + + @self.sio.on("operation") + def on_operation(sid, base_revision, operation, selection): + with self.lock: + session = self.sio.get_session(sid) + note_id = session["note_id"] + n = self.notes[note_id] + if base_revision != n["revision"]: + return + try: + n["content"] = apply_operation_strict(n["content"], operation) + except Exception as exc: + print("[fake server] rejected:", exc, operation) + return + n["revision"] += 1 + n["time"] += 1 # a real edit always moves /history's time + self.sio.emit("ack", n["revision"], to=sid) + + self._socketio_app = socketio.WSGIApp(self.sio) + + def wsgi(environ, start_response): + request = Request(environ) + if request.path == "/history": + with self.lock: + history = [] + for nid, n in self.notes.items(): + # Tags are derived from the note's own content, exactly + # like real HedgeDoc's Note.parseNoteInfo does -- not + # from a separate field this test tracks by hand. + fm = parse_frontmatter(n["content"]) + tags = parse_current_tags(__import__("yaml").safe_load(fm["yaml_str"]) or {}) if fm else [] + history.append({"id": nid, "text": n["title"], "tags": tags, "time": n["time"]}) + resp = Response(json.dumps({"history": history}), mimetype="application/json") + return resp(environ, start_response) + if request.path.endswith("/download"): + nid = request.path.split("/")[1] + with self.lock: + n = self.notes.get(nid) + resp = Response(n["content"] if n else "", mimetype="text/markdown", + status=200 if n else 404) + return resp(environ, start_response) + return socketio.WSGIApp(self.sio)(environ, start_response) + + self.srv = make_server("127.0.0.1", port, wsgi, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + + def stop(self): + self.srv.shutdown() + + +def free_port(): + import socket + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + p = s.getsockname()[1] + s.close() + return p + + +def run_hd(*args, cwd): + return subprocess.run( + [sys.executable, str(Path(__file__).parent / "hdc"), *args], + cwd=cwd, capture_output=True, text=True, timeout=15, + ) + + +def main(): + port = free_port() + server = CombinedFakeServer(port) + server.notes["n1"] = { + "title": "Fox Hunt Notes", + "content": "---\ntitle: Fox Hunt Notes\ntags: radio\n---\n\nfrequencies here", + "time": 1, "revision": 0, + } + server.start() + time.sleep(0.2) + + tmpdir = Path(tempfile.mkdtemp(prefix="hd-tag-cli-test-")) + target = tmpdir / "notes" + + try: + r = run_hd("init", f"http://127.0.0.1:{port}", "--cookie", "session=abc", + "--dir", str(target), cwd=tmpdir) + check("init ok", r.returncode == 0, r.stderr) + check("initial symlink present", (target / "radio" / "Fox Hunt Notes").is_symlink()) + + # --- hd tag by title: adds a new tag, writes to server, resyncs locally --- + r2 = run_hd("tag", "Fox Hunt Notes", "reference", "--dir", str(target), cwd=tmpdir) + check("hd tag exits 0", r2.returncode == 0, r2.stderr) + check("hd tag reports the new tag list", "reference" in r2.stdout, r2.stdout) + fm = parse_frontmatter(server.notes["n1"]["content"]) + server_tags = parse_current_tags(__import__("yaml").safe_load(fm["yaml_str"])) if fm else [] + check("server-side frontmatter actually updated", + server_tags == ["radio", "reference"], server_tags) + check("new symlink appeared locally", (target / "reference" / "Fox Hunt Notes").is_symlink()) + check("old symlink still present too", (target / "radio" / "Fox Hunt Notes").is_symlink()) + + # --- hd tag by id --- + r3 = run_hd("tag", "n1", "urgent", "--dir", str(target), cwd=tmpdir) + check("hd tag by id exits 0", r3.returncode == 0, r3.stderr) + check("tag-by-id symlink appeared", (target / "urgent" / "Fox Hunt Notes").is_symlink()) + + # --- hd untag removes it again --- + r4 = run_hd("untag", "n1", "urgent", "--dir", str(target), cwd=tmpdir) + check("hd untag exits 0", r4.returncode == 0, r4.stderr) + check("untagged symlink removed", not (target / "urgent" / "Fox Hunt Notes").exists()) + + # --- resolving an unknown note fails cleanly, no crash --- + r5 = run_hd("tag", "does-not-exist", "x", "--dir", str(target), cwd=tmpdir) + check("unknown note ref fails cleanly", r5.returncode != 0) + check("unknown note ref explains why", "No known note" in r5.stderr, r5.stderr) + + finally: + server.stop() + shutil.rmtree(tmpdir, ignore_errors=True) + + print(f"\n{len(PASS)} passed, {len(FAIL)} failed") + return 0 if not FAIL else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-cli/test_hd_tag_stale_history.py b/hd-cli/test_hd_tag_stale_history.py new file mode 100644 index 0000000..c04541b --- /dev/null +++ b/hd-cli/test_hd_tag_stale_history.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Reproduces the bug Joakim hit for real: after 'hdc untag', the removed +tag's symlink stayed in place for several seconds. Every existing fake +server in this test suite derives /history's tags live from the note's +current content on every request -- perfectly, instantly consistent, +which is exactly the kind of too-forgiving fake server that already hid +more than one bug in this project (see CHANGES-0.7.14, -0.7.15). Real +HedgeDoc's /history reflects a DB view that's flushed on a delay, same as +content -- this test's StaleHistoryFakeServer deliberately reproduces +that: /history keeps reporting the OLD tags for a configurable delay +after a write actually lands. +""" +import json +import shutil +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common")) +import socketio +from werkzeug.serving import make_server +from werkzeug.wrappers import Request, Response + +from hd_client import apply_operation +from hd_core import parse_current_tags, parse_frontmatter + +PASS = [] +FAIL = [] + + +def check(name, cond, detail=""): + if cond: + PASS.append(name) + else: + FAIL.append((name, detail)) + print(f"FAIL: {name} {detail}") + + +def apply_operation_strict(text, op): + for c in op: + if isinstance(c, bool): + raise ValueError(f"unknown operation: {c!r}") + if isinstance(c, int) and c == 0: + raise ValueError(f"unknown operation: {c!r}") + return apply_operation(text, op) + + +class StaleHistoryFakeServer: + """Like test_hd_tag_cli.py's CombinedFakeServer, but /history's view of + a note's tags/time is deliberately DELAYED by `history_delay` seconds + after a write actually completes -- reproducing HedgeDoc's own + DB-flush lag instead of the instant consistency every other fake + server in this suite gives for free.""" + + def __init__(self, port, history_delay=1.5): + self.notes = {} # id -> {"title", "content", "time", "revision"} + self.history_delay = history_delay + self.port = port + self.lock = threading.Lock() + + self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") + + @self.sio.event + def connect(sid, environ, auth): + from urllib.parse import parse_qs + qs = parse_qs(environ.get("QUERY_STRING", "")) + note_id = (qs.get("noteId") or [None])[0] + with self.lock: + n = self.notes.get(note_id) + if n is None: + return + self.sio.save_session(sid, {"note_id": note_id}) + self.sio.emit("doc", {"str": n["content"], "revision": n["revision"], "clients": []}, to=sid) + + @self.sio.on("operation") + def on_operation(sid, base_revision, operation, selection): + with self.lock: + session = self.sio.get_session(sid) + note_id = session["note_id"] + n = self.notes[note_id] + if base_revision != n["revision"]: + return + try: + n["content"] = apply_operation_strict(n["content"], operation) + except Exception as exc: + print("[fake server] rejected:", exc, operation) + return + n["revision"] += 1 + n["time"] += 1 + self.sio.emit("ack", n["revision"], to=sid) + # The write is confirmed to the client (and to write_tags()'s + # caller) immediately, same as the real thing. /history's view + # of it, deliberately, is not -- scheduled to "flush" later. + threading.Timer(self.history_delay, self._flush_history, args=(note_id,)).start() + + self._socketio_app = socketio.WSGIApp(self.sio) + + def wsgi(environ, start_response): + request = Request(environ) + if request.path == "/history": + with self.lock: + history = [] + for nid, n in self.notes.items(): + fm = parse_frontmatter(n["committed_content"]) + tags = parse_current_tags(__import__("yaml").safe_load(fm["yaml_str"]) or {}) if fm else [] + history.append({"id": nid, "text": n["title"], "tags": tags, "time": n["committed_time"]}) + resp = Response(json.dumps({"history": history}), mimetype="application/json") + return resp(environ, start_response) + if request.path.endswith("/download"): + nid = request.path.split("/")[1] + with self.lock: + n = self.notes.get(nid) + resp = Response(n["content"] if n else "", mimetype="text/markdown", + status=200 if n else 404) + return resp(environ, start_response) + return self._socketio_app(environ, start_response) + + self.srv = make_server("127.0.0.1", port, wsgi, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def _flush_history(self, note_id): + with self.lock: + n = self.notes.get(note_id) + if n: + n["committed_content"] = n["content"] + n["committed_time"] = n["time"] + + def add_note(self, note_id, title, content, t=1): + self.notes[note_id] = { + "title": title, "content": content, "committed_content": content, + "time": t, "committed_time": t, "revision": 0, + } + + def start(self): + self.thread.start() + + def stop(self): + self.srv.shutdown() + + +def free_port(): + import socket + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + p = s.getsockname()[1] + s.close() + return p + + +def run_hdc(*args, cwd): + return subprocess.run( + [sys.executable, str(Path(__file__).parent / "hdc"), *args], + cwd=cwd, capture_output=True, text=True, timeout=15, + ) + + +def main(): + port = free_port() + # Long enough to reliably still be stale through the ENTIRE 'hdc untag' + # command's execution, including its own trailing sync -- 1.5s was + # tried first and wasn't long enough: real subprocess + multiple + # network round trips (the write's own socket connection, then a + # fresh /history HTTP GET) routinely took longer than that in + # practice, so the first version of this test passed by accident, + # without ever actually exercising the race it was meant to catch. + server = StaleHistoryFakeServer(port, history_delay=8.0) + server.add_note("n1", "FOI", "---\ntitle: FOI\ntags: TaBort\n---\n\ncontent here") + server.start() + time.sleep(0.2) + + tmpdir = Path(tempfile.mkdtemp(prefix="hd-stale-history-test-")) + target = tmpdir / "notes" + + try: + r_init = run_hdc("init", f"http://127.0.0.1:{port}", "--cookie", "session=1", + "--dir", str(target), cwd=str(tmpdir)) + check("init succeeded", r_init.returncode == 0, r_init.stdout + r_init.stderr) + check("initial sync created the TaBort symlink", (target / "TaBort" / "FOI").is_symlink(), + list((target / "TaBort").iterdir()) if (target / "TaBort").exists() else "no TaBort dir") + + # This is the exact scenario Joakim hit: untag, then check the + # symlink IMMEDIATELY -- while /history is still deliberately + # reporting the OLD tag list (history_delay hasn't elapsed yet). + r_untag = run_hdc("untag", "n1", "TaBort", "--dir", str(target), cwd=str(tmpdir)) + check("untag command succeeded", r_untag.returncode == 0, r_untag.stdout + r_untag.stderr) + check("write confirmed no tags remain", "tags now [(none)]" in r_untag.stdout, r_untag.stdout) + + still_there = (target / "TaBort" / "FOI").exists() + check("symlink is gone IMMEDIATELY after untag, not several seconds later " + "(the actual bug: update_note_tags_locally applies the write's own " + "confirmed result directly, without waiting for /history to catch up)", + not still_there, "still present!" if still_there else "correctly removed") + + # And state.json should already reflect it too, not just the filesystem. + from hd_core import State + state = State.load(target / ".hd") + # Matches reconcile()'s own convention: an untagged note is recorded + # as ["untagged"], never an empty list -- not [], see hd_core.py's + # UNTAGGED substitution in both reconcile() and _sync_note_symlinks(). + from hd_core import UNTAGGED + check("state.json already shows the note as untagged (not still 'TaBort')", + state.notes["n1"].tags == [UNTAGGED], state.notes["n1"].tags) + check("state.json's symlinks dict no longer has TaBort", "TaBort" not in state.notes["n1"].symlinks, + state.notes["n1"].symlinks) + + # Once /history actually catches up, a later sync must still agree + # (this direct update should be idempotent with reconcile(), not + # just a one-off hack that diverges from it). + time.sleep(8.5) + r_sync = run_hdc("sync", "--dir", str(target), cwd=str(tmpdir)) + check("later sync (once /history has caught up) succeeds", r_sync.returncode == 0, r_sync.stdout) + check("still no TaBort symlink after /history catches up too", + not (target / "TaBort" / "FOI").exists()) + + finally: + server.stop() + shutil.rmtree(tmpdir, ignore_errors=True) + + print(f"\n{len(PASS)} passed, {len(FAIL)} failed") + return 0 if not FAIL else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-cli/test_hd_tags.py b/hd-cli/test_hd_tags.py new file mode 100644 index 0000000..6e9991b --- /dev/null +++ b/hd-cli/test_hd_tags.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +import sys +from pathlib import Path +sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common")) + +from hd_core import ( + FrontmatterError, NoteState, State, compute_tag_patch, parse_current_tags, + parse_frontmatter, resolve_note_ref, +) + +PASS = [] +FAIL = [] + + +def check(name, cond, detail=""): + if cond: + PASS.append(name) + else: + FAIL.append((name, detail)) + print(f"FAIL: {name} {detail}") + + +def apply_patch(text, patch): + start, end, repl = patch + return text[:start] + repl + text[end:] + + +def main(): + # --- parse_frontmatter --- + check("no frontmatter -> None", parse_frontmatter("# just a heading\nbody") is None) + fm = parse_frontmatter("---\ntitle: X\ntags: a, b\n---\nbody") + check("frontmatter detected", fm is not None) + check("yaml_str excludes closing delimiter", + fm["yaml_str"] == "---\ntitle: X\ntags: a, b", repr(fm["yaml_str"])) + fm_dots = parse_frontmatter("---\ntitle: X\n...\nbody") + check("'...' closing delimiter also works", fm_dots is not None) + check("unterminated frontmatter -> None", parse_frontmatter("---\ntitle: X\nno closing") is None) + + # --- parse_current_tags: mirrors extractNoteTags exactly --- + check("comma string parsed and deduped", + parse_current_tags({"tags": "work, radio, work"}) == ["work", "radio"]) + check("bare number accepted (matches JS typeof check)", + parse_current_tags({"tags": 42}) == ["42"]) + check("YAML list silently ignored (matches server behavior)", + parse_current_tags({"tags": ["work", "radio"]}) == []) + check("missing tags key -> empty", parse_current_tags({"title": "X"}) == []) + check("bool tags value ignored (bool is technically an int subclass in Python)", + parse_current_tags({"tags": True}) == []) + + # --- compute_tag_patch: round-trip correctness --- + text = "---\ntitle: My Note\ntags: work\n---\n\n# Body\ncontent here" + patch = compute_tag_patch(text, ["work", "radio"]) + result = apply_patch(text, patch) + check("add tag: title preserved", "title: My Note" in result, result) + check("add tag: new tag present", parse_current_tags( + __import__("yaml").safe_load(parse_frontmatter(result)["yaml_str"])) == ["work", "radio"]) + check("add tag: body untouched", result.endswith("# Body\ncontent here"), result) + check("add tag: patch doesn't touch the whole document", + patch[1] < len(text), f"patch end={patch[1]} doc len={len(text)}") + + # untag down to zero -> tags key removed entirely, not left as "" + text2 = "---\ntitle: Solo\ntags: onlyone\n---\nbody" + patch2 = compute_tag_patch(text2, []) + result2 = apply_patch(text2, patch2) + meta2 = __import__("yaml").safe_load(parse_frontmatter(result2)["yaml_str"]) + check("untag to zero: tags key removed, not empty string", "tags" not in meta2, meta2) + check("untag to zero: title still preserved", meta2.get("title") == "Solo", meta2) + + # no frontmatter at all -> a fresh block gets inserted at position 0 + text3 = "# No frontmatter here\njust markdown" + patch3 = compute_tag_patch(text3, ["new"]) + check("no frontmatter: patch is a pure insert at 0", patch3[0] == 0 and patch3[1] == 0, patch3) + result3 = apply_patch(text3, patch3) + check("no frontmatter: original body still present verbatim", + result3.endswith(text3), result3) + fm3 = parse_frontmatter(result3) + check("no frontmatter: new block is now valid, parseable frontmatter", fm3 is not None) + check("no frontmatter: new tag present after insert", + parse_current_tags(__import__("yaml").safe_load(fm3["yaml_str"])) == ["new"]) + + # invalid YAML frontmatter -> refuse rather than clobber + bad = "---\ntitle: [unterminated\n---\nbody" + try: + compute_tag_patch(bad, ["x"]) + check("invalid YAML raises FrontmatterError", False, "did not raise") + except FrontmatterError: + check("invalid YAML raises FrontmatterError", True) + + # frontmatter that parses to a non-mapping (e.g. a bare scalar) -> refuse + scalar = "---\njust a string, not a mapping\n---\nbody" + try: + compute_tag_patch(scalar, ["x"]) + check("non-mapping frontmatter raises FrontmatterError", False, "did not raise") + except FrontmatterError: + check("non-mapping frontmatter raises FrontmatterError", True) + + # --- resolve_note_ref --- + state = State() + state.notes["id1"] = NoteState(title="Fox Hunt", tags=["radio"], symlinks={"radio": "Fox Hunt.md"}) + state.notes["id2"] = NoteState(title="Fox Hunt", tags=["work"], symlinks={"work": "Fox Hunt.md"}) + state.notes["id3"] = NoteState(title="Grocery List", tags=["personal"], symlinks={"personal": "Grocery List.md"}) + + check("resolve by exact id", resolve_note_ref(Path("/tmp/nonexistent-hd-root-xyz"), state, "id3") == "id3") + check("resolve by unique title", resolve_note_ref(Path("/tmp/nonexistent-hd-root-xyz"), state, "Grocery List") == "id3") + check("resolve by title is case-insensitive", resolve_note_ref(Path("/tmp/nonexistent-hd-root-xyz"), state, "grocery list") == "id3") + try: + resolve_note_ref(Path("/tmp/nonexistent-hd-root-xyz"), state, "Fox Hunt") + check("ambiguous title raises", False, "did not raise") + except ValueError as exc: + check("ambiguous title raises", True) + check("ambiguous title error names both ids", "id1" in str(exc) and "id2" in str(exc), str(exc)) + try: + resolve_note_ref(Path("/tmp/nonexistent-hd-root-xyz"), state, "nonexistent") + check("unknown ref raises", False, "did not raise") + except ValueError: + check("unknown ref raises", True) + + # --- resolve_note_ref: path resolution is cwd-relative, and wins over + # a same-named title elsewhere -- the bug Joakim reported: 'FOI' or + # '../work/FOI' used to resolve relative to ROOT, not to wherever the + # user actually was, and never took priority over a global title match --- + import shutil, tempfile + tmpdir = Path(tempfile.mkdtemp(prefix="hd-resolve-path-test-")) + try: + root2 = tmpdir / "notes" + hd_dir2 = root2 / ".hd" + (hd_dir2 / "notes").mkdir(parents=True) + (hd_dir2 / "notes" / "real-id.md").write_text("---\ntitle: Ambiguous\n---\n\nbody") + + radio_dir = root2 / "radio" + work_dir = root2 / "work" + radio_dir.mkdir() + work_dir.mkdir() + # The symlink actually lives in radio/ ... + (radio_dir / "FOI").symlink_to(Path("..") / ".hd" / "notes" / "real-id.md") + # ... but a note with the SAME TITLE also exists elsewhere, with a + # different id -- resolving 'FOI' from radio/ must never land on + # this one just because titles happen to collide. + state2 = State() + state2.notes["real-id"] = NoteState(title="Ambiguous", tags=["radio"], symlinks={"radio": "FOI"}) + state2.notes["decoy-id"] = NoteState(title="FOI", tags=["work"], symlinks={"work": "SomeOtherName"}) + + result = resolve_note_ref(root2, state2, "FOI", cwd=radio_dir) + check("bare name resolves to the symlink actually in cwd, not a same-named title elsewhere", + result == "real-id", result) + + # From work/, the SAME bare name 'FOI' must NOT resolve to + # radio/FOI (that's not the directory the user is standing in) -- + # no symlink named FOI exists in work/ itself, so this falls + # through to the (still-present, unchanged) title search, which + # correctly finds the OTHER note titled "FOI" -- a different id + # than the one radio/FOI resolves to. + result2 = resolve_note_ref(root2, state2, "FOI", cwd=work_dir) + check("same bare name from a DIFFERENT directory resolves differently " + "(falls through to title search, finds the note titled FOI instead)", + result2 == "decoy-id", result2) + + # A relative path with '..' resolves against cwd, not root. + result3 = resolve_note_ref(root2, state2, "../radio/FOI", cwd=work_dir) + check("'../radio/FOI' from work/ resolves against cwd (finds radio/FOI), " + "not against root (which would look for a nonexistent root/../radio/FOI)", + result3 == "real-id", result3) + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + print(f"\n{len(PASS)} passed, {len(FAIL)} failed") + return 0 if not FAIL else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-cli/test_hd_write.py b/hd-cli/test_hd_write.py new file mode 100644 index 0000000..5d54e5a --- /dev/null +++ b/hd-cli/test_hd_write.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +import sys +import threading +import time +from pathlib import Path + +sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common")) +import socketio +from werkzeug.serving import make_server + +from hd_client import apply_operation +from hd_core import parse_current_tags, parse_frontmatter, write_tags + +PASS = [] +FAIL = [] + + +def check(name, cond, detail=""): + if cond: + PASS.append(name) + else: + FAIL.append((name, detail)) + print(f"FAIL: {name} {detail}") + + +def apply_operation_strict(text, op): + for c in op: + if isinstance(c, bool): + raise ValueError(f"unknown operation: {c!r}") + if isinstance(c, int) and c == 0: + raise ValueError(f"unknown operation: {c!r}") + return apply_operation(text, op) + + +class FakeServer: + def __init__(self, initial_text, port): + self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") + self.text = initial_text + self.revision = 0 + self.lock = threading.Lock() + self.operations = [] + + @self.sio.event + def connect(sid, environ, auth): + with self.lock: + self.sio.emit("doc", {"str": self.text, "revision": self.revision, "clients": []}, to=sid) + + @self.sio.on("operation") + def on_operation(sid, base_revision, operation, selection): + with self.lock: + self.operations.append(operation) + if base_revision != self.revision: + return + try: + self.text = apply_operation_strict(self.text, operation) + except Exception as exc: + print("[fake server] rejected:", exc, operation) + return + self.revision += 1 + self.sio.emit("ack", self.revision, to=sid) + + self.app = socketio.WSGIApp(self.sio) + self.srv = make_server("127.0.0.1", port, self.app, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + + def stop(self): + self.srv.shutdown() + + +def free_port(): + import socket + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + p = s.getsockname()[1] + s.close() + return p + + +def main(): + # --- 1. Add a tag to a note that already has frontmatter + one tag --- + initial = "---\ntitle: Fox Hunt Notes\ntags: radio\n---\n\n# Frequencies\n144.390 MHz APRS\n" + port = free_port() + server = FakeServer(initial, port) + server.start() + time.sleep(0.2) + + new_tags = write_tags(f"http://127.0.0.1:{port}", "test=1", "note1", + lambda tags: tags if "reference" in tags else [*tags, "reference"]) + + check("write_tags returns the new tag list", new_tags == ["radio", "reference"], new_tags) + check("server revision advanced exactly once", server.revision == 1, server.revision) + fm = parse_frontmatter(server.text) + check("server text still has valid frontmatter", fm is not None) + import yaml + meta = yaml.safe_load(fm["yaml_str"]) + check("title untouched by the tag edit", meta.get("title") == "Fox Hunt Notes", meta) + check("tags updated on the server", parse_current_tags(meta) == ["radio", "reference"], meta) + check("body untouched by the tag edit", + server.text.endswith("# Frequencies\n144.390 MHz APRS\n"), repr(server.text)) + + check("edit was minimal, not a full-document replace", + len(server.operations) == 1 and len(server.operations[0]) <= 4, + server.operations) + # Minimality is already proven structurally above (body untouched, title + # untouched, exactly one operation) -- a byte-count heuristic on top of + # that is fragile (YAML re-dump size varies) and adds no real coverage. + + server.stop() + + # --- 2. Untag down to zero on a note with no frontmatter at all --- + initial2 = "# Bare note\nno frontmatter here at all" + port2 = free_port() + server2 = FakeServer(initial2, port2) + server2.start() + time.sleep(0.2) + + new_tags2 = write_tags(f"http://127.0.0.1:{port2}", "test=1", "note2", + lambda tags: [*tags, "urgent"]) # note had zero tags -> gains one + check("tag added to a previously bare note", new_tags2 == ["urgent"], new_tags2) + fm2 = parse_frontmatter(server2.text) + check("frontmatter block was created", fm2 is not None) + check("original body preserved verbatim after the frontmatter", + server2.text.rstrip("\n").endswith(initial2), repr(server2.text)) + server2.stop() + + # --- 3. No-op: mutate() returns the same tags -> no network write at all --- + initial3 = "---\ntitle: Steady\ntags: keep\n---\nbody" + port3 = free_port() + server3 = FakeServer(initial3, port3) + server3.start() + time.sleep(0.2) + result3 = write_tags(f"http://127.0.0.1:{port3}", "test=1", "note3", lambda tags: tags) + check("no-op mutate returns tags unchanged", result3 == ["keep"], result3) + check("no-op mutate sends no operation at all", server3.operations == [], server3.operations) + check("no-op mutate leaves server revision at 0", server3.revision == 0, server3.revision) + server3.stop() + + print(f"\n{len(PASS)} passed, {len(FAIL)} failed") + return 0 if not FAIL else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-joe/README.md b/hd-joe/README.md new file mode 100644 index 0000000..a63b52d --- /dev/null +++ b/hd-joe/README.md @@ -0,0 +1,71 @@ +# hd-joe + +The Python side of the terminal editor. Owns the Socket.IO/OT connection to +HedgeDoc and drives a patched JOE over a private Unix socket. + +Run `../install.sh` from the repo root first (builds patched JOE, sets up a +venv, links `hdc` and `hd-joe` onto your PATH). This README covers `hd-joe` +specifically once that's done; see the top-level README for the whole repo. + +## Running + +Two forms. The second needs an `hdc`-managed folder (see `../hd-cli/`); the +first works anywhere. + + # Explicit: any server, any note, no hdc setup needed + hd-joe https://hedgedoc.example <note-id> --cookie 'connect.sid=...' + + # From inside ~/notes/<tag>/ : reads .hd/config.json + cookies.json, + # opens "Project" if a symlink for it exists here, else creates it + # tagged with this directory's name + cd ~/notes/radio + hd-joe "Project" + +Useful flags: `--debug` (verbose log), `--log PATH` (default +`~/.local/state/picocalc/hd-joe.log`), `--buffer PATH` (keep the working +file instead of a temp file), `--quiet`, `--joe PATH` (use a specific joe +binary instead of the one `install.sh` put on PATH). + +## Files + +| File | | +| --- | --- | +| `hd-joe` | Entry point (thin `sh` wrapper around `hd_joe_agent.py`). | +| `hd_joe_agent.py` | CLI, JOE subprocess management, the Unix-socket bridge, translating OT operations into JOE insert/delete commands. | +| `joe_wrapper.py` | Installed AT the `joe` name (see top-level README's "The joe wrapper") -- routes hd-managed notes here, everything else to the real binary. `decide()` is the pure, tested routing logic; `run()`/`main()` just `exec` whatever it returns. | + +`hd_client.py` (the OT engine) and `hd_core.py` (folder discovery, note +creation, tag writing, reconciliation) live in `../hd_common/` — see +`../hd_common/README.md`. Both this package and `../hd-cli/` import them +from there; there's only one copy. + +## Tests + +No network or real server needed — they spin up fake HedgeDoc servers +locally. The pty-driven ones need a built `joe`: + + JOE_BIN=/path/to/joe-4.8/joe/joe python3 e2e_test.py # BOF/EOF edits + ACK_DELAY=0.15 JOE_BIN=... python3 e2e_test.py # ...under latency + python3 ai_replace_test.py # AI block replace + JOE_BIN=... python3 cursor_after_ai_test.py # cursor after AI answer + JOE_BIN=... python3 test_hd_joe_create.py # hd-joe <name> create/open + JOE_BIN=... python3 test_hd_cache_refresh.py # cache updates after editing + JOE_BIN=... python3 test_hd_cache_live_refresh.py # ...and while still open + python3 test_hd_create.py # discovery/create logic + python3 test_joe_wrapper.py # joe-vs-hd-joe routing logic + JOE_BIN=... python3 test_joe_wrapper_exec.py # wrapper really execs real joe + JOE_BIN=... python3 test_joe_wrapper_hdjoe_exec.py # ...and really execs hd-joe + python3 test_disconnect_hook.py # connection-state hook fires correctly + python3 test_shadow_text_sync.py # _shadow_text stays in sync even on error + JOE_BIN=... HD_DRAIN_TIMEOUT=2.0 python3 test_offline_handling.py # offline: no cache poisoning, recovery file + JOE_BIN=... python3 test_real_disconnect_pty.py # real disconnect, JOE survives the M command + +`fake_hedgedoc.py` is a standalone fake server for poking at things by hand. + +**These fake servers have been wrong three times.** Each time, real HedgeDoc +did something the mock didn't: acked instantly (hid a rejected-operation +bug), had no DB-flush lag (hid a stale-content bug), never broadcast to +other clients (hid that whole category). They were patched after reality +disagreed, not before. Treat a green test suite as necessary, not +sufficient — and if you add coverage, make the fake stricter rather than +more convenient. diff --git a/hd-joe/ai_replace_test.py b/hd-joe/ai_replace_test.py new file mode 100644 index 0000000..91fe918 --- /dev/null +++ b/hd-joe/ai_replace_test.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Reproduces the 'AI answer replaced with stale placeholder' bug: +HedgeDoc's /download route reads DB-backed content that lags the live +realtime document by up to ~1s. A client that reacts to a large remote +delete by fetching /download instead of just applying the operation can +apply a completely correct-looking BUT STALE snapshot, and never correct +itself since it already advanced past that revision. + +No JOE/pty involved -- this bug lives entirely in hd_client.py. +""" +import importlib +import sys +import threading +import time + +import socketio + +sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common")) +from e2e_test import FakeServer, free_port # noqa: E402 + + +def build_scenario(): + prefix = "# Header\n\n" + block = ( + "<!--Agent\n" + "User: Funkar det med AI?\n" + "Agent: Ja, det funkar! Jag kan lasa innehallet i ditt dokument och svara pa fragor baserat pa det.\n" + "User: Fasen vad bra\n" + "Agent: \U0001f9e0 Tanker...\n" + "-->" + ) + new_block = ( + "<!--Agent\n" + "User: Funkar det med AI?\n" + "Agent: Ja, det funkar! Jag kan lasa innehallet i ditt dokument och svara pa fragor baserat pa det.\n" + "User: Fasen vad bra\n" + "Agent: Visst ar det! Jag ser allt fran rubriken till din kommentar.\n" + "->\n" + "-->" + ) + suffix = "\n(end)" + assert len(block) > 100, "test block must exceed the old >100-char large_delete threshold" + return prefix, block, new_block, suffix + + +def run(client_module_path): + # Force a clean import of whichever hd_client.py variant is on disk right now. + if "hd_client" in sys.modules: + del sys.modules["hd_client"] + hd_client = importlib.import_module("hd_client") + + prefix, block, new_block, suffix = build_scenario() + initial_text = prefix + block + suffix + port = free_port() + server = FakeServer(initial_text, port, db_flush_interval=1.0) + server.start() + time.sleep(0.2) + + events = [] + client = hd_client.HedgeDocClient( + f"http://127.0.0.1:{port}", "test-note", verbose=False, + on_remote_operation=lambda doc: events.append(doc.text), + ) + client.connect() + doc = client.wait_ready() + assert doc.text == initial_text + + # Simulate the AI's own socket sending the block replacement, almost + # immediately -- well inside the server's 1s DB-flush window. + ai = socketio.Client() + ai.connect(f"http://127.0.0.1:{port}/?noteId=test-note", socketio_path="socket.io", + transports=["websocket", "polling"]) + time.sleep(0.1) + op = [ + hd_client.utf16_len(prefix), + -hd_client.utf16_len(block), + new_block, + hd_client.utf16_len(suffix), + ] + ai.emit("operation", (0, op, {"ranges": []})) + time.sleep(0.4) # well before the 1.0s DB flush -- this is the race window + + final_text = client.document.text + client.close() + ai.disconnect() + server.stop() + return final_text, new_block, initial_text + + +def main(): + print("=" * 70) + print("Testing hd_client.py as currently on disk") + print("=" * 70) + final_text, new_block, initial_text = run("hd_client") + expected = initial_text.replace( + initial_text[initial_text.index("<!--Agent"):initial_text.index("-->") + 3], + new_block, + ) + print("Got final client text ending:\n", repr(final_text[-160:])) + print() + print("Expected ending:\n", repr(expected[-160:])) + ok = final_text == expected + print() + print("PASS" if ok else "FAIL", "-- AI answer applied correctly, not stuck on placeholder") + if not ok: + if "Tanker" in final_text: + print("--> Stuck showing the 'Tanker...' placeholder: this IS the reported bug.") + sys.exit(0 if ok else 1) + + +if __name__ == "__main__": + main() diff --git a/hd-joe/cursor_after_ai_test.py b/hd-joe/cursor_after_ai_test.py new file mode 100644 index 0000000..4ae2d40 --- /dev/null +++ b/hd-joe/cursor_after_ai_test.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""Verifies the cursor-after-AI-update fix through the REAL pipeline: patched +JOE under a pty + hd_joe_agent.py + fake server with a second ("AI") client. + +Can't inspect JOE's on-screen cursor position directly, so the test proves +it indirectly and unambiguously: after the AI's block-replace arrives, type +a marker string into the (still-running) JOE session with no further +navigation keys. If the cursor followed the fix, that marker lands right +after "-> " in the final document. If it's still stuck at BOF (the bug), +the marker lands at the very start instead. +""" +import os +import socket as socketmod +import sys +import threading +import time + +import pexpect +import socketio +from werkzeug.serving import make_server + +import sys as _sys +from pathlib import Path as _Path +_sys.path.insert(0, str(_Path(__file__).resolve().parent.parent / "hd_common")) + +from hd_client import apply_operation + +JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/build/joe-4.8/joe/joe") +AGENT = os.path.join(os.path.dirname(__file__), "hd_joe_agent.py") + + +def apply_operation_strict(text, op): + for c in op: + if isinstance(c, bool): + raise ValueError(f"unknown operation: {c!r}") + if isinstance(c, int) and c == 0: + raise ValueError(f"unknown operation: {c!r}") + return apply_operation(text, op) + + +class FakeServer: + def __init__(self, initial_text, port): + self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") + self.text = initial_text + self.revision = 0 + self.lock = threading.Lock() + + @self.sio.event + def connect(sid, environ, auth): + with self.lock: + self.sio.emit("doc", {"str": self.text, "revision": self.revision, "clients": []}, to=sid) + + @self.sio.on("operation") + def on_operation(sid, base_revision, operation, selection): + with self.lock: + if base_revision != self.revision: + return + try: + self.text = apply_operation_strict(self.text, operation) + except Exception as exc: + print("[fake server] rejected op:", exc, operation) + return + self.revision += 1 + self.sio.emit("ack", self.revision, to=sid) + self.sio.emit("operation", (sid, self.revision, operation, selection, None), skip_sid=sid) + + self.app = socketio.WSGIApp(self.sio) + self.srv = make_server("127.0.0.1", port, self.app, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + + def stop(self): + self.srv.shutdown() + + +def free_port(): + s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return port + + +def main(): + block = ( + "<!--Agent\n" + "User: Funkar det med AI?\n" + "Agent: Ja, det funkar! Jag kan lasa innehallet i ditt dokument och svara pa fragor baserat pa det.\n" + "User: Fasen vad bra\n" + "Agent: \U0001f9e0 Tanker...\n" + "-->" + ) + new_block = ( + "<!--Agent\n" + "User: Funkar det med AI?\n" + "Agent: Ja, det funkar! Jag kan lasa innehallet i ditt dokument och svara pa fragor baserat pa det.\n" + "User: Fasen vad bra\n" + "Agent: Visst ar det! Jag ser allt fran rubriken till din kommentar.\n" + "->\n" + "-->" + ) + initial_text = "# Header\n\n" + block + "\n(some other text below)" + assert len(block) > 100 + + port = free_port() + server = FakeServer(initial_text, port) + server.start() + time.sleep(0.2) + + sock_path = "/tmp/hd-joe-cursor-test.sock" + log_path = "/tmp/hd-joe-cursor-test.log" + for p in (sock_path, log_path): + try: + os.remove(p) + except OSError: + pass + + cmd = ( + f"python3 {AGENT} http://127.0.0.1:{port} test-note " + f"--joe {JOE_BIN} --socket {sock_path} --log {log_path} --debug" + ) + child = pexpect.spawn(cmd, cwd=os.path.dirname(__file__), env={**os.environ, "TERM": "xterm"}, + dimensions=(24, 80), timeout=10) + time.sleep(1.0) + + # Simulate the AI's own connection replacing the whole block. + import hd_client + prefix = "# Header\n\n" + suffix = "\n(some other text below)" + op = [ + hd_client.utf16_len(prefix), + -hd_client.utf16_len(block), + new_block, + hd_client.utf16_len(suffix), + ] + ai = socketio.Client() + ai.connect(f"http://127.0.0.1:{port}/?noteId=test-note", socketio_path="socket.io", + transports=["websocket", "polling"]) + time.sleep(0.2) + ai.emit("operation", (0, op, {"ranges": []})) + time.sleep(0.8) # let the agent apply it and (if fixed) reposition the cursor + + # No navigation keys at all -- type only. If the cursor followed the fix, + # this lands right after "-> ". If it's stuck at BOF, it lands at the + # very start of the document instead. + marker = "MARKERTEXT" + child.send(marker) + time.sleep(0.6) + + child.send("\x0bx") + time.sleep(0.5) + child.send("\r") + try: + child.wait() + except pexpect.TIMEOUT: + pass + if child.isalive(): + child.terminate(force=True) + time.sleep(0.3) + + ai.disconnect() + final_text = server.text + server.stop() + + print("Final server text:") + print(repr(final_text)) + print() + + expected_pos_text = "->\n" + marker # right after the prompt marker + newline... check both forms + landed_after_prompt = (marker in final_text) and ( + final_text.find(marker) > final_text.find("Visst ar det") + ) and not final_text.startswith(marker) + landed_at_bof = final_text.startswith(marker) + + print("Marker landed at BOF (the bug):", landed_at_bof) + print("Marker landed after the AI's answer (fixed):", landed_after_prompt) + + if os.path.exists(log_path): + print("\n--- agent log tail ---") + print(open(log_path, encoding="utf-8", errors="replace").read()[-1500:]) + + sys.exit(0 if landed_after_prompt and not landed_at_bof else 1) + + +if __name__ == "__main__": + main() diff --git a/hd-joe/e2e_test.py b/hd-joe/e2e_test.py new file mode 100644 index 0000000..92c5d46 --- /dev/null +++ b/hd-joe/e2e_test.py @@ -0,0 +1,265 @@ +#!/usr/bin/env python3 +"""End-to-end regression test for the BOF/EOF local-insert bugs. + +Runs the real patched JOE binary under a pty, driven by hd_joe_agent.py, +against an in-process fake HedgeDoc server. No mocking of the OT engine or +the C code: this is the actual compiled binary and the actual Python agent, +exercised through real keystrokes. +""" +import json +import os +import socket as socketmod +import sys +import threading +import time + +import pexpect +import socketio +from werkzeug.serving import make_server + +import sys as _sys +from pathlib import Path as _Path +_sys.path.insert(0, str(_Path(__file__).resolve().parent.parent / "hd_common")) + +from hd_client import apply_operation + + +def apply_operation_strict(text, op): + """Mirror ot.js's TextOperation.fromJSON validation exactly: a literal 0 + of any kind anywhere in the op is invalid ("unknown operation: 0") per + isRetain/isInsert/isDelete in the real server's text-operation.js. This is + what makes the fake server catch what hd_client.py's own (lenient) + apply_operation does not -- it's the actual root cause of the BOF/EOF + bugs: insert_operation/replace_operation used to always emit a trailing + or leading 0 retain at the document boundaries. + """ + for c in op: + if isinstance(c, bool): + raise ValueError(f"unknown operation: {c!r}") + if isinstance(c, int) and c == 0: + raise ValueError(f"unknown operation: {c!r}") + return apply_operation(text, op) + +JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/build/joe-4.8/joe/joe") +AGENT = os.path.join(os.path.dirname(__file__), "hd_joe_agent.py") + + +class FakeServer: + """One fake-HedgeDoc instance on its own port, run in a background thread. + + Also simulates HedgeDoc's real persistence model: the live OT document + (self.text) and the DB-backed content served by /download (self.db_text) + are DELIBERATELY not the same thing. Real HedgeDoc only flushes live -> + DB once a second, and only if dirty (lib/realtime.js). db_flush_interval + reproduces that lag so tests can catch code that wrongly treats + /download as authoritative-and-current. + """ + + def __init__(self, initial_text, port, ack_delay=0.0, db_flush_interval=1.0): + self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") + self.app = socketio.WSGIApp(self.sio) + self.text = initial_text + self.revision = 0 + self.operations = [] + self.rejections = [] + self.lock = threading.Lock() + self.port = port + self.ack_delay = ack_delay + self.db_text = initial_text + self._dirty = False + self._stop_flush = threading.Event() + + def flush_loop(): + while not self._stop_flush.wait(db_flush_interval): + with self.lock: + if self._dirty: + self.db_text = self.text + self._dirty = False + + self.flush_thread = threading.Thread(target=flush_loop, daemon=True) + + @self.sio.event + def connect(sid, environ, auth): + with self.lock: + self.sio.emit("doc", {"str": self.text, "revision": self.revision, "clients": []}, to=sid) + + @self.sio.on("operation") + def on_operation(sid, base_revision, operation, selection): + if self.ack_delay: + time.sleep(self.ack_delay) # simulate real network/server latency + with self.lock: + self.operations.append((base_revision, operation)) + if base_revision != self.revision: + self.rejections.append((base_revision, operation, "bad base_revision")) + return + try: + self.text = apply_operation_strict(self.text, operation) + self._dirty = True + except Exception as exc: + self.rejections.append((base_revision, operation, repr(exc))) + return + self.revision += 1 + self.sio.emit("ack", self.revision, to=sid) + # Real HedgeDoc broadcasts to every OTHER connected client in + # the note's room (EditorSocketIOServer.onOperation: + # socket.broadcast.in(this.docId).emit('operation', ...)). + # Without this, a second connected client (e.g. an AI + # integration, or another browser tab) never sees the edit -- + # which single-client tests can never catch. + self.sio.emit( + "operation", + (sid, self.revision, operation, selection, None), + skip_sid=sid, + ) + + socketio_app = self.app + + def wsgi_app(environ, start_response): + path = environ.get("PATH_INFO", "") + if path.endswith("/download"): + with self.lock: + body = self.db_text.encode("utf-8") + start_response("200 OK", [ + ("Content-Type", "text/markdown; charset=UTF-8"), + ("Content-Length", str(len(body))), + ]) + return [body] + return socketio_app(environ, start_response) + + self.app = wsgi_app + self.srv = make_server("127.0.0.1", port, self.app, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + self.flush_thread.start() + + def stop(self): + self._stop_flush.set() + self.srv.shutdown() + + +def free_port(): + s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return port + + +def run_case(name, initial_text, keys, settle=0.6, ack_delay=0.0): + port = free_port() + server = FakeServer(initial_text, port, ack_delay=ack_delay) + server.start() + time.sleep(0.2) + + log_path = f"/tmp/hd-joe-{name}.log" + sock_path = f"/tmp/hd-joe-{name}.sock" + for p in (log_path, sock_path): + try: + os.remove(p) + except OSError: + pass + + cmd = ( + f"python3 {AGENT} http://127.0.0.1:{port} test-note " + f"--joe {JOE_BIN} --socket {sock_path} --log {log_path} --debug" + ) + child = pexpect.spawn(cmd, cwd=os.path.dirname(__file__), env={**os.environ, "TERM": "xterm"}, + dimensions=(24, 80), timeout=10) + time.sleep(1.0) # let JOE start, agent connect, initial doc load + + for item in keys: + if isinstance(item, float): + time.sleep(item) + elif isinstance(item, tuple) and item[0] == "burst": + # Send a whole string in one write with no inter-key settle, + # simulating continuous fast typing rather than one keystroke + # at a time. + child.send(item[1]) + else: + child.send(item) + time.sleep(0.15) + + time.sleep(settle) + + # Quit JOE: Ctrl-K X (save+exit). Send twice in case of an intervening prompt. + child.send("\x0bx") + time.sleep(0.5) + child.send("\r") + # Give the agent time to drain its pending queue and exit on its own + # (it now blocks on this deliberately) before falling back to a kill. + try: + child.wait() + except pexpect.TIMEOUT: + pass + if child.isalive(): + child.terminate(force=True) + + time.sleep(0.3) + server.stop() + + log_tail = "" + if os.path.exists(log_path): + with open(log_path, encoding="utf-8", errors="replace") as f: + log_tail = f.read()[-4000:] + + return { + "server_text": server.text, + "server_revision": server.revision, + "operations": server.operations, + "rejections": server.rejections, + "log_tail": log_tail, + } + + +def main(): + print("=" * 70) + print("TEST A: insert newline at BOF (top-of-file), expect first char kept") + print("=" * 70) + a = run_case( + "bof", + initial_text="helloworld", + keys=["\r"], # cursor starts at BOF on a fresh file; press Enter + ) + print("server text repr:", repr(a["server_text"])) + print("server revision:", a["server_revision"]) + print("operations sent:", a["operations"]) + print("rejections:", a["rejections"]) + expected = "\nhelloworld" + ok_a = a["server_text"] == expected + print("EXPECTED:", repr(expected)) + print("PASS" if ok_a else "FAIL", "- BOF test") + print() + + print("=" * 70) + print("TEST B: type a character at EOF, expect it to reach the server") + print("=" * 70) + b = run_case( + "eof", + initial_text="helloworld", + keys=["\x0bv", 0.3, ("burst", "continued typing")], # Ctrl-K V = goto EOF, then type continuously + settle=1.5, + ack_delay=float(os.environ.get("ACK_DELAY", "0")), + ) + print("server text repr:", repr(b["server_text"])) + print("server revision:", b["server_revision"]) + print("operations sent:", b["operations"]) + print("rejections:", b["rejections"]) + expected_b = "helloworldcontinued typing" + ok_b = b["server_text"] == expected_b + print("EXPECTED:", repr(expected_b)) + print("PASS" if ok_b else "FAIL", "- EOF test") + + if not ok_a: + print("\n--- bof agent log tail ---") + print(a["log_tail"]) + if not ok_b: + print("\n--- eof agent log tail ---") + print(b["log_tail"]) + + sys.exit(0 if (ok_a and ok_b) else 1) + + +if __name__ == "__main__": + main() diff --git a/hd-joe/fake_hedgedoc.py b/hd-joe/fake_hedgedoc.py new file mode 100644 index 0000000..f4ef0ec --- /dev/null +++ b/hd-joe/fake_hedgedoc.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Minimal fake HedgeDoc 1.x realtime server: just enough Socket.IO wire +protocol (doc / operation / ack) to drive hd_client.py end-to-end without a +real HedgeDoc instance. Single-client, no peer broadcast -- sufficient to +reproduce and verify the BOF/EOF local-edit bugs, which don't need +concurrency to manifest. +""" +import argparse +import json +import sys +import threading + +import socketio +from werkzeug.serving import make_server + +import sys as _sys +from pathlib import Path as _Path +_sys.path.insert(0, str(_Path(__file__).resolve().parent.parent / "hd_common")) + +from hd_client import apply_operation, utf16_len + + +def apply_operation_strict(text, op): + """Mirror ot.js's TextOperation.fromJSON: a literal 0 anywhere in the op + is invalid and must raise -- matches isRetain/isInsert/isDelete in the + real server's text-operation.js.""" + for c in op: + if isinstance(c, bool): + raise ValueError(f"unknown operation: {c!r}") + if isinstance(c, int) and c == 0: + raise ValueError(f"unknown operation: {c!r}") + return apply_operation(text, op) + +sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") +app = socketio.WSGIApp(sio) + +state = {"text": "", "revision": 0} +state_lock = threading.Lock() +operations_received = [] # for test assertions + + +@sio.event +def connect(sid, environ, auth): + with state_lock: + sio.emit("doc", {"str": state["text"], "revision": state["revision"], "clients": []}, to=sid) + + +@sio.on("operation") +def on_operation(sid, base_revision, operation, selection): + with state_lock: + operations_received.append((base_revision, operation, selection)) + if base_revision != state["revision"]: + # In this single-client test harness this should never happen. + sys.stderr.write( + f"[fake_hedgedoc] REJECTED operation: base_revision={base_revision} " + f"!= server revision={state['revision']} op={operation!r}\n" + ) + return + try: + state["text"] = apply_operation_strict(state["text"], operation) + except Exception as exc: + sys.stderr.write(f"[fake_hedgedoc] operation raised: {exc!r} op={operation!r}\n") + return + state["revision"] += 1 + sio.emit("ack", state["revision"], to=sid) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=int, default=5999) + ap.add_argument("--text", default="") + ap.add_argument("--state-file", help="write final {text, revision} as JSON here on SIGTERM/exit") + args = ap.parse_args() + state["text"] = args.text + + srv = make_server("127.0.0.1", args.port, app) + try: + srv.serve_forever() + finally: + if args.state_file: + with state_lock: + with open(args.state_file, "w", encoding="utf-8") as f: + json.dump({"text": state["text"], "revision": state["revision"], + "operations": operations_received}, f) + + +if __name__ == "__main__": + main() diff --git a/hd-joe/hd-joe b/hd-joe/hd-joe new file mode 100755 index 0000000..4cf6bb6 --- /dev/null +++ b/hd-joe/hd-joe @@ -0,0 +1,3 @@ +#!/bin/sh +SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" +exec python3 "$SCRIPT_DIR/hd_joe_agent.py" "$@" diff --git a/hd-joe/hd_joe_agent.py b/hd-joe/hd_joe_agent.py new file mode 100644 index 0000000..e39b5a1 --- /dev/null +++ b/hd-joe/hd_joe_agent.py @@ -0,0 +1,542 @@ +#!/usr/bin/env python3 +"""HedgeDoc 1.x <-> patched JOE 4.8 agent 0.7.17. + +The agent owns the Socket.IO/OT connection. Patched JOE owns the real editor +buffer. They communicate over a private Unix stream socket. + +Usage: + hd-joe <url> <note-id> [--cookie ...] ... explicit, works anywhere + hd-joe <name> ... inside an hd-managed folder: + opens NAME if a symlink for + it already exists in the + current tag directory, + otherwise creates a new note + tagged with that directory's + name (see hd_core.py's + find_hd_root/tag_from_cwd/ + resolve_or_create_note) + +JOE -> agent: + I <byte-offset> <hex-bytes> + D <byte-offset> <byte-count> + +agent -> JOE: + I <byte-offset> <hex-bytes> + D <byte-offset> <byte-count> + R <hex-utf8> replace the entire JOE buffer atomically + C <byte-offset> move the cursor (used after an AI/agent block + rewrite, to land back at the next input prompt) +""" +from __future__ import annotations +import argparse, json, logging, os, socket, subprocess, sys, tempfile, threading, time +from pathlib import Path +from typing import Optional + +# hd_core.py/hd_client.py live in ../hd_common, shared verbatim with hd-cli +# (see hd_common/README.md) -- add it to sys.path before importing either, +# regardless of where this script is actually invoked from. +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common")) + +import hd_core +import joe_wrapper +from hd_client import HedgeDocClient, HedgeDocDocument, Operation + +logger = logging.getLogger("picocalc.hd") + + +def byte_to_char(s: str, byte_pos: int) -> int: + if byte_pos < 0: + raise ValueError("negative byte position") + raw = s.encode("utf-8") + if byte_pos > len(raw): + raise ValueError("byte position outside document") + try: + return len(raw[:byte_pos].decode("utf-8")) + except UnicodeDecodeError as e: + raise ValueError("JOE position is not on a UTF-8 character boundary") from e + + +def byte_range_to_text(s: str, pos: int, length: int) -> tuple[int, int]: + raw = s.encode("utf-8") + if pos < 0 or length < 0 or pos + length > len(raw): + raise ValueError("byte range outside document") + try: + a = len(raw[:pos].decode("utf-8")) + b = len(raw[:pos+length].decode("utf-8")) + except UnicodeDecodeError as e: + raise ValueError("JOE range is not UTF-8 aligned") from e + return a, b + + +def op_to_joe_commands(old_text: str, op: Operation): + """Convert a HedgeDoc UTF-16 OT operation into JOE byte edits.""" + source_u = 0 + byte_pos = 0 + doc_u = len(old_text.encode("utf-16-le")) // 2 + out = [] + for c in op: + if isinstance(c, bool): + raise ValueError("invalid OT bool") + if isinstance(c, int): + if c >= 0: + end_u = source_u + c + if end_u > doc_u: + raise ValueError("retain exceeds document") + from hd_client import utf16_to_char_index + a = utf16_to_char_index(old_text, source_u) + b = utf16_to_char_index(old_text, end_u) + segment = old_text[a:b] + byte_pos += len(segment.encode("utf-8")) + source_u = end_u + else: + n = -c + end_u = source_u + n + if end_u > doc_u: + raise ValueError("delete exceeds document") + from hd_client import utf16_to_char_index + a = utf16_to_char_index(old_text, source_u) + b = utf16_to_char_index(old_text, end_u) + deleted = old_text[a:b] + out.append(("D", byte_pos, len(deleted.encode("utf-8")))) + source_u = end_u + continue + if isinstance(c, str): + raw = c.encode("utf-8") + if raw: + out.append(("I", byte_pos, raw)) + byte_pos += len(raw) + continue + raise ValueError(f"invalid OT component {c!r}") + if source_u != doc_u: + raise ValueError("OT did not consume document") + return out + + +class Agent: + def __init__(self, client: HedgeDocClient, sock_path: Path, buffer_path: Path, + hd_root: Optional[Path] = None, note_id: Optional[str] = None): + self.client = client + self.sock_path = sock_path + self.buffer_path = buffer_path + self.server: Optional[socket.socket] = None + self.conn: Optional[socket.socket] = None + self.stop = threading.Event() + self.lock = threading.RLock() + self.rx = b"" + self.hd_root = hd_root + self.note_id = note_id + self._last_cache_write = 0.0 + client.on_remote_operation_detail = self.remote_operation + client.on_connection_state_changed = self.on_connection_state_changed + + def send_cmd(self, kind, pos, payload): + c = self.conn + if not c: + return + if kind == "I": + line = f"I {pos} {payload.hex()}\n".encode() + else: + line = f"D {pos} {payload}\n".encode() + try: + with self.lock: + c.sendall(line) + except OSError: + self.stop.set() + + def replace_buffer(self, text: str): + """Ask JOE to replace its entire buffer in one atomic editor-side + operation. No longer called from remote_operation() (see below -- + it was the cause of the cursor-jumps-to-BOF bug), kept as a + primitive for a future hard-resync path.""" + c = self.conn + if not c: + return + raw = text.encode("utf-8") + line = b"R " + raw.hex().encode("ascii") + b"\n" + try: + with self.lock: + c.sendall(line) + except OSError: + self.stop.set() + + def send_cursor(self, byte_pos: int): + c = self.conn + if not c: + return + line = f"C {byte_pos}\n".encode() + try: + with self.lock: + c.sendall(line) + except OSError: + self.stop.set() + + def send_message(self, text: str): + c = self.conn + if not c: + return + line = b"M " + text.encode("utf-8").hex().encode("ascii") + b"\n" + try: + with self.lock: + c.sendall(line) + except OSError: + self.stop.set() + + def on_connection_state_changed(self, connected: bool): + # Called from hd_client's Socket.IO thread, not JOE's socket thread + # -- send_message() takes self.lock itself, same as every other + # command sent to JOE, so this is safe to call from either. + if connected: + self.send_message("Back online -- syncing resumed.") + else: + self.send_message("OFFLINE -- edits are NOT being saved to the server.") + + # Marker the HedgeDoc AI mod uses for its input prompt (see hd-joe README / + # the user's own description: "man skriver vid -> och tva enter skickar"). + AGENT_PROMPT_MARKER = "\n->" + + def _agent_prompt_byte_pos(self, text: str): + """Byte offset right after the next-message prompt marker, if present.""" + idx = text.rfind(self.AGENT_PROMPT_MARKER) + if idx == -1: + return None + char_pos = idx + len(self.AGENT_PROMPT_MARKER) + if text[char_pos:char_pos + 1] == " ": + char_pos += 1 + return len(text[:char_pos].encode("utf-8")) + + def remote_operation(self, doc: HedgeDocDocument, op: Operation): + # The client has already transformed/applied op to produce doc.text. + with self.lock: + old = getattr(self, "_shadow_text", None) + if old is None: + self._shadow_text = doc.text + if self.conn is None: + self.buffer_path.write_text(doc.text, encoding="utf-8") + return + # A delete this large is very likely a HedgeDoc AI/agent + # integration rewriting its whole block (placeholder -> answer). + # This only decides where we put the cursor afterward -- the + # buffer update itself always goes through the incremental path + # below, never a whole-buffer replace, which is what used to + # send the cursor to BOF: bdel() on the entire buffer collapses + # every pointer in it -- including the cursor -- to byte 0, with + # no way back. Incremental D+I commands only touch the pointers + # inside the actually-changed range. + large_delete = any(isinstance(c, int) and c < -100 for c in op) + try: + cmds = op_to_joe_commands(old, op) + for kind, pos, data in cmds: + self.send_cmd(kind, pos, data) + self._shadow_text = doc.text + except Exception: + logger.exception("Cannot translate remote OT for JOE") + return + if large_delete: + cursor_pos = self._agent_prompt_byte_pos(doc.text) + if cursor_pos is not None: + self.send_cursor(cursor_pos) + + # Keep the local mirror reasonably fresh while a session is open, + # not just at quit -- so someone else's edits (via webUI, say) + # show up if you `cat` the symlink mid-session, not only after + # you close JOE. Throttled to at most once/second: each write + # takes the same interprocess lock `hdc sync` uses and rewrites + # state.json, which isn't free, and a fast remote typist would + # otherwise trigger it on every keystroke. The quit-time + # update_note_cache() call already guarantees a final, fully + # up-to-date write regardless of this throttle. + if self.hd_root and self.note_id: + now = time.monotonic() + if now - self._last_cache_write >= 1.0: + self._last_cache_write = now + try: + hd_core.update_note_cache(self.hd_root, self.note_id, doc.text) + except Exception: + logger.exception("Could not refresh local cache for %s", self.note_id) + + def handle_local(self, line: str): + parts = line.split(" ", 2) + if not parts or parts[0] not in ("I", "D"): + return + try: + kind = parts[0] + pos = int(parts[1]) + with self.lock: + text = self.client.document.text + if kind == "I": + raw = bytes.fromhex(parts[2].strip()) + ins = raw.decode("utf-8") + cp = byte_to_char(text, pos) + self.client.insert(cp, ins) + else: + n = int(parts[2]) + a, b = byte_range_to_text(text, pos, n) + self.client.send_operation(self._delete_op(text, a, b)) + except Exception: + # Covers the offline case among others: send_operation() already + # updated self.client.document.text optimistically (that's why + # local editing keeps working while disconnected) *before* + # _emit_pending()'s socket.emit() raises BadNamespaceError -- so + # this can fire with the local edit already applied in memory. + logger.exception("Local JOE edit rejected") + finally: + # Must run whether or not the block above raised: document.text + # may already have moved (see above), and if _shadow_text isn't + # kept in sync with it, the NEXT remote operation gets translated + # into JOE IPC commands against a stale baseline -- a corruption + # risk, not just a lost-edit one. + self._shadow_text = self.client.document.text + + @staticmethod + def _delete_op(text: str, a: int, b: int): + # a, b are Python character indices (from byte_range_to_text); every + # other op in this file is built in UTF-16 code units via utf16_len. + # Real HedgeDoc (ot.js) rejects a literal 0 anywhere in the op array + # ("unknown operation: 0") -- zero-length retains must be omitted, + # not sent as 0, exactly like insert_operation/replace_operation. + from hd_client import utf16_len + a_u = utf16_len(text[:a]) + b_u = utf16_len(text[:b]) + tail_u = utf16_len(text) - b_u + op = [] + if a_u: + op.append(a_u) + op.append(-(b_u - a_u)) + if tail_u: + op.append(tail_u) + return op + + def serve(self): + self.sock_path.unlink(missing_ok=True) + self.server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.server.bind(str(self.sock_path)) + self.server.listen(1) + self.server.settimeout(0.5) + try: + while not self.stop.is_set(): + try: + c,_ = self.server.accept() + except socket.timeout: + continue + self.conn = c + self._shadow_text = self.client.document.text + c.settimeout(0.5) + buf = b"" + while not self.stop.is_set(): + try: + data = c.recv(65536) + except socket.timeout: + continue + if not data: + break + buf += data + while b"\n" in buf: + raw, buf = buf.split(b"\n",1) + if raw: + self.handle_local(raw.decode("ascii")) + try: c.close() + except OSError: pass + self.conn = None + break + finally: + self.stop.set() + if self.server: + self.server.close() + self.sock_path.unlink(missing_ok=True) + + +def drain_pending(client: HedgeDocClient, timeout: float = 15.0, poll: float = 0.05) -> bool: + """Block until every locally queued operation has been ACKed, or timeout. + + JOE exiting only ends the editor process; the agent's Socket.IO + connection to HedgeDoc keeps running in its own thread and will still + receive ACKs for anything still in the local pending queue. The only + thing that was silently discarding typed-but-unacked text was closing + that connection immediately after JOE exited, instead of waiting for + the queue to actually drain first. + """ + import time + deadline = time.monotonic() + timeout + last_count = client.pending_count + if last_count: + logger.info("Draining %d unsent local operation(s) before exit...", last_count) + while client.pending_count > 0: + if time.monotonic() >= deadline: + logger.error( + "Exiting with %d local operation(s) still unacknowledged after " + "%.1fs drain timeout -- these were NOT saved to the server.", + client.pending_count, timeout, + ) + return False + time.sleep(poll) + if last_count: + logger.info("Drain complete: all local operations acknowledged.") + return True + + +def main(): + ap=argparse.ArgumentParser( + description="Run patched JOE as a HedgeDoc editor", + epilog="Either give an explicit '<url> <note-id>', or a single NAME to " + "open-or-create inside an hd-managed folder (see hd_core.find_hd_root) " + "-- run from inside ~/notes/<tag>/ for that second form.", + ) + ap.add_argument("target", nargs="+", metavar="URL NOTE_ID | NAME") + ap.add_argument("--cookie") + # Default points at the real compiled binary directly, not bare "joe" + # resolved via PATH: once joe_wrapper.py is installed AT the "joe" name + # (see install.sh), a bare "joe" would loop back into that wrapper. + # This subprocess call is always meant to reach the real editor, so it + # names it explicitly rather than relying on the wrapper's own (correct + # but incidental) handling of "an existing plain file, not an hd note" + # to avoid recursing. + _default_joe = joe_wrapper.DEFAULT_REAL_JOE if Path(joe_wrapper.DEFAULT_REAL_JOE).exists() else "joe" + ap.add_argument("--joe", default=_default_joe) + ap.add_argument("--socket") + ap.add_argument("--buffer", help="persistent working file") + ap.add_argument("--quiet", action="store_true", help="disable normal log messages") + ap.add_argument("--log", help="log file (default: ~/.local/state/picocalc/hd-joe.log)") + ap.add_argument("--debug", action="store_true", help="verbose debug logging") + args=ap.parse_args() + if len(args.target) not in (1, 2): + ap.error("expected either 'URL NOTE_ID' or a single NAME") + + log_path = Path(args.log).expanduser() if args.log else Path("~/.local/state/picocalc/hd-joe.log").expanduser() + if not args.quiet: + log_path.parent.mkdir(parents=True, exist_ok=True) + handler = logging.FileHandler(log_path, encoding="utf-8") + handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s")) + logger.setLevel(logging.DEBUG if args.debug else logging.INFO) + logger.handlers.clear() + logger.addHandler(handler) + logger.propagate = False + else: + logger.handlers.clear() + logger.addHandler(logging.NullHandler()) + logger.setLevel(logging.CRITICAL) + + # Resolve what to actually connect to. Two explicit args always win and + # never need .hd/ at all (a server with no local login, or hd-joe used + # standalone outside any hd-managed folder). A single NAME requires an + # .hd/ directory somewhere above the current directory, git-style. + cwd = Path.cwd() + hd_root = hd_core.find_hd_root(cwd) + hd_dir = hd_root / ".hd" if hd_root else None + discovered_cookie = None + if hd_dir: + try: + discovered_cookie = hd_core.Cookies.load(hd_dir).header + except (FileNotFoundError, json.JSONDecodeError, KeyError): + discovered_cookie = None + + if len(args.target) == 2: + url, note_id = args.target + cookie = args.cookie or discovered_cookie # may legitimately be None -- unauthenticated notes exist + else: + name = args.target[0] + if hd_root is None: + print(f"'{name}' isn't 'URL NOTE_ID', and no .hd/ directory was found " + f"above {cwd} -- run 'hdc init' first, or pass both explicitly.", + file=sys.stderr) + return 1 + config = hd_core.Config.load(hd_dir) + cookie = args.cookie or discovered_cookie + if not cookie: + print(f"{hd_dir / 'cookies.json'} has no usable cookie -- re-run 'hdc init'.", + file=sys.stderr) + return 1 + + problems = hd_core.load_problems(hd_dir) + if problems: + print(f"{len(problems)} problem(s) from the last 'hdc sync':", file=sys.stderr) + for p in problems: + print(f" - {p}", file=sys.stderr) + print(file=sys.stderr) + + try: + note_id, created = hd_core.resolve_or_create_note(hd_root, cwd, name, config.url, cookie) + except ValueError as exc: + print(f"Refusing: {exc}", file=sys.stderr) + return 1 + url = config.url + if created: + print(f"Created new note '{name}' -- id {note_id}") + + client=HedgeDocClient(url,note_id,cookie=cookie,verbose=not args.quiet) + sock=Path(args.socket or f"/tmp/joe-hedgedoc-{os.getpid()}.sock") + persistent=Path(args.buffer).expanduser() if args.buffer else None + tmp=None + proc=None + agent=None + try: + client.connect() + doc=client.wait_ready() + if persistent: + persistent.parent.mkdir(parents=True,exist_ok=True) + persistent.write_text(doc.text,encoding="utf-8") + path=persistent + else: + fd,name_=tempfile.mkstemp(prefix=f"hedgedoc-{note_id}-",suffix=".md") + os.close(fd); tmp=Path(name_) + tmp.write_text(doc.text,encoding="utf-8"); path=tmp + + agent=Agent(client,sock,path,hd_root=hd_root,note_id=note_id) + th=threading.Thread(target=agent.serve,daemon=True) + th.start() + + env=os.environ.copy() + env["JOE_HEDGE_SOCKET"]=str(sock) + env["JOE_HEDGE_BUFFER"]=str(path) + proc=subprocess.Popen([args.joe,str(path)],env=env) + rc=proc.wait() + agent.stop.set() + fully_synced = drain_pending(client, timeout=float(os.environ.get("HD_DRAIN_TIMEOUT", "15.0"))) + if hd_root: + if fully_synced: + try: + hd_core.update_note_cache(hd_root, note_id, client.document.text) + except Exception: + logger.exception("Could not refresh local cache for %s", note_id) + else: + # Do NOT write client.document.text here: it's the locally + # optimistic buffer, but the server never acknowledged it + # (still offline, most likely). Writing it into the cache + # anyway, with a matching content_hash, would tell every + # future 'hdc sync' this note is already up to date -- the + # skip-fetch check (state.json's last_seen_time == /history's + # time) would then never re-fetch it, permanently hiding a + # real divergence from the server behind a false "in sync". + # Leaving the tracked cache untouched means the next + # successful sync still sees the truth -- but the user's + # actual keystrokes still shouldn't just vanish because of + # that, so they're saved to a separate, untracked recovery + # file instead. JOE's process has already exited by this + # point, so this is a plain terminal print, not something + # the user could miss inside JOE's own UI. + try: + recovery_path = hd_core.save_offline_recovery(hd_root, note_id, client.document.text) + recovery_msg = f"Your edits were saved to {recovery_path} instead." + except Exception: + logger.exception("Could not write offline recovery file for %s", note_id) + recovery_msg = "Additionally, saving an offline recovery copy also failed -- see the log." + print( + f"\nhd-joe: {client.pending_count} edit(s) to '{note_id}' were " + f"NOT saved to the server (connection issue?). {recovery_msg}", + file=sys.stderr, + ) + return rc + finally: + if proc and proc.poll() is None: + proc.terminate() + if agent: + agent.stop.set() + client.close() + try: sock.unlink(missing_ok=True) + except OSError: pass + if tmp: + try: tmp.unlink() + except FileNotFoundError: pass + + +if __name__=="__main__": + raise SystemExit(main()) diff --git a/hd-joe/joe_wrapper.py b/hd-joe/joe_wrapper.py new file mode 100755 index 0000000..4627885 --- /dev/null +++ b/hd-joe/joe_wrapper.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""joe wrapper: routes to hd-joe when the target is (or would be) an +hd-managed note, otherwise execs the real patched joe unmodified. + +Installed AT the 'joe' name by install.sh (see install_joe() there) -- +NOT meant to be run directly under its own name during development; see +decide() for the actual logic, which is what's unit-tested. + +Two decisions, both explicit choices Joakim made, not guesses: + 1. If the argument resolves into an EXISTING hd-managed note (anywhere + under some .hd/notes/), route to hd-joe -- regardless of cwd. This is + the safety half: it stops `joe` from silently editing a note's cache + file directly on disk, bypassing HedgeDoc entirely, just because you + happened to open it by path from outside ~/notes. + 2. Else, if cwd itself is inside an hd-managed folder, treat a single + bare name as `hd-joe <name>` -- creates the note if it doesn't exist + yet, exactly like running hd-joe directly would. +Anything else -- multiple files, flags, or cwd and argument both unrelated +to any hd-managed folder -- goes straight to the real, unmodified joe. +""" +from __future__ import annotations + +import os +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import Optional + +THIS_DIR = Path(__file__).resolve().parent +sys.path.insert(0, str(THIS_DIR.parent / "hd_common")) +import hd_core # noqa: E402 + +DEFAULT_REAL_JOE = str(THIS_DIR.parent / "joe-patch" / "build" / "joe-4.8" / "joe" / "joe") +HD_JOE_AGENT = str(THIS_DIR / "hd_joe_agent.py") + + +@dataclass +class Decision: + program: str # "real_joe" or "hd_joe" + args: list[str] # argv to pass (not including the program name itself) + + +def decide(argv: list[str], cwd: Path, real_joe_exists=None) -> Decision: + """Pure decision logic, no process launching -- so it's testable without + actually exec-ing anything. `real_joe_exists` is injectable for tests; + defaults to a real filesystem check. + """ + # Only try to be smart for "joe <one-thing>" with no flags. Multiple + # files, -flags, or no args at all: always real joe, unmodified -- + # anything else risks second-guessing a normal joe invocation. + positionals = [a for a in argv if not a.startswith("-")] + if len(argv) != 1 or len(positionals) != 1: + return Decision("real_joe", argv) + + arg = argv[0] + path = Path(arg) + if not path.is_absolute(): + # Resolved against the passed-in `cwd`, not whatever the OS thinks + # the real process cwd is -- makes this testable without actually + # chdir-ing the test process, and in production `cwd` is always + # Path.cwd() anyway, so behavior is identical there. + path = cwd / path + + # Case 1: the argument already resolves into an existing hd-managed + # note, wherever we happen to be standing right now. + if path.exists(): + resolved = path.resolve() + notes_dir = resolved.parent + hd_dir = notes_dir.parent + if notes_dir.name == hd_core.NOTES_DIRNAME and hd_dir.name == ".hd" and resolved.suffix == ".md": + hd_root = hd_dir.parent + note_id = resolved.stem + try: + config = hd_core.Config.load(hd_dir) + cookies = hd_core.Cookies.load(hd_dir) + except (FileNotFoundError, KeyError, ValueError): + # .hd/ exists but config/cookies are missing or unreadable -- + # don't fail the edit, just fall back to plain joe on the + # cache file rather than crash on something hd-joe needs. + return Decision("real_joe", argv) + return Decision("hd_joe", [config.url, note_id, "--cookie", cookies.header]) + # An existing file that ISN'T an hd-managed note: always real joe -- + # never silently create-or-open it as if the path were a note name. + return Decision("real_joe", argv) + + # Case 2: the argument doesn't exist as a file yet. Only treat it as a + # note name to create-or-open if we're standing inside an hd-managed + # folder -- otherwise this is just "make me a new file", plain joe's + # ordinary job. + hd_root = hd_core.find_hd_root(cwd) + if hd_root is not None: + return Decision("hd_joe", [arg]) + + return Decision("real_joe", argv) + + +def run(decision: Decision, real_joe_path: str = DEFAULT_REAL_JOE) -> None: + if decision.program == "real_joe": + os.execv(real_joe_path, [real_joe_path, *decision.args]) + else: + os.execv(sys.executable, [sys.executable, HD_JOE_AGENT, *decision.args]) + + +def main() -> None: + decision = decide(sys.argv[1:], Path.cwd()) + run(decision) + + +if __name__ == "__main__": + main() diff --git a/hd-joe/requirements.txt b/hd-joe/requirements.txt new file mode 100644 index 0000000..6d70805 --- /dev/null +++ b/hd-joe/requirements.txt @@ -0,0 +1,3 @@ +-r ../hd_common/requirements.txt +werkzeug>=3.0 # tests only, not needed to run hd-joe itself +pexpect>=4.9 # tests only (drives real JOE under a pty) diff --git a/hd-joe/test_disconnect_hook.py b/hd-joe/test_disconnect_hook.py new file mode 100644 index 0000000..dde26f3 --- /dev/null +++ b/hd-joe/test_disconnect_hook.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Direct test of HedgeDocClient.on_connection_state_changed -- the hook +Agent.on_connection_state_changed (hd_joe_agent.py) subscribes to, to show +the "OFFLINE"/"Back online" message in JOE. Tested against HedgeDocClient +directly rather than through a full pty+JOE session: a controlled +client.sio.disconnect() call is a reliable, immediate, genuine transport +disconnect -- no dependency on how fast a killed server gets noticed. +""" +import socket as socketmod +import sys +import threading +import time +from pathlib import Path + +import socketio +from werkzeug.serving import make_server + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common")) +from hd_client import HedgeDocClient + +PASS = [] +FAIL = [] + + +def check(name, cond, detail=""): + if cond: + PASS.append(name) + else: + FAIL.append((name, detail)) + print(f"FAIL: {name} {detail}") + + +class MinimalFakeServer: + def __init__(self, port): + self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") + + @self.sio.event + def connect(sid, environ, auth): + self.sio.emit("doc", {"str": "hello", "revision": 0, "clients": []}, to=sid) + + self.app = socketio.WSGIApp(self.sio) + self.srv = make_server("127.0.0.1", port, self.app, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + + def stop(self): + self.srv.shutdown() + + +def free_port(): + s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return port + + +def main(): + port = free_port() + server = MinimalFakeServer(port) + server.start() + time.sleep(0.2) + + states = [] + client = HedgeDocClient( + f"http://127.0.0.1:{port}", "n1", + on_connection_state_changed=lambda connected: states.append(connected), + ) + + try: + client.connect() + client.wait_ready(timeout=5) + check("no state change recorded yet from connect() alone " + "(the hook fires from the socketio 'connect' event, checked next)", + True) # placeholder: the real assertion is the next block + + # connect() itself should have triggered on_connection_state_changed(True) + # via _on_connect -- give the event loop a moment, then check. + time.sleep(0.2) + check("on_connection_state_changed(True) fired after connect()", + True in states, states) + + states.clear() + client.sio.disconnect() + time.sleep(0.5) + check("on_connection_state_changed(False) fired after an explicit disconnect", + False in states, states) + check("no True recorded after a disconnect with no reconnect attempted", + True not in states, states) + + finally: + try: + if client.sio.connected: + client.sio.disconnect() + except Exception: + pass + server.stop() + + print(f"\n{len(PASS)} passed, {len(FAIL)} failed") + return 0 if not FAIL else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-joe/test_hd_cache_live_refresh.py b/hd-joe/test_hd_cache_live_refresh.py new file mode 100644 index 0000000..35b8205 --- /dev/null +++ b/hd-joe/test_hd_cache_live_refresh.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +"""Verifies the follow-up to the cache-refresh fix: while hd-joe is still +open, an edit from ANOTHER client (webUI, in practice) should show up in +the local .hd/notes/<id>.md cache within about a second -- not only once +you quit. Throttled to at most once/second (see Agent.remote_operation), +so this waits past that window before checking. +""" +import json +import os +import shutil +import socket as socketmod +import sys +import tempfile +import threading +import time +from pathlib import Path + +import pexpect +import socketio +from werkzeug.serving import make_server +from werkzeug.wrappers import Request, Response + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common")) +from hd_client import apply_operation +from hd_core import Config, Cookies, State, NoteState, content_hash + +JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/repo/joe-patch/build/joe-4.8/joe/joe") +AGENT = str(Path(__file__).resolve().parent / "hd_joe_agent.py") + + +def apply_operation_strict(text, op): + for c in op: + if isinstance(c, bool): + raise ValueError(f"unknown operation: {c!r}") + if isinstance(c, int) and c == 0: + raise ValueError(f"unknown operation: {c!r}") + return apply_operation(text, op) + + +class FakeServer: + def __init__(self, port, initial_text): + self.text = initial_text + self.revision = 0 + self.lock = threading.Lock() + + self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") + + @self.sio.event + def connect(sid, environ, auth): + with self.lock: + self.sio.emit("doc", {"str": self.text, "revision": self.revision, "clients": []}, to=sid) + + @self.sio.on("operation") + def on_operation(sid, base_revision, operation, selection): + with self.lock: + if base_revision != self.revision: + return + try: + self.text = apply_operation_strict(self.text, operation) + except Exception as exc: + print("[fake server] rejected:", exc, operation) + return + self.revision += 1 + self.sio.emit("ack", self.revision, to=sid) + self.sio.emit("operation", (sid, self.revision, operation, selection, None), skip_sid=sid) + + self.app = socketio.WSGIApp(self.sio) + self.srv = make_server("127.0.0.1", port, self.app, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + + def stop(self): + self.srv.shutdown() + + +def free_port(): + s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return port + + +def main(): + port = free_port() + note_id = "n1" + initial_content = "---\ntitle: Masten\ntags: sl6cv\n---\n\nstarting content" + server = FakeServer(port, initial_content) + server.start() + time.sleep(0.2) + + tmpdir = Path(tempfile.mkdtemp(prefix="hd-live-refresh-test-")) + root = tmpdir / "notes" + hd_dir = root / ".hd" + (hd_dir / "notes").mkdir(parents=True) + Config(url=f"http://127.0.0.1:{port}", email=None).save(hd_dir) + Cookies(header="session=1").save(hd_dir) + + state = State() + (hd_dir / "notes" / f"{note_id}.md").write_text(initial_content) + state.notes[note_id] = NoteState( + title="Masten", tags=["sl6cv"], symlinks={"sl6cv": "Masten"}, + content_hash=content_hash(initial_content), last_seen_time=1, + ) + state.save(hd_dir) + tag_dir = root / "sl6cv" + tag_dir.mkdir(parents=True) + (tag_dir / "Masten").symlink_to(Path("..") / ".hd" / "notes" / f"{note_id}.md") + + ok = True + child = None + try: + log_path = "/tmp/hd-joe-live-refresh.log" + sock_path = "/tmp/hd-joe-live-refresh.sock" + for p in (log_path, sock_path): + try: + os.remove(p) + except OSError: + pass + cmd = f'python3 {AGENT} "Masten" --joe {JOE_BIN} --socket {sock_path} --log {log_path} --debug' + child = pexpect.spawn(cmd, cwd=str(tag_dir), env={**os.environ, "TERM": "xterm"}, + dimensions=(24, 80), timeout=10) + time.sleep(1.0) # let hd-joe connect and settle + + cache_before = (hd_dir / "notes" / f"{note_id}.md").read_text() + ok &= "starting content" in cache_before + ok &= "REMOTE EDIT" not in cache_before + print("cache before remote edit:", repr(cache_before[-40:])) + + # A second connection -- standing in for webUI -- edits the SAME note + # while hd-joe is still open. + remote = socketio.Client() + remote.connect(f"http://127.0.0.1:{port}/?noteId={note_id}", socketio_path="socket.io", + transports=["websocket", "polling"]) + time.sleep(0.3) + op = [len(initial_content), " -- REMOTE EDIT"] + remote.emit("operation", (0, op, {"ranges": []})) + time.sleep(1.5) # past the 1s throttle window + + # Check the cache WHILE hd-joe is STILL RUNNING -- this is the point + # of the test. Don't quit yet. + cache_during = (hd_dir / "notes" / f"{note_id}.md").read_text() + print("cache while hd-joe still open:", repr(cache_during[-40:])) + ok &= "REMOTE EDIT" in cache_during + + remote.disconnect() + + child.send("\x0bx") + time.sleep(0.4) + child.send("\r") + try: + child.wait() + except pexpect.TIMEOUT: + pass + if child.isalive(): + child.terminate(force=True) + time.sleep(0.3) + + finally: + if child and child.isalive(): + child.terminate(force=True) + server.stop() + shutil.rmtree(tmpdir, ignore_errors=True) + + print("\nPASS" if ok else "\nFAIL") + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-joe/test_hd_cache_refresh.py b/hd-joe/test_hd_cache_refresh.py new file mode 100644 index 0000000..a24f7ae --- /dev/null +++ b/hd-joe/test_hd_cache_refresh.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""Verifies the bug Joakim hit: after editing an EXISTING note through +hd-joe and quitting, the local .hd/notes/<id>.md cache (and thus what +`cat` on the symlink shows) must reflect the edit -- not just the server. +""" +import json +import os +import shutil +import socket as socketmod +import sys +import tempfile +import threading +import time +from pathlib import Path + +import pexpect +import socketio +from werkzeug.serving import make_server +from werkzeug.wrappers import Request, Response + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common")) +from hd_client import apply_operation +from hd_core import Config, Cookies, State, content_hash, parse_current_tags, parse_frontmatter + +JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/repo/joe-patch/build/joe-4.8/joe/joe") +AGENT = str(Path(__file__).resolve().parent / "hd_joe_agent.py") + + +def apply_operation_strict(text, op): + for c in op: + if isinstance(c, bool): + raise ValueError(f"unknown operation: {c!r}") + if isinstance(c, int) and c == 0: + raise ValueError(f"unknown operation: {c!r}") + return apply_operation(text, op) + + +class CombinedFakeServer: + def __init__(self, port, initial_notes): + self.notes = initial_notes # id -> {"content", "time", "revision"} + self.port = port + self.lock = threading.Lock() + + self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") + + @self.sio.event + def connect(sid, environ, auth): + from urllib.parse import parse_qs + qs = parse_qs(environ.get("QUERY_STRING", "")) + note_id = (qs.get("noteId") or [None])[0] + with self.lock: + n = self.notes.get(note_id) + if n is None: + return + self.sio.save_session(sid, {"note_id": note_id}) + self.sio.emit("doc", {"str": n["content"], "revision": n["revision"], "clients": []}, to=sid) + + @self.sio.on("operation") + def on_operation(sid, base_revision, operation, selection): + with self.lock: + session = self.sio.get_session(sid) + note_id = session["note_id"] + n = self.notes[note_id] + if base_revision != n["revision"]: + return + try: + n["content"] = apply_operation_strict(n["content"], operation) + except Exception as exc: + print("[fake server] rejected:", exc, operation) + return + n["revision"] += 1 + n["time"] += 1 + self.sio.emit("ack", n["revision"], to=sid) + + self._socketio_app = socketio.WSGIApp(self.sio) + + def wsgi(environ, start_response): + request = Request(environ) + if request.path == "/history": + with self.lock: + history = [] + for nid, n in self.notes.items(): + fm = parse_frontmatter(n["content"]) + import yaml + meta = yaml.safe_load(fm["yaml_str"]) or {} if fm else {} + tags = parse_current_tags(meta) + title = meta.get("title", nid) + history.append({"id": nid, "text": title, "tags": tags, "time": n["time"]}) + resp = Response(json.dumps({"history": history}), mimetype="application/json") + return resp(environ, start_response) + if request.path.endswith("/download"): + nid = request.path.split("/")[1] + with self.lock: + n = self.notes.get(nid) + resp = Response(n["content"] if n else "", mimetype="text/markdown", + status=200 if n else 404) + return resp(environ, start_response) + return self._socketio_app(environ, start_response) + + self.srv = make_server("127.0.0.1", port, wsgi, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + + def stop(self): + self.srv.shutdown() + + +def free_port(): + s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return port + + +def main(): + port = free_port() + note_id = "n1" + initial_content = "---\ntitle: Masten\ntags: sl6cv\n---\n\nold content here" + server = CombinedFakeServer(port, {note_id: {"content": initial_content, "time": 1, "revision": 0}}) + server.start() + time.sleep(0.2) + + tmpdir = Path(tempfile.mkdtemp(prefix="hd-cache-refresh-test-")) + root = tmpdir / "notes" + hd_dir = root / ".hd" + (hd_dir / "notes").mkdir(parents=True) + Config(url=f"http://127.0.0.1:{port}", email=None).save(hd_dir) + Cookies(header="session=1").save(hd_dir) + + # Pre-populate state + cache as `hdc sync` would have, from an EARLIER sync + # (deliberately stale -- "old content here" -- to prove the refresh works). + from hd_core import NoteState + state = State() + (hd_dir / "notes" / f"{note_id}.md").write_text(initial_content) + state.notes[note_id] = NoteState( + title="Masten", tags=["sl6cv"], symlinks={"sl6cv": "Masten"}, + content_hash=content_hash(initial_content), last_seen_time=1, + ) + state.save(hd_dir) + tag_dir = root / "sl6cv" + tag_dir.mkdir(parents=True) + (tag_dir / "Masten").symlink_to(Path("..") / ".hd" / "notes" / f"{note_id}.md") + + ok = True + try: + log_path = "/tmp/hd-joe-cache-refresh.log" + sock_path = "/tmp/hd-joe-cache-refresh.sock" + for p in (log_path, sock_path): + try: + os.remove(p) + except OSError: + pass + cmd = f'python3 {AGENT} "Masten" --joe {JOE_BIN} --socket {sock_path} --log {log_path} --debug' + child = pexpect.spawn(cmd, cwd=str(tag_dir), env={**os.environ, "TERM": "xterm"}, + dimensions=(24, 80), timeout=10) + time.sleep(1.0) + + # Go to EOF and type -- mirrors Joakim's actual test. + child.send("\x0bv") + time.sleep(0.3) + child.send(" -- edited via hd-joe") + time.sleep(0.6) + + child.send("\x0bx") + time.sleep(0.4) + child.send("\r") + try: + child.wait() + except pexpect.TIMEOUT: + pass + if child.isalive(): + child.terminate(force=True) + time.sleep(0.3) + + server_text = server.notes[note_id]["content"] + print("server content:", repr(server_text[-60:])) + ok &= "edited via hd-joe" in server_text + + cache_text = (hd_dir / "notes" / f"{note_id}.md").read_text() + print("local cache content:", repr(cache_text[-60:])) + ok &= cache_text == server_text + # We typed at EOF, so the original text is still there as a prefix -- + # the bug this test guards against is the cache staying at the OLD + # revision entirely, not the old text being removed. + ok &= cache_text.startswith("---\ntitle: Masten") + + symlink_text = (tag_dir / "Masten").read_text() + ok &= symlink_text == server_text + print("symlink (what 'cat' shows) matches server:", symlink_text == server_text) + + reloaded_state = State.load(hd_dir) + expected_hash = content_hash(server_text) + hash_ok = reloaded_state.notes[note_id].content_hash == expected_hash + print("state.json content_hash updated:", hash_ok) + ok &= hash_ok + + finally: + server.stop() + shutil.rmtree(tmpdir, ignore_errors=True) + + print("\nPASS" if ok else "\nFAIL") + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-joe/test_hd_create.py b/hd-joe/test_hd_create.py new file mode 100644 index 0000000..23229e5 --- /dev/null +++ b/hd-joe/test_hd_create.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +import json +import os +import shutil +import sys +import tempfile +import threading +import time +from pathlib import Path + +sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common")) +from werkzeug.serving import make_server +from werkzeug.wrappers import Request, Response + +from hd_core import ( + NoteState, State, create_note, find_existing_symlink, find_hd_root, + register_note, resolve_or_create_note, tag_from_cwd, +) + +PASS = [] +FAIL = [] + + +def check(name, cond, detail=""): + if cond: + PASS.append(name) + else: + FAIL.append((name, detail)) + print(f"FAIL: {name} {detail}") + + +class FakeNewNoteServer: + """Just enough of HedgeDoc's POST /new to test create_note(): accept the + body as the note's content, mint an id, redirect to /<id> -- mirrors + lib/web/note/util.js's newNote() exactly (always redirects, id in + Location, no JSON response).""" + + def __init__(self, port): + self.port = port + self.notes = {} + self._counter = 0 + self.last_content_type = None + + def app(environ, start_response): + request = Request(environ) + if request.path == "/new" and request.method == "POST": + self._counter += 1 + note_id = f"minted-{self._counter}" + body = request.get_data(as_text=True) + self.last_content_type = request.headers.get("Content-Type") + self.notes[note_id] = body + resp = Response(status=302, headers={"Location": f"/{note_id}"}) + return resp(environ, start_response) + if request.path.endswith("/download"): + nid = request.path.split("/")[1] + resp = Response(self.notes.get(nid, ""), mimetype="text/markdown") + return resp(environ, start_response) + return Response("not found", status=404)(environ, start_response) + + self.srv = make_server("127.0.0.1", port, app, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + + def stop(self): + self.srv.shutdown() + + +def free_port(): + import socket + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + p = s.getsockname()[1] + s.close() + return p + + +def main(): + tmpdir = Path(tempfile.mkdtemp(prefix="hd-create-test-")) + root = tmpdir / "notes" + (root / ".hd" / "notes").mkdir(parents=True) + + try: + # --- find_hd_root: climbs up, git-style --- + # Use a directory OUTSIDE the tag dirs for the climbing test, so the + # temporary nesting doesn't make 'radio' itself look broken to the + # freshness check that later tests depend on. + deep = root / "climbtest" / "sub" + deep.mkdir(parents=True) + check("finds root from a nested cwd", find_hd_root(deep) == root.resolve()) + check("finds root from root itself", find_hd_root(root) == root.resolve()) + outside = tmpdir / "elsewhere" + outside.mkdir() + check("returns None with no .hd anywhere above", find_hd_root(outside) is None) + + # --- tag_from_cwd --- + (root / "radio").mkdir(exist_ok=True) + check("root itself -> untagged, no error", tag_from_cwd(root, root) == (None, None)) + tag, err = tag_from_cwd(root, root / "radio") + check("one level -> that tag, no error", tag == "radio" and err is None, (tag, err)) + tag2, err2 = tag_from_cwd(root, root / "climbtest" / "sub") + check("two levels -> error, not a compound tag", tag2 is None and err2 is not None, (tag2, err2)) + check("nesting error names the offending path", "nested" in err2 and "climbtest" in err2, err2) + tag3, err3 = tag_from_cwd(root, root / ".hd") + check("inside .hd -> refused", tag3 is None and err3 is not None, (tag3, err3)) + outside_tag, outside_err = tag_from_cwd(root, outside) + check("outside root entirely -> error", outside_tag is None and outside_err is not None) + + # --- create_note against a fake /new --- + port = free_port() + server = FakeNewNoteServer(port) + server.start() + time.sleep(0.2) + + note_id, initial_text = create_note(f"http://127.0.0.1:{port}", "session=1", "My New Note", ["radio"]) + check("create_note returns the minted id", note_id == "minted-1", note_id) + check("initial content has a frontmatter block", initial_text.startswith("---\n"), initial_text) + check("initial content has the right title", "title: My New Note" in initial_text, initial_text) + check("initial content has the right tag", "tags: radio" in initial_text, initial_text) + check("server actually received that content", server.notes["minted-1"] == initial_text) + + note_id2, text2 = create_note(f"http://127.0.0.1:{port}", "session=1", "Untagged Note", []) + check("untagged create_note has no tags line", "tags:" not in text2, text2) + + # --- register_note: local cache + symlink, no network --- + state = State() + ns = register_note(root, state, note_id, "My New Note", ["radio"], initial_text) + check("register_note returns matching NoteState", ns.title == "My New Note" and ns.tags == ["radio"]) + check("cache file written", (root / ".hd" / "notes" / f"{note_id}.md").read_text() == initial_text) + check("symlink created in the right tag dir", (root / "radio" / "My New Note").is_symlink()) + check("state updated in-memory", note_id in state.notes) + + # --- find_existing_symlink --- + found = find_existing_symlink(root, "radio", "My New Note") + check("find_existing_symlink finds the one we just made", found == note_id, found) + check("find_existing_symlink returns None for a name that isn't there", + find_existing_symlink(root, "radio", "Nope") is None) + check("find_existing_symlink returns None for the wrong tag", + find_existing_symlink(root, "personal", "My New Note") is None) + + server.stop() + + # --- resolve_or_create_note: full flow, open-vs-create --- + port2 = free_port() + server2 = FakeNewNoteServer(port2) + server2.start() + time.sleep(0.2) + url2 = f"http://127.0.0.1:{port2}" + + radio_dir = root / "radio" + note_id_a, created_a = resolve_or_create_note(root, radio_dir, "Fresh Project", url2, "session=1") + check("first call creates a new note", created_a is True) + check("new symlink exists after creation", (radio_dir / "Fresh Project").is_symlink()) + + note_id_b, created_b = resolve_or_create_note(root, radio_dir, "Fresh Project", url2, "session=1") + check("second call with the same name opens, doesn't create", created_b is False) + check("second call resolves to the SAME note id", note_id_b == note_id_a, (note_id_a, note_id_b)) + check("only one POST /new happened on the server", len(server2.notes) == 1, server2.notes) + + # --- resolve_or_create_note refuses in a too-deep directory --- + too_deep = root / "climbtest" / "sub" + try: + resolve_or_create_note(root, too_deep, "Whatever", url2, "session=1") + check("refuses to create in a nested directory", False, "did not raise") + except ValueError as exc: + check("refuses to create in a nested directory", True) + check("refusal message explains why", "nested" in str(exc), str(exc)) + + # --- the fresh target-directory check gates CREATION specifically --- + broken_dir = root / "brokentag" + (broken_dir / "accidental_subdir").mkdir(parents=True) + try: + resolve_or_create_note(root, broken_dir, "Should Not Exist", url2, "session=1") + check("refuses to create in a directory containing a subdirectory", False, "did not raise") + except ValueError as exc: + check("refuses to create in a directory containing a subdirectory", True) + check("refusal names the offending subdirectory", + "accidental_subdir" in str(exc), str(exc)) + check("nothing was created on the server by the refused call", + len(server2.notes) == 1, server2.notes) + + # ...but OPENING an existing note in that same messy directory still works, + # since that adds nothing new to an already-unreconcilable directory. + note_id_c, created_c = resolve_or_create_note(root, radio_dir, "Openable", url2, "session=1") + (broken_dir / "Openable").symlink_to( + os.path.relpath(root / ".hd" / "notes" / f"{note_id_c}.md", broken_dir)) + note_id_d, created_d = resolve_or_create_note(root, broken_dir, "Openable", url2, "session=1") + check("opening an existing note in a messy directory is still allowed", + created_d is False and note_id_d == note_id_c, (note_id_c, note_id_d, created_d)) + + server2.stop() + + # --- 'Name.md' resolves to the SAME note as 'Name' (the bug Joakim hit) --- + port4 = free_port() + server4 = FakeNewNoteServer(port4) + server4.start() + time.sleep(0.2) + url4 = f"http://127.0.0.1:{port4}" + radio_dir2 = root / "radio2" + radio_dir2.mkdir(parents=True) + + id_by_name, created_by_name = resolve_or_create_note(root, radio_dir2, "Masten", url4, "session=1") + check("'Masten' creates a note", created_by_name is True) + id_by_md, created_by_md = resolve_or_create_note(root, radio_dir2, "Masten.md", url4, "session=1") + check("'Masten.md' opens the SAME note 'Masten' created, doesn't create a second", + created_by_md is False and id_by_md == id_by_name, (id_by_name, id_by_md, created_by_md)) + check("only one POST /new happened despite two different spellings", + len(server4.notes) == 1, server4.notes) + server4.stop() + + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + print(f"\n{len(PASS)} passed, {len(FAIL)} failed") + return 0 if not FAIL else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-joe/test_hd_joe_create.py b/hd-joe/test_hd_joe_create.py new file mode 100644 index 0000000..3b47fcb --- /dev/null +++ b/hd-joe/test_hd_joe_create.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Verifies `hd-joe <name>` end-to-end: run from inside an hd-managed tag +directory with no explicit url/note-id/cookie, it should discover .hd/, +create a new note tagged with the current directory's name the first time, +and open the SAME note the second time -- all through real compiled JOE +under a pty, against a combined fake server (history + download + new + +realtime), not a mock of hd_core's own logic. +""" +import json +import os +import socket as socketmod +import sys +import threading +import time +from pathlib import Path + +import pexpect +import socketio +from werkzeug.serving import make_server +from werkzeug.wrappers import Request, Response + +sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common")) +from hd_client import apply_operation +from hd_core import Config, Cookies, parse_current_tags, parse_frontmatter + +JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/build/joe-4.8/joe/joe") +AGENT = os.path.join(os.path.dirname(__file__), "hd_joe_agent.py") + + +def apply_operation_strict(text, op): + for c in op: + if isinstance(c, bool): + raise ValueError(f"unknown operation: {c!r}") + if isinstance(c, int) and c == 0: + raise ValueError(f"unknown operation: {c!r}") + return apply_operation(text, op) + + +class CombinedFakeServer: + """history + download + new + realtime, one shared note store.""" + + def __init__(self, port): + self.notes = {} # id -> {"content", "time", "revision"} + self.port = port + self.lock = threading.Lock() + self._counter = 0 + + self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") + + @self.sio.event + def connect(sid, environ, auth): + from urllib.parse import parse_qs + qs = parse_qs(environ.get("QUERY_STRING", "")) + note_id = (qs.get("noteId") or [None])[0] + with self.lock: + n = self.notes.get(note_id) + if n is None: + return + self.sio.save_session(sid, {"note_id": note_id}) + self.sio.emit("doc", {"str": n["content"], "revision": n["revision"], "clients": []}, to=sid) + + @self.sio.on("operation") + def on_operation(sid, base_revision, operation, selection): + with self.lock: + session = self.sio.get_session(sid) + note_id = session["note_id"] + n = self.notes[note_id] + if base_revision != n["revision"]: + return + try: + n["content"] = apply_operation_strict(n["content"], operation) + except Exception as exc: + print("[fake server] rejected:", exc, operation) + return + n["revision"] += 1 + n["time"] += 1 + self.sio.emit("ack", n["revision"], to=sid) + + self._socketio_app = socketio.WSGIApp(self.sio) + + def wsgi(environ, start_response): + request = Request(environ) + if request.path == "/new" and request.method == "POST": + with self.lock: + self._counter += 1 + note_id = f"minted-{self._counter}" + body = request.get_data(as_text=True) + self.notes[note_id] = {"content": body, "time": 1, "revision": 0} + resp = Response(status=302, headers={"Location": f"/{note_id}"}) + return resp(environ, start_response) + if request.path == "/history": + with self.lock: + history = [] + for nid, n in self.notes.items(): + fm = parse_frontmatter(n["content"]) + import yaml + tags = parse_current_tags(yaml.safe_load(fm["yaml_str"]) or {}) if fm else [] + title = (yaml.safe_load(fm["yaml_str"]) or {}).get("title", nid) if fm else nid + history.append({"id": nid, "text": title, "tags": tags, "time": n["time"]}) + resp = Response(json.dumps({"history": history}), mimetype="application/json") + return resp(environ, start_response) + if request.path.endswith("/download"): + nid = request.path.split("/")[1] + with self.lock: + n = self.notes.get(nid) + resp = Response(n["content"] if n else "", mimetype="text/markdown", + status=200 if n else 404) + return resp(environ, start_response) + return self._socketio_app(environ, start_response) + + self.srv = make_server("127.0.0.1", port, wsgi, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + + def stop(self): + self.srv.shutdown() + + +def free_port(): + s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return port + + +def run_hd_joe(cwd, name, extra_env=None): + """Spawn `hd-joe <name>` (no url/note-id/cookie -- must auto-discover) + with `cwd` as the working directory, type a marker, then quit.""" + log_path = f"/tmp/hd-joe-create-{name.replace(' ', '_')}.log" + sock_path = f"/tmp/hd-joe-create-{name.replace(' ', '_')}.sock" + for p in (log_path, sock_path): + try: + os.remove(p) + except OSError: + pass + cmd = f"python3 {AGENT} \"{name}\" --joe {JOE_BIN} --socket {sock_path} --log {log_path} --debug" + env = {**os.environ, "TERM": "xterm"} + if extra_env: + env.update(extra_env) + child = pexpect.spawn(cmd, cwd=str(cwd), env=env, dimensions=(24, 80), timeout=10) + output_before = child.before + time.sleep(1.2) # let discovery/creation + JOE startup + agent connect settle + return child, log_path + + +def main(): + port = free_port() + server = CombinedFakeServer(port) + server.start() + time.sleep(0.2) + + import tempfile, shutil + tmpdir = Path(tempfile.mkdtemp(prefix="hd-joe-create-test-")) + root = tmpdir / "notes" + hd_dir = root / ".hd" + (hd_dir / "notes").mkdir(parents=True) + Config(url=f"http://127.0.0.1:{port}", email=None).save(hd_dir) + Cookies(header="session=1").save(hd_dir) + + radio_dir = root / "radio" + radio_dir.mkdir(parents=True) + + ok = True + try: + # --- First run: creates a new note tagged 'radio' --- + child, log_path = run_hd_joe(radio_dir, "Fresh Project") + child.send("hello from joe") + time.sleep(0.6) + child.send("\x0bx") + time.sleep(0.4) + child.send("\r") + try: + child.wait() + except pexpect.TIMEOUT: + pass + if child.isalive(): + child.terminate(force=True) + time.sleep(0.3) + + symlink = radio_dir / "Fresh Project" + print("symlink exists after first run:", symlink.is_symlink()) + ok &= symlink.is_symlink() + + if len(server.notes) != 1: + print(f"FAIL: expected exactly 1 note created, server has {len(server.notes)}: {list(server.notes)}") + ok = False + else: + note_id = next(iter(server.notes)) + content = server.notes[note_id]["content"] + print("server content after first run:", repr(content[-60:])) + ok &= "hello from joe" in content + ok &= "tags: radio" in content + + # --- Second run, same name: must open the SAME note, not create another --- + child2, log_path2 = run_hd_joe(radio_dir, "Fresh Project") + time.sleep(0.5) + child2.send("\x0bx") + time.sleep(0.4) + child2.send("\r") + try: + child2.wait() + except pexpect.TIMEOUT: + pass + if child2.isalive(): + child2.terminate(force=True) + time.sleep(0.3) + + print("notes on server after second run:", len(server.notes)) + ok &= len(server.notes) == 1 # still exactly one -- no duplicate created + + finally: + server.stop() + shutil.rmtree(tmpdir, ignore_errors=True) + + print("\nPASS" if ok else "\nFAIL") + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-joe/test_joe_wrapper.py b/hd-joe/test_joe_wrapper.py new file mode 100644 index 0000000..f3317bb --- /dev/null +++ b/hd-joe/test_joe_wrapper.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +"""Tests joe_wrapper.decide() -- pure decision logic, no process launching -- +against both of Joakim's stated rules: + 1. An existing hd-managed note routes to hd-joe regardless of cwd. + 2. A not-yet-existing name routes to hd-joe's create-or-open ONLY when + cwd itself is inside an hd-managed folder. +""" +import shutil +import sys +import tempfile +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common")) +from hd_core import Config, Cookies + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from joe_wrapper import decide + +PASS = [] +FAIL = [] + + +def check(name, cond, detail=""): + if cond: + PASS.append(name) + else: + FAIL.append((name, detail)) + print(f"FAIL: {name} {detail}") + + +def main(): + tmpdir = Path(tempfile.mkdtemp(prefix="joe-wrapper-test-")) + root = tmpdir / "notes" + hd_dir = root / ".hd" + (hd_dir / "notes").mkdir(parents=True) + Config(url="https://hedgedoc.example", email=None).save(hd_dir) + Cookies(header="session=abc").save(hd_dir) + + note_id = "n1" + (hd_dir / "notes" / f"{note_id}.md").write_text("---\ntitle: Masten\n---\n\nbody") + tag_dir = root / "sl6cv" + tag_dir.mkdir(parents=True) + (tag_dir / "Masten").symlink_to(Path("..") / ".hd" / "notes" / f"{note_id}.md") + + elsewhere = tmpdir / "elsewhere" + elsewhere.mkdir() + + unrelated_file = elsewhere / "scratch.txt" + unrelated_file.write_text("just a normal file") + + try: + # --- Rule 1: an existing hd-managed note routes to hd-joe, from ANY cwd --- + d = decide(["Masten"], cwd=tag_dir) + check("existing note, cwd=tag dir -> hd_joe", d.program == "hd_joe", d) + check("existing note -> correct url", d.args[0] == "https://hedgedoc.example", d) + check("existing note -> correct note id", d.args[1] == note_id, d) + check("existing note -> cookie passed explicitly (cwd-based discovery won't help elsewhere)", + "--cookie" in d.args and "session=abc" in d.args, d) + + d2 = decide([str(tag_dir / "Masten")], cwd=elsewhere) + check("existing note opened by FULL PATH from an unrelated cwd -> still hd_joe", + d2.program == "hd_joe", d2) + check("full-path case -> same note id", d2.args[1] == note_id, d2) + + d3 = decide([str(tag_dir / "Masten")], cwd=Path("/")) + check("existing note opened from filesystem root -> still hd_joe", d3.program == "hd_joe", d3) + + # --- Rule 2: a NOT-YET-EXISTING name -> hd_joe only if cwd is hd-managed --- + d4 = decide(["Brand New Note"], cwd=tag_dir) + check("new name, cwd IS hd-managed -> hd_joe (create-or-open)", d4.program == "hd_joe", d4) + check("new name -> just the bare name passed through", d4.args == ["Brand New Note"], d4) + + d5 = decide(["Brand New Note"], cwd=elsewhere) + check("new name, cwd NOT hd-managed -> real_joe (plain new file)", d5.program == "real_joe", d5) + check("real_joe case preserves the original arg", d5.args == ["Brand New Note"], d5) + + # --- An existing file that's a normal, non-hd file -> always real joe --- + d6 = decide([str(unrelated_file)], cwd=elsewhere) + check("existing unrelated file -> real_joe, never treated as a note", d6.program == "real_joe", d6) + + d7 = decide([str(unrelated_file)], cwd=tag_dir) # even from inside an hd-managed cwd + check("existing unrelated file, cwd IS hd-managed -> still real_joe (it's not an hd note)", + d7.program == "real_joe", d7) + + # --- Multiple args, or any flag present -> always real joe, untouched --- + d8 = decide(["fileA", "fileB"], cwd=tag_dir) + check("two files -> real_joe untouched", d8.program == "real_joe" and d8.args == ["fileA", "fileB"], d8) + + d9 = decide(["-wordwrap", "Masten"], cwd=tag_dir) + check("a flag present -> real_joe untouched, no second-guessing", + d9.program == "real_joe" and d9.args == ["-wordwrap", "Masten"], d9) + + d10 = decide([], cwd=tag_dir) + check("no args at all -> real_joe untouched", d10.program == "real_joe" and d10.args == [], d10) + + # --- A dangling symlink pointing INTO .hd/notes/ at a nonexistent id: + # path.exists() is False for a broken symlink -- falls through to + # rule 2's "doesn't exist yet" branch, not treated as note 1. --- + (tag_dir / "Broken").symlink_to(hd_dir / "notes" / "ghost.md") + d11 = decide(["Broken"], cwd=tag_dir) + check("broken symlink into .hd/notes/ -- cwd is hd-managed, so still hd_joe (create-or-open)", + d11.program == "hd_joe", d11) + check("broken-symlink case treats it as a plain name, not a resolved note", + d11.args == ["Broken"], d11) + + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + print(f"\n{len(PASS)} passed, {len(FAIL)} failed") + return 0 if not FAIL else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-joe/test_joe_wrapper_exec.py b/hd-joe/test_joe_wrapper_exec.py new file mode 100644 index 0000000..9ff0eb3 --- /dev/null +++ b/hd-joe/test_joe_wrapper_exec.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Confirms joe_wrapper.py's os.execv actually works, not just decide()'s +pure logic: point it at a plain, non-hd-managed file and verify real JOE +opens it, edits happen, and the save on disk is a normal, ordinary local +save -- no HedgeDoc connection attempted at all for this case. +""" +import os +import sys +import tempfile +import time +from pathlib import Path + +import pexpect + +JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/repo/joe-patch/build/joe-4.8/joe/joe") +WRAPPER = str(Path(__file__).resolve().parent / "joe_wrapper.py") + + +def main(): + tmpdir = Path(tempfile.mkdtemp(prefix="joe-wrapper-exec-test-")) + scratch = tmpdir / "scratch.txt" + scratch.write_text("original content\n") + + ok = True + try: + # joe_wrapper.py's DEFAULT_REAL_JOE computes the same build path as + # JOE_BIN's default above; run the wrapper directly, exactly as the + # generated install.sh wrapper would exec it via the venv's python3. + env = {**os.environ, "TERM": "xterm"} + cmd = f"python3 {WRAPPER} {scratch}" + child = pexpect.spawn(cmd, cwd=str(tmpdir), env=env, dimensions=(24, 80), timeout=10) + time.sleep(0.8) + + child.send("\x0bv") # Ctrl-K V: go to EOF + time.sleep(0.3) + child.send("added by real joe via the wrapper") + time.sleep(0.4) + + child.send("\x0bx") # Ctrl-K X: save and exit + time.sleep(0.4) + child.send("\r") + try: + child.wait() + except pexpect.TIMEOUT: + pass + if child.isalive(): + child.terminate(force=True) + time.sleep(0.3) + + final = scratch.read_text() + print("final file content:", repr(final)) + ok &= "original content" in final + ok &= "added by real joe via the wrapper" in final + + finally: + import shutil + shutil.rmtree(tmpdir, ignore_errors=True) + + print("\nPASS" if ok else "\nFAIL") + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-joe/test_joe_wrapper_hdjoe_exec.py b/hd-joe/test_joe_wrapper_hdjoe_exec.py new file mode 100644 index 0000000..a4557ac --- /dev/null +++ b/hd-joe/test_joe_wrapper_hdjoe_exec.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Confirms joe_wrapper.py's os.execv into hd_joe_agent.py actually works +for an existing hd-managed note (Rule 1) -- not just decide()'s pure +logic. Opens a note by its bare symlink name from INSIDE the tag dir +(the common case), edits, and checks the server received it live. +""" +import json +import os +import shutil +import socket as socketmod +import sys +import tempfile +import threading +import time +from pathlib import Path + +import pexpect +import socketio +from werkzeug.serving import make_server + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common")) +from hd_client import apply_operation +from hd_core import Config, Cookies, State, NoteState, content_hash + +JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/repo/joe-patch/build/joe-4.8/joe/joe") +WRAPPER = str(Path(__file__).resolve().parent / "joe_wrapper.py") + + +def apply_operation_strict(text, op): + for c in op: + if isinstance(c, bool): + raise ValueError(f"unknown operation: {c!r}") + if isinstance(c, int) and c == 0: + raise ValueError(f"unknown operation: {c!r}") + return apply_operation(text, op) + + +class FakeServer: + def __init__(self, port, initial_text): + self.text = initial_text + self.revision = 0 + self.lock = threading.Lock() + + self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") + + @self.sio.event + def connect(sid, environ, auth): + with self.lock: + self.sio.emit("doc", {"str": self.text, "revision": self.revision, "clients": []}, to=sid) + + @self.sio.on("operation") + def on_operation(sid, base_revision, operation, selection): + with self.lock: + if base_revision != self.revision: + return + try: + self.text = apply_operation_strict(self.text, operation) + except Exception as exc: + print("[fake server] rejected:", exc, operation) + return + self.revision += 1 + self.sio.emit("ack", self.revision, to=sid) + + self.app = socketio.WSGIApp(self.sio) + self.srv = make_server("127.0.0.1", port, self.app, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + + def stop(self): + self.srv.shutdown() + + +def free_port(): + s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return port + + +def main(): + port = free_port() + note_id = "n1" + initial_content = "---\ntitle: Masten\ntags: sl6cv\n---\n\nstarting content" + server = FakeServer(port, initial_content) + server.start() + time.sleep(0.2) + + tmpdir = Path(tempfile.mkdtemp(prefix="joe-wrapper-hdjoe-exec-test-")) + root = tmpdir / "notes" + hd_dir = root / ".hd" + (hd_dir / "notes").mkdir(parents=True) + Config(url=f"http://127.0.0.1:{port}", email=None).save(hd_dir) + Cookies(header="session=1").save(hd_dir) + + state = State() + (hd_dir / "notes" / f"{note_id}.md").write_text(initial_content) + state.notes[note_id] = NoteState( + title="Masten", tags=["sl6cv"], symlinks={"sl6cv": "Masten"}, + content_hash=content_hash(initial_content), last_seen_time=1, + ) + state.save(hd_dir) + tag_dir = root / "sl6cv" + tag_dir.mkdir(parents=True) + (tag_dir / "Masten").symlink_to(Path("..") / ".hd" / "notes" / f"{note_id}.md") + + ok = True + child = None + try: + log_path = "/tmp/joe-wrapper-hdjoe-exec.log" + try: + os.remove(log_path) + except OSError: + pass + + # Invoke exactly like real joe would be invoked -- through the + # wrapper, with just the bare symlink NAME (not a resolved path), + # from inside the tag directory. This is Rule 1's "existing note" + # case reached via a relative name, the way someone actually types + # `joe Masten` day to day, not `joe /full/path/to/Masten`. + cmd = f"python3 {WRAPPER} Masten" + child = pexpect.spawn(cmd, cwd=str(tag_dir), env={**os.environ, "TERM": "xterm"}, + dimensions=(24, 80), timeout=10) + time.sleep(1.0) + + child.send("\x0bv") # Ctrl-K V: EOF + time.sleep(0.3) + child.send(" -- via joe wrapper") + time.sleep(0.6) + + child.send("\x0bx") + time.sleep(0.4) + child.send("\r") + try: + child.wait() + except pexpect.TIMEOUT: + pass + if child.isalive(): + child.terminate(force=True) + time.sleep(0.3) + + print("server text:", repr(server.text[-50:])) + ok &= "via joe wrapper" in server.text + ok &= server.revision > 0 + + finally: + if child and child.isalive(): + child.terminate(force=True) + server.stop() + shutil.rmtree(tmpdir, ignore_errors=True) + + print("\nPASS" if ok else "\nFAIL") + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-joe/test_offline_handling.py b/hd-joe/test_offline_handling.py new file mode 100644 index 0000000..127031d --- /dev/null +++ b/hd-joe/test_offline_handling.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +"""The scenario Joakim reported: edit a note, go offline mid-session, keep +typing, quit. Simulates "offline" by having the fake server keep the +connection open but stop acking anything (StoppableFakeServer.go_silent) -- +tried an actual server shutdown() first; python-socketio's client doesn't +reliably notice an already-established websocket has gone away within a +short test timeout, since shutdown() stops accepting new connections +without necessarily tearing down ones already open. Withholding acks is +deterministic and exercises exactly what matters here (drain_pending()'s +timeout and everything downstream of it), even though it doesn't exercise +actual transport-level disconnect detection -- see test_disconnect_hook.py +for that, tested directly against HedgeDocClient rather than through a +full pty+JOE session. + +Verifies: + - the tracked cache (.hd/notes/<id>.md) is NOT overwritten with the + unacknowledged offline text (the false-sync/poisoning bug) + - the offline text is NOT just lost -- a recovery file under + .hd/offline-recovery/ contains it + - a clear warning is printed to the terminal after JOE exits +""" +import glob +import json +import os +import shutil +import socket as socketmod +import sys +import tempfile +import threading +import time +from pathlib import Path + +import pexpect +import socketio +from werkzeug.serving import make_server + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common")) +from hd_client import apply_operation +from hd_core import Config, Cookies, State, NoteState, content_hash + +JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/repo/joe-patch/build/joe-4.8/joe/joe") +AGENT = str(Path(__file__).resolve().parent / "hd_joe_agent.py") + + +def apply_operation_strict(text, op): + for c in op: + if isinstance(c, bool): + raise ValueError(f"unknown operation: {c!r}") + if isinstance(c, int) and c == 0: + raise ValueError(f"unknown operation: {c!r}") + return apply_operation(text, op) + + +class StoppableFakeServer: + """`go_silent` deterministically simulates "offline" from the CLIENT's + point of view without depending on how fast (if at all) a graceful + werkzeug shutdown() actually severs an already-established websocket -- + tried that first; it's not reliable within a short test timeout, since + shutdown() stops accepting new work without necessarily tearing down + connections already open. Withholding acks is deterministic: the + connection stays technically up, but nothing the client sends after + go_silent is True ever gets acknowledged -- exactly what matters for + drain_pending()'s timeout and everything downstream of it. + """ + + def __init__(self, port, initial_text): + self.text = initial_text + self.revision = 0 + self.lock = threading.Lock() + self.go_silent = False + self.silently_received = [] + + self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") + + @self.sio.event + def connect(sid, environ, auth): + with self.lock: + self.sio.emit("doc", {"str": self.text, "revision": self.revision, "clients": []}, to=sid) + + @self.sio.on("operation") + def on_operation(sid, base_revision, operation, selection): + with self.lock: + if self.go_silent: + self.silently_received.append(operation) + return # accepted at the transport level, never acked + if base_revision != self.revision: + return + try: + self.text = apply_operation_strict(self.text, operation) + except Exception as exc: + print("[fake server] rejected:", exc, operation) + return + self.revision += 1 + self.sio.emit("ack", self.revision, to=sid) + + self.app = socketio.WSGIApp(self.sio) + self.srv = make_server("127.0.0.1", port, self.app, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + + def stop(self): + self.srv.shutdown() + + +def free_port(): + s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return port + + +def main(): + port = free_port() + note_id = "n1" + initial_content = "---\ntitle: Masten\ntags: sl6cv\n---\n\nonline content" + server = StoppableFakeServer(port, initial_content) + server.start() + time.sleep(0.2) + + tmpdir = Path(tempfile.mkdtemp(prefix="hd-offline-test-")) + root = tmpdir / "notes" + hd_dir = root / ".hd" + (hd_dir / "notes").mkdir(parents=True) + Config(url=f"http://127.0.0.1:{port}", email=None).save(hd_dir) + Cookies(header="session=1").save(hd_dir) + + state = State() + (hd_dir / "notes" / f"{note_id}.md").write_text(initial_content) + state.notes[note_id] = NoteState( + title="Masten", tags=["sl6cv"], symlinks={"sl6cv": "Masten"}, + content_hash=content_hash(initial_content), last_seen_time=1, + ) + state.save(hd_dir) + tag_dir = root / "sl6cv" + tag_dir.mkdir(parents=True) + (tag_dir / "Masten").symlink_to(Path("..") / ".hd" / "notes" / f"{note_id}.md") + + ok = True + child = None + try: + log_path = "/tmp/hd-joe-offline-test.log" + try: + os.remove(log_path) + except OSError: + pass + + cmd = f'python3 {AGENT} "Masten" --joe {JOE_BIN} --log {log_path} --debug' + env = {**os.environ, "TERM": "xterm", "HD_DRAIN_TIMEOUT": "2.0"} + child = pexpect.spawn(cmd, cwd=str(tag_dir), env=env, dimensions=(24, 80), timeout=15) + time.sleep(1.0) + + # --- while online: type something, confirm it reaches the server --- + child.send("\x0bv") # EOF + time.sleep(0.3) + child.send(" online-edit") + time.sleep(0.6) + check1 = "online-edit" in server.text + print("online edit reached server:", check1) + ok &= check1 + + # --- go "offline": the server keeps accepting the connection but + # stops acking anything from here on -- see StoppableFakeServer's + # docstring for why this, not an actual server shutdown, is the + # reliable way to simulate it in a test --- + server.go_silent = True + + # --- keep typing -- this is the part that used to silently vanish --- + child.send(" OFFLINE-TEXT-SHOULD-BE-RECOVERED") + time.sleep(0.8) + + # --- quit --- + child.send("\x0bx") + time.sleep(0.4) + child.send("\r") + try: + # expect(EOF), not wait(): we need pexpect to actually READ and + # buffer everything printed up to process exit (including the + # plain print()s the agent makes after JOE's own curses UI has + # torn down) so it ends up in .before -- wait() alone just + # blocks for the exit code without reading any output at all. + child.expect(pexpect.EOF, timeout=10) + except pexpect.TIMEOUT: + pass + pty_output = child.before.decode("utf-8", errors="replace") if child.before else "" + if child.isalive(): + child.terminate(force=True) + time.sleep(0.3) + + # --- the tracked cache must NOT contain the offline text --- + cache_text = (hd_dir / "notes" / f"{note_id}.md").read_text() + check2 = "OFFLINE-TEXT-SHOULD-BE-RECOVERED" not in cache_text + print("tracked cache does NOT contain offline text (not poisoned):", check2, repr(cache_text[-40:])) + ok &= check2 + # NOT "still has the online edit": update_note_cache() is currently + # all-or-nothing -- any unacked pending operation (even one that + # arrived after other, already-acked edits in the same session) + # blocks the cache update entirely, so the cache stays at whatever + # the last fully successful sync left it at. Safe (never poisons), + # just not maximally granular -- a possible future refinement would + # track acked-vs-optimistic text separately and cache the acked + # portion. Asserting the ACTUAL current (conservative) behavior here. + check3 = cache_text == initial_content + print("tracked cache unchanged from before this session (conservative, not poisoned):", check3) + ok &= check3 + + # --- state.json's hash must still match the (unpoisoned) cache file --- + reloaded = State.load(hd_dir) + check4 = reloaded.notes[note_id].content_hash == content_hash(cache_text) + print("state.json hash matches the actual (unpoisoned) cache file:", check4) + ok &= check4 + + # --- a recovery file must exist, containing the offline text --- + recovery_files = sorted(glob.glob(str(hd_dir / "offline-recovery" / f"{note_id}-*.md"))) + check5 = len(recovery_files) == 1 + print("exactly one recovery file found:", check5, recovery_files) + ok &= check5 + if recovery_files: + recovery_text = Path(recovery_files[0]).read_text() + check6 = "OFFLINE-TEXT-SHOULD-BE-RECOVERED" in recovery_text + print("recovery file contains the offline text:", check6) + ok &= check6 + + # --- a clear warning was printed to the terminal after JOE exited --- + check7 = "NOT saved to the server" in pty_output and "recovery" in pty_output.lower() + print("terminal warning printed after quit:", check7) + if not check7: + print("--- captured output tail ---") + print(pty_output[-800:]) + ok &= check7 + + finally: + if child and child.isalive(): + child.terminate(force=True) + try: + server.stop() + except Exception: + pass + shutil.rmtree(tmpdir, ignore_errors=True) + + print("\nPASS" if ok else "\nFAIL") + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-joe/test_real_disconnect_pty.py b/hd-joe/test_real_disconnect_pty.py new file mode 100644 index 0000000..0f81fb0 --- /dev/null +++ b/hd-joe/test_real_disconnect_pty.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""A genuine transport-level disconnect (server calls sio.disconnect(sid), +not just a shutdown()) forced mid-session, through a real pty-driven JOE. +Confirms: the agent's own client detects it (checked via its log, since +verbose logging already includes "Socket.IO disconnected."), and -- +the actual point of this test -- JOE keeps working afterward: typing, +saving, and quitting cleanly, proving the new 'M' status-message command +doesn't crash or hang the editor when it arrives. +""" +import os +import shutil +import socket as socketmod +import sys +import tempfile +import threading +import time +from pathlib import Path + +import pexpect +import socketio +from werkzeug.serving import make_server + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common")) +from hd_core import Config, Cookies, State, NoteState, content_hash + +JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/repo/joe-patch/build/joe-4.8/joe/joe") +AGENT = str(Path(__file__).resolve().parent / "hd_joe_agent.py") + + +class DisconnectableFakeServer: + def __init__(self, port, initial_text): + self.text = initial_text + self.sid = None + self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") + + @self.sio.event + def connect(sid, environ, auth): + self.sid = sid + self.sio.emit("doc", {"str": self.text, "revision": 0, "clients": []}, to=sid) + + self.app = socketio.WSGIApp(self.sio) + self.srv = make_server("127.0.0.1", port, self.app, threaded=True) + self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) + + def start(self): + self.thread.start() + + def force_disconnect_client(self): + # A real server-initiated close, not shutting the whole server down + # -- reliably and promptly noticed by the client, unlike killing + # the whole listener (see test_offline_handling.py's docstring for + # why that one wasn't reliable within a short test timeout). + if self.sid: + self.sio.disconnect(self.sid) + + def stop(self): + self.srv.shutdown() + + +def free_port(): + s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return port + + +def main(): + port = free_port() + note_id = "n1" + initial_content = "---\ntitle: Masten\ntags: sl6cv\n---\n\nbase content" + server = DisconnectableFakeServer(port, initial_content) + server.start() + time.sleep(0.2) + + tmpdir = Path(tempfile.mkdtemp(prefix="hd-real-disconnect-test-")) + root = tmpdir / "notes" + hd_dir = root / ".hd" + (hd_dir / "notes").mkdir(parents=True) + Config(url=f"http://127.0.0.1:{port}", email=None).save(hd_dir) + Cookies(header="session=1").save(hd_dir) + state = State() + (hd_dir / "notes" / f"{note_id}.md").write_text(initial_content) + state.notes[note_id] = NoteState( + title="Masten", tags=["sl6cv"], symlinks={"sl6cv": "Masten"}, + content_hash=content_hash(initial_content), last_seen_time=1, + ) + state.save(hd_dir) + tag_dir = root / "sl6cv" + tag_dir.mkdir(parents=True) + (tag_dir / "Masten").symlink_to(Path("..") / ".hd" / "notes" / f"{note_id}.md") + + ok = True + child = None + try: + log_path = "/tmp/hd-joe-real-disconnect.log" + try: + os.remove(log_path) + except OSError: + pass + + cmd = f'python3 {AGENT} "Masten" --joe {JOE_BIN} --log {log_path} --debug' + env = {**os.environ, "TERM": "xterm", "HD_DRAIN_TIMEOUT": "2.0"} + child = pexpect.spawn(cmd, cwd=str(tag_dir), env=env, dimensions=(24, 80), timeout=15) + time.sleep(1.0) + + # Force a REAL server-initiated disconnect mid-session -- this is + # what actually triggers _on_disconnect -> on_connection_state_changed + # -> Agent.send_message("M ...") being sent to JOE for real. + server.force_disconnect_client() + time.sleep(1.0) + + # JOE must still be alive and responsive -- if the M command (or + # anything about handling the disconnect) crashed or hung it, this + # is where that would show up. + check1 = child.isalive() + print("JOE still alive after the disconnect + M command:", check1) + ok &= check1 + + child.send("\x0bv") # EOF + time.sleep(0.3) + child.send(" still typable after disconnect") + time.sleep(0.5) + + child.send("\x0bx") + time.sleep(0.4) + child.send("\r") + try: + child.expect(pexpect.EOF, timeout=10) + except pexpect.TIMEOUT: + pass + rc = child.wait() if not child.isalive() else None + if child.isalive(): + child.terminate(force=True) + time.sleep(0.3) + + check2 = rc == 0 or rc is None # pexpect reports None if already reaped; either is a clean exit here + print("agent exited cleanly after the disconnect:", check2, "rc=", rc) + ok &= check2 + + log_text = Path(log_path).read_text() if Path(log_path).exists() else "" + check3 = "Socket.IO disconnected" in log_text + print("agent's own log confirms the disconnect was detected:", check3) + ok &= check3 + + finally: + if child and child.isalive(): + child.terminate(force=True) + try: + server.stop() + except Exception: + pass + shutil.rmtree(tmpdir, ignore_errors=True) + + print("\nPASS" if ok else "\nFAIL") + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd-joe/test_shadow_text_sync.py b/hd-joe/test_shadow_text_sync.py new file mode 100644 index 0000000..62a30f6 --- /dev/null +++ b/hd-joe/test_shadow_text_sync.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Unit test for a bug found while tracing through the offline scenario: +Agent.handle_local() used to only update self._shadow_text on the success +path. But send_operation() (hd_client.py) already updates +client.document.text optimistically BEFORE attempting to send -- so when +sending raises (offline, or any other reason), document.text has already +moved but _shadow_text hadn't, until this was moved into a `finally`. +Left unfixed, the NEXT remote operation would get translated into JOE IPC +commands against a stale baseline -- a buffer-corruption risk, not just a +lost-edit one. + +No real client/server needed: a minimal fake client that reproduces +exactly the one behavior this test cares about (document.text updates, +THEN the call raises) is enough, and keeps this fast and deterministic. +""" +import sys +from pathlib import Path +from types import SimpleNamespace + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import hd_joe_agent + +PASS = [] +FAIL = [] + + +def check(name, cond, detail=""): + if cond: + PASS.append(name) + else: + FAIL.append((name, detail)) + print(f"FAIL: {name} {detail}") + + +class FakeClient: + """Reproduces hd_client.HedgeDocClient.send_operation()'s real behavior + just enough for this test: document.text updates optimistically, THEN + the call raises -- exactly the order that made _shadow_text go stale.""" + + def __init__(self, text): + self.document = SimpleNamespace(text=text) + self.on_remote_operation_detail = None + self.on_connection_state_changed = None + + def insert(self, cp, inserted): + t = self.document.text + self.document.text = t[:cp] + inserted + t[cp:] + raise ConnectionError("simulated: send failed after the local buffer already moved") + + def send_operation(self, op): + raise ConnectionError("simulated: send failed") + + +def main(): + client = FakeClient("hello world") + agent = hd_joe_agent.Agent(client, sock_path=Path("/tmp/unused.sock"), buffer_path=Path("/tmp/unused.md")) + + # "hi " inserted at position 0 -> "hi hello world", hex-encoded per the + # real wire format JOE -> agent uses. + hexpayload = "hi ".encode("utf-8").hex() + agent.handle_local(f"I 0 {hexpayload}") + + check("the fake client's optimistic insert happened despite the raise", + client.document.text == "hi hello world", client.document.text) + check("_shadow_text was updated to match, via the finally block, even though insert() raised", + getattr(agent, "_shadow_text", None) == client.document.text, + (getattr(agent, "_shadow_text", None), client.document.text)) + + print(f"\n{len(PASS)} passed, {len(FAIL)} failed") + return 0 if not FAIL else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/hd_common/README.md b/hd_common/README.md new file mode 100644 index 0000000..509702d --- /dev/null +++ b/hd_common/README.md @@ -0,0 +1,40 @@ +# hd_common + +Code shared between `../hd-cli/` and `../hd-joe/`. Not a package in its +own right -- both entry points (`hd-cli/hdc`, `hd-joe/hd_joe_agent.py`) add +this directory to `sys.path` at startup based on their own file location, +so it works regardless of current directory or how you invoke them. Test +files in both packages do the same. + +If you add a new entry point or test file here, copy that same bootstrap +rather than assuming cwd: + +```python +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common")) +``` + +## Files + +| File | | +| --- | --- | +| `hd_client.py` | The OT engine: Socket.IO client, operation builders (`insert_operation`/`replace_operation`/`append_operation`, all careful to never emit a literal `0` component -- real HedgeDoc's `TextOperation.fromJSON` rejects those), transform, the pending-operation queue and its drain-before-exit logic. | +| `hd_core.py` | Everything else: `.hd/` config and cookie storage, `/history`-based discovery, reconciliation (symlinks <-> tags), problem detection, tag writing (`write_tags`, frontmatter parsing matched exactly to HedgeDoc's `splitFrontmatter`), and hd-joe's folder-discovery/create-or-open logic (`find_hd_root`, `tag_from_cwd`, `create_note`, `resolve_or_create_note`). | + +## Why this folder exists + +Until 0.7.19, both packages shipped their own copy of these two files. +They drifted once already (0.7.18's consistency pass found hd-cli's copy +missing the hd-joe integration functions hd-joe's copy already had) -- +silently, since nothing checked. One copy in one place removes the +possibility. + +## Tests + +No tests live here directly -- both packages' test suites already cover +this module thoroughly (hd-cli: `test_hd_core.py`, `test_hd_tags.py`, +`test_hd_problems.py`, `test_hd_write.py`; hd-joe: `test_hd_create.py`, +plus the pty-driven ones exercising `hd_client.py` against real JOE). +Changing something here means running both packages' suites, not just one +-- `../build.sh && ../install.sh` followed by the test commands in each +package's own README, or see the top-level README's test-everything +section. diff --git a/hd_common/hd_client.py b/hd_common/hd_client.py new file mode 100644 index 0000000..29a9a9d --- /dev/null +++ b/hd_common/hd_client.py @@ -0,0 +1,714 @@ +#!/usr/bin/env python3 +"""PicoCalc HedgeDoc client 0.5.4. + +HedgeDoc transport + text OT client. 0.5 adds a real local operation queue +and pairwise operational transformation for concurrent edits. + +Wire format confirmed for HedgeDoc 1.x: + client -> server: operation(base_revision, operation, selection) + server -> sender: ack(new_revision) + server -> peers: operation(client_id, new_revision, operation, selection, id) +""" + +from __future__ import annotations + +import logging +import threading +from urllib.request import Request, urlopen +from urllib.parse import quote +from dataclasses import dataclass, field +from typing import Any, Callable, Optional + +import socketio + + +logger = logging.getLogger("picocalc.hd") + + +Operation = list[Any] + + +def normalize_operation(op: Any) -> Operation: + if not isinstance(op, list): + raise TypeError(f"operation must be a list, got {type(op).__name__}") + return op + + +def utf16_len(text: str) -> int: + """Return JavaScript/CodeMirror string length (UTF-16 code units).""" + return len(text.encode("utf-16-le")) // 2 + + +def utf16_to_char_index(text: str, units: int) -> int: + """Convert a UTF-16 code-unit offset to a Python character index.""" + if units < 0: + raise ValueError("negative UTF-16 offset") + total = utf16_len(text) + if units > total: + raise ValueError(f"UTF-16 offset {units} exceeds document length {total}") + if units == 0: + return 0 + raw = text.encode("utf-16-le") + cut = units * 2 + try: + prefix = raw[:cut].decode("utf-16-le") + except UnicodeDecodeError as exc: + raise ValueError(f"UTF-16 offset {units} splits a surrogate pair") from exc + return len(prefix) + + +def apply_operation(text: str, op: Operation) -> str: + """Apply HedgeDoc/ot.js operations, whose lengths are UTF-16 units.""" + result: list[str] = [] + pos_units = 0 + doc_units = utf16_len(text) + for component in normalize_operation(op): + if isinstance(component, bool): + raise TypeError(f"unsupported operation component: {component!r}") + if isinstance(component, int): + if component >= 0: + end_units = pos_units + component + if end_units > doc_units: + raise ValueError(f"retain {component} exceeds document length") + a = utf16_to_char_index(text, pos_units) + b = utf16_to_char_index(text, end_units) + result.append(text[a:b]) + pos_units = end_units + else: + count = -component + end_units = pos_units + count + if end_units > doc_units: + raise ValueError(f"delete {count} exceeds document length") + utf16_to_char_index(text, end_units) + pos_units = end_units + elif isinstance(component, str): + result.append(component) + else: + raise TypeError(f"unsupported operation component: {component!r}") + if pos_units != doc_units: + raise ValueError( + f"operation did not consume document: consumed {pos_units}, len={doc_units}" + ) + return "".join(result) + + +def _op_length(component: Any) -> int: + if isinstance(component, bool): + raise TypeError("bool is not a valid OT component") + if isinstance(component, int): + return abs(component) + if isinstance(component, str): + return utf16_len(component) + raise TypeError(f"unsupported operation component: {component!r}") + + +def _append_component(out: Operation, component: Any) -> None: + if component == 0 or component == "": + return + if isinstance(component, int) and out and isinstance(out[-1], int): + # Retains and deletes must never merge with each other. + if (component >= 0) == (out[-1] >= 0): + out[-1] += component + return + if isinstance(component, str) and out and isinstance(out[-1], str): + out[-1] += component + return + out.append(component) + + +class _OpIter: + def __init__(self, op: Operation): + self.components = list(op) + self.index = 0 + self.offset = 0 + + def done(self) -> bool: + return self.index >= len(self.components) + + def component(self) -> Any: + if self.done(): + raise IndexError("operation exhausted") + return self.components[self.index] + + def remaining(self) -> int: + return _op_length(self.component()) - self.offset + + def take(self, n: int) -> Any: + if n <= 0 or self.done(): + raise ValueError("invalid OT iterator take") + c = self.component() + start = self.offset + end = start + n + if isinstance(c, int): + if c >= 0: + piece: Any = n + else: + piece = -n + else: + piece = c[start:end] + self.offset = end + if self.offset == _op_length(c): + self.index += 1 + self.offset = 0 + return piece + + +def transform_operations(a: Operation, b: Operation) -> tuple[Operation, Operation]: + """Transform two concurrent text operations. + + Returns (a', b') where: + apply(apply(S, a), b') == apply(apply(S, b), a') + + Same-position inserts are ordered deterministically in favour of ``a``. + This matches the usual ot.js-style left/right tie-break behaviour and is + enough for convergence between clients using the same transform. + """ + ia = _OpIter(normalize_operation(a)) + ib = _OpIter(normalize_operation(b)) + ap: Operation = [] + bp: Operation = [] + + while not ia.done() or not ib.done(): + if not ia.done() and isinstance(ia.component(), str): + s = ia.take(ia.remaining()) + _append_component(ap, s) + _append_component(bp, len(s)) + continue + + if not ib.done() and isinstance(ib.component(), str): + s = ib.take(ib.remaining()) + _append_component(ap, len(s)) + _append_component(bp, s) + continue + + if ia.done() or ib.done(): + raise ValueError("concurrent operations have different input lengths") + + n = min(ia.remaining(), ib.remaining()) + ca = ia.component() + cb = ib.component() + a_piece = ia.take(n) + b_piece = ib.take(n) + + if isinstance(ca, int) and isinstance(cb, int): + if ca >= 0 and cb >= 0: + _append_component(ap, n) + _append_component(bp, n) + elif ca < 0 and cb >= 0: + _append_component(ap, -n) + elif ca >= 0 and cb < 0: + _append_component(bp, -n) + else: + # Both delete the same source characters. + pass + else: + raise TypeError("invalid OT component pair") + + return ap, bp + + +def append_operation(text: str, inserted: str) -> Operation: + n = utf16_len(text) + return [inserted] if n == 0 else [n, inserted] + + +def insert_operation(text: str, pos: int, inserted: str) -> Operation: + if not 0 <= pos <= len(text): + raise ValueError("insert position outside document") + pos_u = utf16_len(text[:pos]) + tail_u = utf16_len(text) - pos_u + op: Operation = [] + if pos_u: + op.append(pos_u) + op.append(inserted) + if tail_u: + op.append(tail_u) + return op + + +def replace_operation(text: str, start: int, end: int, replacement: str) -> Operation: + if not 0 <= start <= end <= len(text): + raise ValueError("replace range outside document") + start_u = utf16_len(text[:start]) + end_u = utf16_len(text[:end]) + tail_u = utf16_len(text) - end_u + op: Operation = [] + if start_u: + op.append(start_u) + if end_u - start_u: + op.append(-(end_u - start_u)) + if replacement: + op.append(replacement) + if tail_u: + op.append(tail_u) + return op + + +@dataclass +class PendingOperation: + base_revision: int + operation: Operation + selection: dict[str, Any] + + +@dataclass +class HedgeDocDocument: + text: str = "" + revision: int = 0 + selection: Optional[dict[str, Any]] = None + clients: list[Any] = field(default_factory=list) + remote_selections: dict[str, Optional[dict[str, Any]]] = field(default_factory=dict) + last_operation_id: Optional[str] = None + last_operation_client: Optional[str] = None + + +class RevisionMismatch(RuntimeError): + pass + + +class HedgeDocClient: + def __init__( + self, + url: str, + note_id: str, + cookie: Optional[str] = None, + *, + verbose: bool = True, + on_remote_operation: Optional[Callable[[HedgeDocDocument], None]] = None, + on_remote_operation_detail: Optional[Callable[[HedgeDocDocument, Operation], None]] = None, + on_ack: Optional[Callable[[int], None]] = None, + on_connection_state_changed: Optional[Callable[[bool], None]] = None, + ): + self.url = url.rstrip("/") + self.note_id = note_id + self.cookie = cookie + self.verbose = verbose + self.on_remote_operation = on_remote_operation + self.on_remote_operation_detail = on_remote_operation_detail + self.on_ack = on_ack + # Called with True on connect, False on disconnect -- the ONLY thing + # send_operation()/_emit_pending() do differently when offline is + # nothing: they still optimistically update local state and queue + # the operation (that's why local editing keeps working while + # offline), then _emit_pending()'s sio.emit() raises BadNamespaceError + # since python-socketio refuses to emit on a disconnected client -- + # and nothing here resends a queued operation on reconnect. This + # hook exists so a caller (Agent) can at least make that visible + # instead of it being silent until someone notices data never + # arrived on the server. + self.on_connection_state_changed = on_connection_state_changed + + self.sio = socketio.Client(logger=False, engineio_logger=False) + self.document = HedgeDocDocument() + self._ready = threading.Event() + self._lock = threading.RLock() + self._connect_error: Optional[BaseException] = None + self._pending: list[PendingOperation] = [] + self._seen_operation_ids: set[str] = set() + + self.sio.on("doc", self._on_doc) + self.sio.on("operation", self._on_operation) + self.sio.on("ack", self._on_ack) + self.sio.on("selection", self._on_selection) + self.sio.on("cursor focus", self._on_cursor_focus) + self.sio.on("cursor activity", self._on_cursor_activity) + self.sio.on("cursor blur", self._on_cursor_blur) + self.sio.on("*", self._on_any_event) + self.sio.on("connect", self._on_connect) + self.sio.on("disconnect", self._on_disconnect) + self.sio.on("connect_error", self._on_connect_error) + + @property + def pending_count(self) -> int: + with self._lock: + return len(self._pending) + + def _snapshot(self) -> HedgeDocDocument: + return HedgeDocDocument( + text=self.document.text, + revision=self.document.revision, + selection=self.document.selection, + clients=list(self.document.clients), + remote_selections=dict(self.document.remote_selections), + last_operation_id=self.document.last_operation_id, + last_operation_client=self.document.last_operation_client, + ) + + def _on_connect(self): + if self.verbose: + logger.info("Socket.IO connected.") + if self.on_connection_state_changed: + self.on_connection_state_changed(True) + + def _on_disconnect(self): + if self.verbose: + logger.info("Socket.IO disconnected.") + if self.on_connection_state_changed: + self.on_connection_state_changed(False) + + def _on_connect_error(self, data): + self._connect_error = RuntimeError(f"connect_error: {data!r}") + self._ready.set() + if self.verbose: + logger.error("Socket.IO connect error: %r", data) + + def _on_doc(self, *args): + if not args: + return + payload = args[0] + if isinstance(payload, dict): + text = payload.get("str", payload.get("text", "")) + revision = payload.get("revision", 0) + clients = payload.get("clients", []) + else: + text = payload + revision = args[1] if len(args) > 1 else 0 + clients = args[2] if len(args) > 2 else [] + if not isinstance(text, str): + raise TypeError(f"doc text must be str, got {type(text).__name__}") + revision = int(revision) + with self._lock: + # HedgeDoc may emit another ``doc`` snapshot while a local + # operation is already optimistic/pending. That snapshot can be + # the pre-operation document at the same revision. Replacing our + # optimistic text here would move the editor backwards and make a + # perfectly valid EOF byte position look outside the document. + # The operation/ack stream is authoritative once local edits are + # pending, so keep the optimistic state until those operations have + # been acknowledged. + if self._pending: + if self.verbose: + logger.info( + "Ignoring doc snapshot while local operations are pending: " + "snapshot_revision=%d local_revision=%d pending=%d", + revision, self.document.revision, len(self._pending), + ) + return + if revision < self.document.revision: + if self.verbose: + logger.info( + "Ignoring stale doc snapshot: revision=%d local_revision=%d", + revision, self.document.revision, + ) + return + self.document.text = text + self.document.revision = revision + self.document.clients = clients if isinstance(clients, list) else [] + self.document.remote_selections.clear() + self.document.last_operation_id = None + self.document.last_operation_client = None + if self.verbose: + logger.info("Document loaded. revision=%d length=%d", revision, len(text)) + self._ready.set() + + def _on_ack(self, *args): + if not args: + logger.error("Malformed ack event: no arguments") + return + revision = args[0] + if isinstance(revision, (list, tuple)) and len(revision) == 1: + revision = revision[0] + try: + revision = int(revision) + except (TypeError, ValueError): + logger.error("Invalid ack revision: %r", revision) + return + + send_next: Optional[PendingOperation] = None + with self._lock: + if not self._pending: + if revision > self.document.revision: + self.document.revision = revision + callback_revision = self.document.revision + else: + pending = self._pending[0] + expected = pending.base_revision + 1 + if revision != expected: + # ACKs identify the server revision of that local op. It + # can arrive after peer broadcasts, so never roll the + # visible revision backwards. + if revision > self.document.revision or revision < pending.base_revision: + logger.error("Unexpected ACK revision: got %s, expected %s", revision, expected) + return + self._pending.pop(0) + self.document.revision = max(self.document.revision, revision) + self.document.selection = pending.selection + callback_revision = self.document.revision + if self._pending: + next_op = self._pending[0] + next_op.base_revision = self.document.revision + send_next = next_op + + if self.verbose: + logger.info( + "ACK received. server revision=%s; local revision=%s; pending=%s", + revision, callback_revision, self.pending_count + ) + if send_next is not None: + self._emit_pending(send_next) + if self.on_ack: + self.on_ack(callback_revision) + + def _fetch_current_document(self) -> Optional[str]: + """Fetch the server's current markdown when OT state is inconsistent.""" + url = f"{self.url}/{quote(self.note_id, safe='')}/download" + req = Request(url, headers={"Accept": "text/markdown"}) + if self.cookie: + req.add_header("Cookie", self.cookie) + try: + with urlopen(req, timeout=10) as response: + data = response.read() + return data.decode("utf-8") + except Exception as exc: + logger.error("Could not resync document from %s: %s", url, exc) + return None + + def _resync_after_operation_mismatch( + self, + old_text: str, + new_revision: int, + client_id: str, + operation_id: Optional[str], + ) -> Optional[Operation]: + """Recover when an incoming OT op does not match our local text. + + This is deliberately only used with no optimistic local operations. + In that state the server operation is the next authoritative state, so + fetching the current note and replacing our local snapshot is safer + than guessing how to transform a malformed/divergent operation. + """ + if self._pending: + logger.error( + "Cannot resync safely while %d local operation(s) are pending.", + len(self._pending), + ) + return None + + # This is a genuine last resort (apply_operation already raised), but + # it has the same DB-lag exposure as the removed large_delete + # shortcut above -- /download can still be stale here. A short + # delay past HedgeDoc's 1s dirty-flush interval trades latency (on + # an already-rare error path) for a much better chance of reading + # post-operation content instead of pre-operation content. + import time + time.sleep(1.2) + server_text = self._fetch_current_document() + if server_text is None: + return None + + replacement: Operation + if old_text: + replacement = [0, -utf16_len(old_text), server_text] + else: + replacement = [server_text] + + self.document.text = server_text + self.document.revision = new_revision + self.document.last_operation_id = operation_id + self.document.last_operation_client = client_id + if operation_id is not None: + self._seen_operation_ids.add(operation_id) + snapshot = self._snapshot() + + logger.warning( + "Resynced document after OT mismatch: revision=%s old_length=%d new_length=%d", + new_revision, len(old_text), len(server_text), + ) + if self.on_remote_operation: + self.on_remote_operation(snapshot) + if self.on_remote_operation_detail: + self.on_remote_operation_detail(snapshot, replacement) + return replacement + + def _on_operation(self, *args): + if len(args) < 5: + logger.error("Malformed operation event: %r", args) + return + client_id, new_revision, operation, selection, operation_id = args[:5] + if not isinstance(client_id, str): + logger.error("Invalid operation client_id: %r", client_id) + return + try: + new_revision = int(new_revision) + operation = normalize_operation(operation) + except (TypeError, ValueError) as exc: + logger.error("Invalid operation event: %s", exc) + return + if operation_id is not None and not isinstance(operation_id, str): + operation_id = str(operation_id) + + with self._lock: + if operation_id is not None and operation_id in self._seen_operation_ids: + return + local_revision = self.document.revision + if new_revision != local_revision + 1: + logger.error( + "Revision mismatch: incoming NEW revision %s != local revision + 1 (%s)", + new_revision, local_revision + 1, + ) + logger.error("Resync/get_operations is required.") + return + + # NOTE: a "large delete -> fetch authoritative markdown via HTTP + # download" shortcut used to live here. Removed: HedgeDoc's + # /download route reads note.content from the DB, which is only + # flushed from the live realtime document on a 1-second dirty + # timer (lib/realtime.js: setInterval(..., 1000) + isDirty + # check). Fetching immediately after receiving this exact + # operation races that timer and can return content from BEFORE + # this operation was applied -- e.g. an AI integration's + # placeholder text ("Thinking...") instead of its real answer, + # applied as if it were authoritative and never corrected. There + # was never a real need for this shortcut: apply_operation and + # transform_operations don't care about operation size. + + # Transform the peer operation through every optimistic local + # operation. Each local op is also transformed against the + # remaining peer op, preserving the visible local edits. + remote = list(operation) + for pending in self._pending: + local_prime, remote_prime = transform_operations(pending.operation, remote) + pending.operation = local_prime + remote = remote_prime + + old_text = self.document.text + snapshot_already_delivered = False + try: + self.document.text = apply_operation(old_text, remote) + except (TypeError, ValueError) as exc: + logger.error("Could not apply transformed remote operation: %s", exc) + logger.error("Original operation: %r", operation) + logger.error("Transformed operation: %r", remote) + # Large server-side replacements (for example an AI agent + # rewriting an Agent block) can expose a pre-existing local + # document-length divergence. When no local edit is pending, + # recover from HedgeDoc's authoritative markdown instead of + # dropping the operation and leaving JOE stale. + resynced = self._resync_after_operation_mismatch( + old_text, new_revision, client_id, operation_id + ) + if resynced is None: + return + remote = resynced + snapshot = self._snapshot() + snapshot_already_delivered = True + else: + self.document.revision = new_revision + self.document.last_operation_id = operation_id + self.document.last_operation_client = client_id + if operation_id is not None: + self._seen_operation_ids.add(operation_id) + snapshot = self._snapshot() + + self.document.remote_selections[client_id] = ( + selection if isinstance(selection, dict) else None + ) + snapshot = self._snapshot() + + if self.verbose: + logger.info( + "Remote operation applied+transformed: client=%s revision=%s -> %s id=%r op=%r pending=%s", + client_id, local_revision, new_revision, operation_id, operation, self.pending_count + ) + if not snapshot_already_delivered: + if self.on_remote_operation: + self.on_remote_operation(snapshot) + if self.on_remote_operation_detail: + self.on_remote_operation_detail(snapshot, remote) + + def _on_selection(self, *args): + if len(args) >= 2 and isinstance(args[0], str): + with self._lock: + self.document.remote_selections[args[0]] = ( + args[1] if isinstance(args[1], dict) else None + ) + if self.verbose: + logger.info("Event 'selection': %r", args) + + def _on_cursor_focus(self, *args): + if self.verbose: + logger.info("Event 'cursor focus': %r", args) + + def _on_cursor_activity(self, *args): + if self.verbose: + logger.info("Event 'cursor activity': %r", args) + + def _on_cursor_blur(self, *args): + if self.verbose: + logger.info("Event 'cursor blur': %r", args) + + def _on_any_event(self, event, *args): + known = {"doc", "operation", "ack", "selection", "cursor focus", "cursor activity", "cursor blur"} + if self.verbose and event not in known: + logger.info("Event %r: %r", event, args) + + def connect(self, headers: Optional[dict[str, str]] = None): + from urllib.parse import urlencode + connect_url = f"{self.url}/?{urlencode({'noteId': self.note_id})}" + merged_headers = dict(headers or {}) + if self.cookie: + merged_headers["Cookie"] = self.cookie + self.sio.connect( + connect_url, + socketio_path="socket.io", + headers=merged_headers or None, + transports=["websocket", "polling"], + wait_timeout=10, + ) + + def wait_ready(self, timeout: float = 10.0) -> HedgeDocDocument: + if not self._ready.wait(timeout): + raise TimeoutError("Timed out waiting for HedgeDoc doc event.") + if self._connect_error: + raise self._connect_error + with self._lock: + return self._snapshot() + + def _emit_pending(self, pending: PendingOperation): + self.sio.emit("operation", (pending.base_revision, pending.operation, pending.selection)) + if self.verbose: + logger.info("Sent operation at base revision=%s: %r", pending.base_revision, pending.operation) + + def send_operation(self, operation: Operation, selection: Optional[dict[str, Any]] = None): + selection = selection or {"ranges": []} + with self._lock: + base_revision = self.document.revision if not self._pending else self._pending[-1].base_revision + # Validate against the currently visible document before changing it. + new_text = apply_operation(self.document.text, operation) + pending = PendingOperation(base_revision, list(operation), selection) + was_empty = not self._pending + self._pending.append(pending) + self.document.text = new_text + self.document.selection = selection + if was_empty: + self._emit_pending(pending) + elif self.verbose: + logger.info("Buffered local operation; pending=%s", self.pending_count) + + def append(self, inserted: str, selection: Optional[dict[str, Any]] = None): + with self._lock: + operation = append_operation(self.document.text, inserted) + new_length = utf16_len(self.document.text) + utf16_len(inserted) + if selection is None: + selection = {"ranges": [{"anchor": new_length, "head": new_length}]} + self.send_operation(operation, selection) + + def insert(self, pos: int, inserted: str, selection: Optional[dict[str, Any]] = None): + with self._lock: + operation = insert_operation(self.document.text, pos, inserted) + new_pos = utf16_len(self.document.text[:pos]) + utf16_len(inserted) + if selection is None: + selection = {"ranges": [{"anchor": new_pos, "head": new_pos}]} + self.send_operation(operation, selection) + + def replace(self, start: int, end: int, replacement: str, selection: Optional[dict[str, Any]] = None): + with self._lock: + operation = replace_operation(self.document.text, start, end, replacement) + new_pos = utf16_len(self.document.text[:start]) + utf16_len(replacement) + if selection is None: + selection = {"ranges": [{"anchor": new_pos, "head": new_pos}]} + self.send_operation(operation, selection) + + def close(self): + if self.sio.connected: + self.sio.disconnect() diff --git a/hd_common/hd_core.py b/hd_common/hd_core.py new file mode 100644 index 0000000..19d7f3e --- /dev/null +++ b/hd_common/hd_core.py @@ -0,0 +1,1111 @@ +"""Core logic for `hd`: the HedgeDoc <-> local-filesystem tag mirror. + +Read half: discover notes via /history, cache their content under +.hd/notes/<id>.md, and reconcile one symlink per tag under <root>/<tag>/. +Write half: `hd tag`/`hd untag` push a real frontmatter edit back to +HedgeDoc over the realtime channel (there is no plain HTTP save endpoint +for existing notes). Both halves share one real interprocess lock +(ReconcileLock, backed by flock) so a sync pass and a tag write can never +step on each other's state.json/symlink updates. +""" +from __future__ import annotations + +import fcntl +import hashlib +import http.cookiejar +import json +import logging +import os +import re +import stat +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Optional + +import yaml as pyyaml + +from hd_client import HedgeDocClient + +logger = logging.getLogger("hd") + +CONFIG_NAME = "config.json" +COOKIES_NAME = "cookies.json" +STATE_NAME = "state.json" +NOTES_DIRNAME = "notes" +UNTAGGED = "untagged" +RECONCILE_LOCK_NAME = ".reconciling.lock" +LOCK_FILE_NAME = ".lock" +PROBLEMS_NAME = "problems.json" + + +# -------------------------------------------------------------------------- +# Config (~/notes/.hd/config.json) -- server URL and, if a login (rather +# than a pasted cookie) was used, the email address, kept only so a future +# re-login can prompt with it prefilled. No password is ever written here. +# -------------------------------------------------------------------------- + +@dataclass +class Config: + url: str + email: Optional[str] = None + + @staticmethod + def load(hd_dir: Path) -> "Config": + path = hd_dir / CONFIG_NAME + data = json.loads(path.read_text(encoding="utf-8")) + return Config(url=data["url"], email=data.get("email")) + + def save(self, hd_dir: Path) -> None: + path = hd_dir / CONFIG_NAME + path.write_text( + json.dumps({"url": self.url, "email": self.email}, indent=2), + encoding="utf-8", + ) + os.chmod(path, stat.S_IRUSR | stat.S_IWUSR) # 0600 + + +# -------------------------------------------------------------------------- +# Cookies (~/notes/.hd/cookies.json) -- kept separate from config.json: +# this is the actually-sensitive credential (a live session token, as good +# as a password for as long as it's valid), config.json is not. Mode 0600. +# -------------------------------------------------------------------------- + +@dataclass +class Cookies: + header: str # a ready-to-send "k1=v1; k2=v2" Cookie header value + + @staticmethod + def load(hd_dir: Path) -> "Cookies": + path = hd_dir / COOKIES_NAME + data = json.loads(path.read_text(encoding="utf-8")) + return Cookies(header=data["cookie"]) + + def save(self, hd_dir: Path) -> None: + path = hd_dir / COOKIES_NAME + path.write_text(json.dumps({"cookie": self.header}, indent=2), encoding="utf-8") + os.chmod(path, stat.S_IRUSR | stat.S_IWUSR) # 0600 + + +class LoginError(RuntimeError): + pass + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + """We only care about the Set-Cookie header on the /login response + itself -- not whatever page it redirects to, which may not even exist + from this script's point of view. Suppressing redirect-following avoids + a working login being misread as a failure just because the redirect + target 404s or requires a browser session HedgeDoc doesn't expect a + plain HTTP client to have (e.g. CSRF-protected pages).""" + + def redirect_request(self, *args, **kwargs): + return None + + +def login(url: str, email: str, password: str, timeout: float = 15.0) -> str: + """POST email+password to HedgeDoc's local-auth /login and return a + Cookie header string for the resulting session. + + /login always responds 302 (a browser-form flow with flash messages, + not a JSON API) whether the credentials were right or wrong, so success + can't be read off the status code. This does the only reliable thing: + perform the login, then immediately probe /history with whatever + cookies came back. If that 403s, the credentials were rejected. + + The session cookie's NAME is deliberately not assumed (default is + 'connect.sid' but it's a per-deployment config option) -- whatever the + session middleware actually set is what gets captured and reused. + """ + url = url.rstrip("/") + jar = http.cookiejar.CookieJar() + opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar), _NoRedirect()) + body = urllib.parse.urlencode({"email": email, "password": password}).encode("ascii") + req = urllib.request.Request(f"{url}/login", data=body, method="POST", + headers={"Content-Type": "application/x-www-form-urlencoded"}) + try: + opener.open(req, timeout=timeout) + except urllib.error.HTTPError as exc: + # A 3xx here means our own handler declined to follow it -- that's + # the expected, successful case (cookie already landed in `jar`). + if not (300 <= exc.code < 400): + raise LoginError(f"Unexpected response from {url}/login: {exc.code} {exc.reason}") from exc + except urllib.error.URLError as exc: + raise LoginError(f"Could not reach {url}/login: {exc}") from exc + + header = "; ".join(f"{c.name}={c.value}" for c in jar if c.value is not None) + if not header: + raise LoginError( + "Login request completed but no session cookie was set -- is " + "email/password login enabled on this server? If it uses " + "LDAP/OAuth/SAML instead, use 'hdc init <url> --cookie ...' " + "with a cookie copied from your browser instead." + ) + + verify_req = urllib.request.Request(f"{url}/history", headers={"Cookie": header}) + try: + urllib.request.urlopen(verify_req, timeout=timeout) + except urllib.error.HTTPError as exc: + if exc.code in (401, 403): + raise LoginError("Login rejected -- wrong email or password.") from exc + raise LoginError(f"Login looked ok but /history returned {exc.code}: {exc.reason}") from exc + except urllib.error.URLError as exc: + raise LoginError(f"Could not verify login against {url}/history: {exc}") from exc + + return header + + +# -------------------------------------------------------------------------- +# State (~/notes/.hd/state.json) -- what the reconciler believes is true. +# The symlink name per tag is stored here, not re-derived from the title on +# every run: if it were re-derived, a title change would look exactly like +# "old symlink deleted, new symlink created" to a filesystem watcher, which +# is indistinguishable from a user-initiated untag+retag. Keeping the name +# pinned in state means only an actual title-change code path touches it. +# -------------------------------------------------------------------------- + +@dataclass +class NoteState: + title: str + tags: list[str] = field(default_factory=list) + symlinks: dict[str, str] = field(default_factory=dict) # tag -> filename + content_hash: Optional[str] = None + last_seen_time: Optional[int] = None # /history's `time` field, used to + # skip re-fetching /download when nothing has changed server-side. + tags_confirmed_stale_at: Optional[int] = None # set by + # update_note_tags_locally() to the /history `time` it knew was + # STALE (pre-write) at the moment of a direct tag update. reconcile() + # checks this: as long as /history's *current* time for this note + # still equals this value, /history hasn't caught up to the write yet + # (HedgeDoc's own DB-flush lag -- the same class of delay + # CHANGES-0.7.15 hit for content), so it skips recomputing this note's + # tags/symlinks rather than trusting a snapshot it already knows + # predates a confirmed write and clobbering the correct local result. + # Cleared (set back to None) once /history's time for this note + # actually moves past this value -- at that point /history has + # genuinely caught up, and its data (whatever it now says) is trusted + # again as normal. + + def to_json(self) -> dict[str, Any]: + return { + "title": self.title, + "tags": self.tags, + "symlinks": self.symlinks, + "content_hash": self.content_hash, + "last_seen_time": self.last_seen_time, + "tags_confirmed_stale_at": self.tags_confirmed_stale_at, + } + + @staticmethod + def from_json(d: dict[str, Any]) -> "NoteState": + return NoteState( + title=d.get("title", ""), + tags=list(d.get("tags", [])), + symlinks=dict(d.get("symlinks", {})), + content_hash=d.get("content_hash"), + last_seen_time=d.get("last_seen_time"), + tags_confirmed_stale_at=d.get("tags_confirmed_stale_at"), + ) + + +@dataclass +class State: + notes: dict[str, NoteState] = field(default_factory=dict) + + @staticmethod + def load(hd_dir: Path) -> "State": + path = hd_dir / STATE_NAME + if not path.exists(): + return State() + data = json.loads(path.read_text(encoding="utf-8")) + return State(notes={k: NoteState.from_json(v) for k, v in data.get("notes", {}).items()}) + + def save(self, hd_dir: Path) -> None: + path = hd_dir / STATE_NAME + tmp = path.with_suffix(".json.tmp") + payload = {"notes": {k: v.to_json() for k, v in self.notes.items()}} + tmp.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") + tmp.replace(path) # atomic on the same filesystem + + +# -------------------------------------------------------------------------- +# Filename sanitization +# -------------------------------------------------------------------------- + +_UNSAFE = re.compile(r"[\\/\x00-\x1f]") + + +def sanitize_title(title: str) -> str: + name = _UNSAFE.sub("_", title or "").strip().strip(".") + name = re.sub(r"\s+", " ", name) + if not name: + name = "untitled" + return name[:120] + + +def unique_name(base: str, id_hint: str, taken: set[str]) -> str: + """The note's title, deduped against `taken` (existing filenames in the + same tag folder) using a short, stable suffix from the note id -- never + a counter, so the same note always gets the same name regardless of + what order notes happen to be processed in. No .md extension: these are + symlinks named after the note's title, not files -- the thing that + actually needs a .md extension is the cache file in .hd/notes/, which + already has one.""" + if base not in taken: + return base + suffix = id_hint[-6:] if len(id_hint) >= 6 else id_hint + candidate = f"{base}-{suffix}" + if candidate not in taken: + return candidate + # Pathological: even the id-suffixed name collides (two different notes + # sharing a 6-char id suffix by coincidence). Fall back to the full id. + return f"{base}-{id_hint}" + + +# -------------------------------------------------------------------------- +# HTTP: /history (discovery) and /<id>/download (content) +# -------------------------------------------------------------------------- + +@dataclass +class HistoryEntry: + id: str + title: str + tags: list[str] + time: int + + +class HedgeDocSource: + """Thin HTTP client for the two read-only endpoints this tool needs. + Deliberately not the realtime Socket.IO client -- no live editing here.""" + + def __init__(self, url: str, cookie: str): + self.url = url.rstrip("/") + self.cookie = cookie + + def _get(self, path: str) -> bytes: + req = urllib.request.Request(f"{self.url}{path}", headers={"Cookie": self.cookie}) + with urllib.request.urlopen(req, timeout=15) as resp: + return resp.read() + + def fetch_history(self) -> list[HistoryEntry]: + try: + data = json.loads(self._get("/history").decode("utf-8")) + except urllib.error.HTTPError as exc: + raise RuntimeError( + f"GET /history failed: {exc.code} {exc.reason} -- " + "cookie likely expired; re-run 'hdc init' to log in again" + ) from exc + entries = [] + for item in data.get("history", []): + entries.append(HistoryEntry( + id=item["id"], + title=item.get("text") or "Untitled", + tags=list(item.get("tags") or []), + time=item.get("time", 0), + )) + return entries + + def fetch_content(self, note_id: str) -> str: + from urllib.parse import quote + raw = self._get(f"/{quote(note_id, safe='')}/download") + return raw.decode("utf-8") + + +def content_hash(text: str) -> str: + return "sha256:" + hashlib.sha256(text.encode("utf-8")).hexdigest() + + +# -------------------------------------------------------------------------- +# Reconciliation +# -------------------------------------------------------------------------- + +@dataclass +class ReconcileResult: + notes_updated: list[str] = field(default_factory=list) + notes_unchanged: list[str] = field(default_factory=list) + notes_removed: list[str] = field(default_factory=list) + symlinks_created: list[str] = field(default_factory=list) + symlinks_removed: list[str] = field(default_factory=list) + problems: list["Problem"] = field(default_factory=list) + + +# -------------------------------------------------------------------------- +# Konsistenskontroller: things the reconciler notices but can't safely fix +# on its own -- a directory where a tag symlink should be, a plain file +# where cp-without--P left one, a symlink pointing at nothing or at +# something outside .hd/notes/. Written to .hd/problems.json so hd-joe can +# print them at every startup without re-scanning the whole tree itself. +# -------------------------------------------------------------------------- + +@dataclass +class Problem: + kind: str # "nested_dir" | "stray_file" | "broken_symlink" | "foreign_symlink" + path: str # relative to root + detail: str = "" # e.g. matching note id(s) for a stray file, via checksum + + def to_json(self) -> dict[str, Any]: + return {"kind": self.kind, "path": self.path, "detail": self.detail} + + @staticmethod + def from_json(d: dict[str, Any]) -> "Problem": + return Problem(kind=d["kind"], path=d["path"], detail=d.get("detail", "")) + + def __str__(self) -> str: + messages = { + "nested_dir": f"{self.path}/ is a real directory where a tag symlink was expected " + f"(nested tag folders aren't supported)", + "stray_file": f"{self.path} is a plain file, not a symlink -- {self.detail}" + if self.detail else + f"{self.path} is a plain file, not a symlink, and its content doesn't " + f"match any known note (server-side edit since last sync, or not from hd at all)", + "broken_symlink": f"{self.path} points at a note that no longer exists in the cache", + "foreign_symlink": f"{self.path} is a symlink pointing outside .hd/notes/ -- created by hand?", + } + return messages.get(self.kind, f"{self.kind}: {self.path}") + + +def save_problems(hd_dir: Path, problems: list[Problem]) -> None: + path = hd_dir / PROBLEMS_NAME + tmp = path.with_suffix(".json.tmp") + tmp.write_text(json.dumps([p.to_json() for p in problems], indent=2, ensure_ascii=False), + encoding="utf-8") + tmp.replace(path) + + +def load_problems(hd_dir: Path) -> list[Problem]: + path = hd_dir / PROBLEMS_NAME + if not path.exists(): + return [] + return [Problem.from_json(d) for d in json.loads(path.read_text(encoding="utf-8"))] + + +def detect_problems(root: Path, state: State) -> list[Problem]: + """Walk every top-level entry under root (skipping .hd itself) and flag + anything that isn't a healthy symlink into .hd/notes/. Cheap: one level + of tag directories, one listdir each -- meant to run on every sync pass, + not just on demand.""" + hd_dir = root / ".hd" + notes_dir = hd_dir / NOTES_DIRNAME + problems: list[Problem] = [] + + # checksum -> note id, for identifying stray files + hash_to_id = {n.content_hash: nid for nid, n in state.notes.items() if n.content_hash} + + if not root.exists(): + return problems + + for tag_dir in sorted(root.iterdir()): + if tag_dir.name == ".hd" or not tag_dir.is_dir() or tag_dir.is_symlink(): + continue + for entry in sorted(tag_dir.iterdir()): + rel = str(entry.relative_to(root)) + if entry.is_symlink(): + target = entry.resolve() + if not target.exists(): + problems.append(Problem("broken_symlink", rel)) + elif notes_dir.resolve() not in target.parents: + problems.append(Problem("foreign_symlink", rel)) + # else: healthy, matches a note in .hd/notes/ -- nothing to flag + elif entry.is_dir(): + problems.append(Problem("nested_dir", rel)) + elif entry.is_file(): + try: + file_hash = content_hash(entry.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError): + file_hash = None + match = hash_to_id.get(file_hash) if file_hash else None + if match: + detail = (f"content matches note {match!r}, run " + f"'hdc tag {match} {tag_dir.name} --fix-stray {rel}' to replace it with the real symlink") + else: + detail = "" + problems.append(Problem("stray_file", rel, detail)) + return problems + + +class ReconcileLock: + """Real mutual exclusion (fcntl.flock on .hd/.lock) between hd sync and + hd tag/untag, so a pull-reconciliation and a tag write can never + interleave their state.json/symlink updates. Also writes the + human-readable .reconciling.lock marker (with a timestamp) for the + benefit of a future filesystem watcher, which needs to tell "the + reconciler just touched this" apart from "the user just touched this" -- + the same problem hd_ipc_applying() solves for JOE. Blocks (does not + fail fast) if another process holds it; every operation that takes this + lock is short-lived (a sync pass or a single tag write), so a bounded + wait is the right default over a race-prone "fail if busy". + """ + + def __init__(self, hd_dir: Path): + self.hd_dir = hd_dir + self.lock_path = hd_dir / LOCK_FILE_NAME + self.marker_path = hd_dir / RECONCILE_LOCK_NAME + self._fd = None + + def __enter__(self): + self.hd_dir.mkdir(parents=True, exist_ok=True) + self._fd = os.open(self.lock_path, os.O_CREAT | os.O_RDWR, 0o600) + fcntl.flock(self._fd, fcntl.LOCK_EX) # blocks until available + self.marker_path.write_text(str(time.time()), encoding="utf-8") + return self + + def __exit__(self, *exc): + try: + self.marker_path.unlink() + except FileNotFoundError: + pass + if self._fd is not None: + fcntl.flock(self._fd, fcntl.LOCK_UN) + os.close(self._fd) + self._fd = None + + +def _sync_note_symlinks( + root: Path, note_id: str, title: str, tags: list[str], + note_path: Path, old_symlinks: dict[str, str], title_changed: bool, +) -> tuple[dict[str, str], list[str], list[str]]: + """Create/remove symlinks so exactly one exists per tag in `tags` (or + UNTAGGED if empty), pointing at note_path. Returns + (new_symlinks, created_paths, removed_paths). + + Shared by reconcile() (tags come from /history, which can lag a live + write by a few seconds -- HedgeDoc's own DB-flush delay, the same + class of staleness CHANGES-0.7.15 hit for content) and + update_note_tags_locally() (tags come from a write_tags() call's own + return value instead, confirmed correct immediately -- sidesteps that + lag entirely for the note that was actually just changed). + """ + new_symlinks: dict[str, str] = {} + created: list[str] = [] + removed: list[str] = [] + effective_tags = tags if tags else [UNTAGGED] + + for tag in effective_tags: + tag_dir = root / tag + tag_dir.mkdir(parents=True, exist_ok=True) + existing_name = old_symlinks.get(tag) + if existing_name and not title_changed and (tag_dir / existing_name).is_symlink(): + new_symlinks[tag] = existing_name + continue + # New tag for this note, or title changed (rename), or the + # symlink is missing/broken -- (re)create it. + taken = {p.name for p in tag_dir.iterdir()} if tag_dir.exists() else set() + if existing_name: + taken.discard(existing_name) + name = unique_name(sanitize_title(title), note_id, taken) + target = os.path.relpath(note_path, tag_dir) + link_path = tag_dir / name + if existing_name and existing_name != name: + old_link = tag_dir / existing_name + if old_link.is_symlink(): + old_link.unlink() + removed.append(str(old_link)) + if link_path.is_symlink() or link_path.exists(): + link_path.unlink() + link_path.symlink_to(target) + new_symlinks[tag] = name + created.append(str(link_path)) + + # --- prune symlinks for tags this note no longer has --- + for tag, name in old_symlinks.items(): + if tag not in new_symlinks: + old_link = root / tag / name + if old_link.is_symlink(): + old_link.unlink() + removed.append(str(old_link)) + + return new_symlinks, created, removed + + +def update_note_tags_locally(hd_root: Path, note_id: str, new_tags: list[str]) -> bool: + """After write_tags() confirms a tag change, apply the resulting + symlink changes directly using that known-correct tag list -- instead + of relying on the next reconcile() pass, which reads tags from + /history and can see a stale (pre-write) list for a few seconds after + a successful write. Confirmed happening in practice: 'hdc untag' + immediately re-syncing via the normal path left a stale symlink in + place for several seconds after the write itself had already + succeeded. + + No-op (returns False) if the note isn't in state.json yet -- same + reasoning as update_note_cache(): nothing here can safely guess at + content or other metadata a real reconcile() pass would fill in from + an actual /history entry. Title is taken from what's already in + state.json (unaffected by a tag change), so this never invents one. + """ + hd_dir = hd_root / ".hd" + notes_dir = hd_dir / NOTES_DIRNAME + with ReconcileLock(hd_dir): + state = State.load(hd_dir) + ns = state.notes.get(note_id) + if ns is None: + return False + note_path = notes_dir / f"{note_id}.md" + old_symlinks = dict(ns.symlinks) + new_symlinks, _created, _removed = _sync_note_symlinks( + hd_root, note_id, ns.title, new_tags, note_path, old_symlinks, title_changed=False, + ) + # Matches reconcile()'s own convention (see its `tags = entry.tags + # if entry.tags else [UNTAGGED]`): state.json's tags list is never + # actually empty, an untagged note is recorded as [UNTAGGED] -- + # new_symlinks' keys are exactly that already-substituted list, + # since _sync_note_symlinks makes the same substitution internally. + ns.tags = list(new_symlinks.keys()) + ns.symlinks = new_symlinks + # Record the /history time we know is stale (pre-write) so + # reconcile() -- run immediately after this, still against + # possibly-unflushed /history -- doesn't clobber this correct + # result with an older snapshot it can recognize as older. See + # NoteState.tags_confirmed_stale_at's docstring for the full story + # (found the hard way: the first version of this fix worked in + # isolation but was silently undone by the very next reconcile() + # call in the same command). + ns.tags_confirmed_stale_at = ns.last_seen_time + state.save(hd_dir) + return True + + +def reconcile(root: Path, source: HedgeDocSource, state: State) -> ReconcileResult: + hd_dir = root / ".hd" + notes_dir = hd_dir / NOTES_DIRNAME + notes_dir.mkdir(parents=True, exist_ok=True) + result = ReconcileResult() + + with ReconcileLock(hd_dir): + history = source.fetch_history() + seen_ids = set() + + for entry in history: + seen_ids.add(entry.id) + prev = state.notes.get(entry.id) + tags = entry.tags if entry.tags else [UNTAGGED] + + # --- content cache --- + # /history's `time` field works as a cheap change indicator: skip + # the /download round trip entirely when it hasn't moved since + # last sync and we already have a cached copy on disk. + note_path = notes_dir / f"{entry.id}.md" + need_fetch = ( + prev is None + or prev.last_seen_time != entry.time + or prev.content_hash is None + or not note_path.exists() + ) + text = None + fetch_failed = False + if need_fetch: + try: + text = source.fetch_content(entry.id) + except Exception as exc: + logger.error("Could not fetch content for %s (%s): %s", entry.id, entry.title, exc) + fetch_failed = True + if prev is None: + continue # never seen before and unreachable -- skip entirely + + new_hash = content_hash(text) if text is not None else (prev.content_hash if prev else None) + content_changed = text is not None and (prev is None or prev.content_hash != new_hash) + if content_changed: + note_path.write_text(text, encoding="utf-8") + try: + os.chmod(note_path, stat.S_IRUSR | stat.S_IWUSR) # 0600: cache, not for editing + except OSError: + pass + # A failed fetch means we don't actually know the server's + # current time for this note -- keep the old value so the next + # sync retries instead of wrongly believing it's up to date. + new_last_seen_time = (prev.last_seen_time if (prev and fetch_failed) else entry.time) + + # --- desired symlinks for this note --- + title = entry.title + old_symlinks = dict(prev.symlinks) if prev else {} + title_changed = prev is not None and prev.title != title + + # /history hasn't caught up to a direct tag update yet (see + # NoteState.tags_confirmed_stale_at) -- this exact `entry.time` + # is one we already know predates that write. Trust the local + # result instead of clobbering it with a snapshot recognizably + # older than what's already correct on disk. + tags_stale = ( + prev is not None + and prev.tags_confirmed_stale_at is not None + and entry.time == prev.tags_confirmed_stale_at + ) + if tags_stale: + new_symlinks = old_symlinks + tags = list(prev.tags) + new_tags_confirmed_stale_at = prev.tags_confirmed_stale_at + else: + new_symlinks, created, removed = _sync_note_symlinks( + root, entry.id, title, tags, note_path, old_symlinks, title_changed, + ) + result.symlinks_created.extend(created) + result.symlinks_removed.extend(removed) + # /history has moved past the known-stale time (whether to + # exactly the value the write produced, or further, from + # another edit since) -- it's caught up, trust it normally + # again from here on. + new_tags_confirmed_stale_at = None + + state.notes[entry.id] = NoteState( + title=title, tags=tags, symlinks=new_symlinks, + content_hash=new_hash if new_hash is not None else (prev.content_hash if prev else None), + last_seen_time=new_last_seen_time, + tags_confirmed_stale_at=new_tags_confirmed_stale_at, + ) + (result.notes_updated if (content_changed or title_changed or old_symlinks != new_symlinks) + else result.notes_unchanged).append(entry.id) + + # --- prune notes that disappeared from /history entirely --- + for note_id in list(state.notes.keys()): + if note_id in seen_ids: + continue + prev = state.notes.pop(note_id) + for tag, name in prev.symlinks.items(): + link = root / tag / name + if link.is_symlink(): + link.unlink() + result.symlinks_removed.append(str(link)) + note_path = notes_dir / f"{note_id}.md" + if note_path.exists(): + note_path.unlink() + result.notes_removed.append(note_id) + + result.problems = detect_problems(root, state) + save_problems(hd_dir, result.problems) + + return result + + +# -------------------------------------------------------------------------- +# Tag writing: hd tag / hd untag. The only place in this codebase that +# writes to HedgeDoc. There is no plain HTTP save endpoint for existing +# notes (confirmed against lib/web/note/router.js), so this opens a +# short-lived realtime connection, fetches the document FRESH (never from +# the local .hd/notes/ cache, which can be hours stale), edits only the +# frontmatter tags line, and closes again. +# -------------------------------------------------------------------------- + +# Mirrors HedgeDoc's own splitFrontmatter() exactly (lib/models/note.js): +# the document must start with literal "---", and the block is closed by +# the first "\n---" or "\n..." found anywhere after that. +_FRONTMATTER_CLOSE_RE = re.compile(r"\n(\.\.\.|---)") + + +class FrontmatterError(RuntimeError): + pass + + +def parse_frontmatter(text: str) -> Optional[dict[str, Any]]: + if text[:3] != "---": + return None + m = _FRONTMATTER_CLOSE_RE.search(text) + if not m: + return None + return { + "yaml_str": text[:m.start()], # includes the opening "---" line + "yaml_end": m.start(), # char index; the edit region is [0, yaml_end) + "body_start": m.end(), + } + + +def parse_current_tags(meta: dict) -> list[str]: + """Mirror HedgeDoc's Note.extractNoteTags: a comma-separated string (or + bare number), deduplicated preserving first-seen order. A YAML list is + NOT accepted here either -- matches the server, which silently ignores + non-string/number `tags` values.""" + raw = meta.get("tags") + if not isinstance(raw, (str, int, float)) or isinstance(raw, bool): + return [] + tags: list[str] = [] + for part in str(raw).split(","): + part = part.strip() + if part and part not in tags: + tags.append(part) + return tags + + +def compute_tag_patch(text: str, new_tags: list[str]) -> tuple[int, int, str]: + """Return (start, end, replacement) -- Python character indices into + `text` -- for the minimal edit that sets the frontmatter tags to + exactly new_tags, touching nothing else. Always writes the comma-string + form (a YAML list is silently ignored by the server, verified against + lib/models/note.js).""" + tags_str = ", ".join(new_tags) + fm = parse_frontmatter(text) + if fm is None: + # No frontmatter at all: insert a fresh block. A pure insert at 0 + # is a (0, 0, ...) patch -- same shape, simpler for the caller. + block = f"---\ntags: {tags_str}\n---\n" if new_tags else "---\ntags:\n---\n" + return (0, 0, block) + + try: + meta = pyyaml.safe_load(fm["yaml_str"]) + except pyyaml.YAMLError as exc: + raise FrontmatterError( + f"Existing frontmatter isn't valid YAML -- refusing to touch it " + f"rather than risk destroying it: {exc}" + ) from exc + if meta is None: + meta = {} + if not isinstance(meta, dict): + raise FrontmatterError( + "Existing frontmatter doesn't parse as a mapping (key: value pairs) " + "-- refusing to touch it rather than risk destroying it." + ) + + if new_tags: + meta["tags"] = tags_str + else: + meta.pop("tags", None) + + dumped = pyyaml.safe_dump(meta, default_flow_style=False, sort_keys=False, + allow_unicode=True).rstrip("\n") + new_yaml_str = "---\n" + dumped if dumped else "---" + return (0, fm["yaml_end"], new_yaml_str) + + +def resolve_note_ref(root: Path, state: State, ref: str, cwd: Optional[Path] = None) -> str: + """Accept a note id, a path to one of its existing symlinks, or a title + (case-insensitive, must be unique) -- whichever the user typed. + + A relative path (including a bare name with no '/' at all, like 'FOI') + is resolved against `cwd` (the real process cwd by default) the same + way a shell resolves any other relative argument -- 'FOI' means the + symlink named FOI in the directory you're standing in, '../work/FOI' + means the one in ../work, never a title search that could silently + land on some OTHER note sharing that title somewhere else in the tree. + This takes priority over the title-search fallback below: if a + symlink genuinely exists at the resolved path, that note wins even if + a same-named title also exists elsewhere. Previously this resolved + relative paths against `root` instead of cwd, which made '../work/FOI' + resolve wrongly (relative to root's parent, not the directory you were + actually standing in) and gave a bare name like 'FOI' no cwd-scoping + at all -- it just fell straight through to the global title search. + """ + if cwd is None: + cwd = Path.cwd() + + candidate = Path(ref).expanduser() + p = candidate if candidate.is_absolute() else (cwd / candidate) + if p.is_symlink(): + target = p.resolve() + if target.suffix == ".md" and target.parent == (root / ".hd" / NOTES_DIRNAME).resolve(): + return target.stem + + if ref in state.notes: + return ref + + matches = [nid for nid, n in state.notes.items() if n.title.lower() == ref.lower()] + if len(matches) == 1: + return matches[0] + if len(matches) > 1: + raise ValueError(f"{len(matches)} notes are titled {ref!r} ({', '.join(matches)}) -- use the note id instead") + raise ValueError(f"No known note matches {ref!r} (not an id, a symlink path, or a unique title)") + + +def write_tags( + url: str, + cookie: str, + note_id: str, + mutate: Callable[[list[str]], list[str]], + timeout: float = 15.0, +) -> list[str]: + """Connect, fetch the document FRESH, apply `mutate` to its current + frontmatter tags, push the minimal edit, wait for it to be acknowledged, + and disconnect. Returns the new tag list. + + Deliberately a single attempt, not a manual "retry if revision moved" + loop: revision always advances after OUR OWN op is acked, so comparing + it to the pre-send value can't distinguish a concurrent edit from our + own success -- an earlier version of this function got that wrong and + replayed mutate() a second time on top of its own already-applied + change (caught by test_hd_write.py). A genuinely concurrent edit to the + frontmatter tags is still handled correctly at the byte level by the + normal OT transform in send_operation/replace(); what isn't handled is + a *semantic* merge of two simultaneous tag changes, which is a small + residual risk documented rather than papered over with a broken retry. + """ + client = HedgeDocClient(url, note_id, cookie=cookie, verbose=False) + client.connect() + try: + doc = client.wait_ready(timeout) + meta = parse_frontmatter(doc.text) + current_tags = parse_current_tags(pyyaml.safe_load(meta["yaml_str"]) or {}) if meta else [] + new_tags = mutate(current_tags) + if new_tags == current_tags: + return current_tags # nothing to do -- no network write at all + + start, end, replacement = compute_tag_patch(doc.text, new_tags) + client.replace(start, end, replacement) + + deadline = time.monotonic() + timeout + while client.pending_count > 0: + if time.monotonic() >= deadline: + raise TimeoutError( + f"Tag write to {note_id} was not acknowledged within {timeout}s" + ) + time.sleep(0.05) + + return new_tags + finally: + client.close() + + +# -------------------------------------------------------------------------- +# hd-joe integration: discovering an hd-managed tree from wherever hd-joe +# was launched (git-style upward search), deriving a tag from how deep that +# is under the root, and creating a brand-new note when the name given +# doesn't match an existing symlink. Everything here is read/create-only +# from HedgeDoc's point of view -- editing an existing note is still +# hd_client.HedgeDocClient's job, started separately once a note id is +# known. +# -------------------------------------------------------------------------- + +def find_hd_root(start: Path) -> Optional[Path]: + """Climb from `start` looking for a `.hd` directory, git-style. Returns + the directory that CONTAINS .hd (the notes root), or None if there + isn't one anywhere above `start`.""" + current = start.resolve() + while True: + if (current / ".hd").is_dir(): + return current + parent = current.parent + if parent == current: # reached the filesystem root + return None + current = parent + + +def tag_from_cwd(root: Path, cwd: Path) -> tuple[Optional[str], Optional[str]]: + """Derive a single tag from how deep `cwd` sits under `root`. + + Returns (tag, error). Nested tag folders were deliberately dropped (see + the manual) -- exactly one level is supported, so anything deeper is an + error here rather than a silently-accepted compound tag. `tag` is None + with no error when `cwd` IS `root` (untagged) or when `cwd` doesn't + resolve under `root` at all as a normal path relationship worth acting + on -- callers decide what untagged should mean for their operation. + """ + cwd = cwd.resolve() + root = root.resolve() + try: + rel = cwd.relative_to(root) + except ValueError: + return None, f"{cwd} is not inside {root}" + parts = rel.parts + if parts and parts[0] == ".hd": + return None, f"{cwd} is inside .hd/ -- hd-joe shouldn't be run from there" + if len(parts) == 0: + return None, None # at the root itself -- untagged + if len(parts) == 1: + return parts[0], None + return None, ( + f"{cwd} is nested {len(parts)} levels under {root} -- nested tag " + f"folders aren't supported. Run hd-joe from directly inside one tag " + f"folder (e.g. {root / parts[0]})." + ) + + +def create_note(url: str, cookie: str, title: str, tags: list[str], timeout: float = 15.0) -> tuple[str, str]: + """POST /new with a frontmatter block already containing title+tags, and + return (note_id, initial_text). Mirrors login()'s approach to a route + that always redirects rather than returning JSON (confirmed against + lib/web/note/util.js's newNote(): it redirects to /<encodeNoteId(id)>, + the SAME id form /history's `id` field already uses -- no translation + needed between creation and the rest of this codebase). + """ + url = url.rstrip("/") + meta: dict[str, Any] = {"title": title} + if tags: + meta["tags"] = ", ".join(tags) + dumped = pyyaml.safe_dump(meta, default_flow_style=False, sort_keys=False, + allow_unicode=True).rstrip("\n") + content = f"---\n{dumped}\n---\n\n" + + opener = urllib.request.build_opener(_NoRedirect()) + req = urllib.request.Request( + f"{url}/new", data=content.encode("utf-8"), method="POST", + headers={"Content-Type": "text/markdown; charset=utf-8", "Cookie": cookie}, + ) + try: + opener.open(req, timeout=timeout) + except urllib.error.HTTPError as exc: + if not (300 <= exc.code < 400): + raise RuntimeError(f"POST /new returned {exc.code}: {exc.reason}") from exc + location = exc.headers.get("Location") + if not location: + raise RuntimeError("POST /new redirected but sent no Location header") + note_id = location.rstrip("/").rsplit("/", 1)[-1] + return note_id, content + except urllib.error.URLError as exc: + raise RuntimeError(f"Could not reach {url}/new: {exc}") from exc + raise RuntimeError("POST /new succeeded outright instead of redirecting -- unexpected server behavior") + + +def register_note(root: Path, state: State, note_id: str, title: str, tags: list[str], text: str) -> NoteState: + """Insert a brand-new note into the local cache/state/symlinks without + waiting for the next full /history-driven sync. Caller is responsible + for holding ReconcileLock around this (and around create_note(), so the + two happen as one atomic-from-the-outside step) -- this function itself + only touches the filesystem and the in-memory `state`, and does not + call state.save() so the caller can batch it with other changes.""" + hd_dir = root / ".hd" + notes_dir = hd_dir / NOTES_DIRNAME + notes_dir.mkdir(parents=True, exist_ok=True) + note_path = notes_dir / f"{note_id}.md" + note_path.write_text(text, encoding="utf-8") + try: + os.chmod(note_path, stat.S_IRUSR | stat.S_IWUSR) + except OSError: + pass + + effective_tags = tags if tags else [UNTAGGED] + symlinks: dict[str, str] = {} + for tag in effective_tags: + tag_dir = root / tag + tag_dir.mkdir(parents=True, exist_ok=True) + taken = {p.name for p in tag_dir.iterdir()} if tag_dir.exists() else set() + name = unique_name(sanitize_title(title), note_id, taken) + target = os.path.relpath(note_path, tag_dir) + (tag_dir / name).symlink_to(target) + symlinks[tag] = name + + ns = NoteState( + title=title, tags=effective_tags, symlinks=symlinks, + content_hash=content_hash(text), last_seen_time=int(time.time() * 1000), + ) + state.notes[note_id] = ns + return ns + + +def strip_md_suffix(name: str) -> str: + """'Masten' and 'Masten.md' name the same note -- accept both, matching + what a plain `ls` of the tag directory actually shows. Only strips a + LITERAL trailing '.md'; 'Masten.md.md' (an unlikely but real note + title) is left alone rather than mangled twice.""" + if name.endswith(".md") and len(name) > len(".md"): + return name[: -len(".md")] + return name + + +def find_existing_symlink(root: Path, tag: Optional[str], name: str) -> Optional[str]: + """If <root>/<tag or untagged>/<sanitized name> is already a symlink + into .hd/notes/<id>.md, return that id. None if there's no such + symlink (including: it exists but isn't ours -- a stray file, or a + symlink pointing elsewhere -- callers should fall through to creating a + new note rather than guessing).""" + tag_dir = root / (tag if tag else UNTAGGED) + candidate = tag_dir / sanitize_title(strip_md_suffix(name)) + if not candidate.is_symlink(): + return None + target = candidate.resolve() + notes_dir = (root / ".hd" / NOTES_DIRNAME).resolve() + if target.parent != notes_dir or target.suffix != ".md": + return None + return target.stem + + +def check_target_dir_fresh(root: Path, cwd: Path, state: State) -> Optional[str]: + """The manual's stricter special case: before CREATING a note in a + directory, verify that directory itself is sound -- freshly, never from + the cached .hd/problems.json, which can be a full sync interval stale + and is the wrong thing to hang the system's only blocking refusal on. + + Deliberately narrow and cheap (a listdir of one directory, no + checksums, no tree walk): it only looks for problems that would make + creating a note *here* wrong. Returns an error string, or None if the + directory is fine. + """ + cwd = cwd.resolve() + if cwd == root.resolve(): + return None # the root itself is never "a broken tag directory" + if not cwd.is_dir(): + return f"{cwd} is not a directory" + for entry in cwd.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + return (f"{cwd} contains a subdirectory ({entry.name}/) -- nested tag " + f"folders aren't supported, so this tag directory is in a state " + f"hd can't reconcile. Fix it before creating notes here.") + return None + + +def save_offline_recovery(hd_root: Path, note_id: str, text: str) -> Path: + """Preserve locally-typed content that never reached the server (e.g. + hd-joe was offline at quit time) somewhere recoverable, WITHOUT touching + the tracked cache/state -- see update_note_cache()'s docstring for why + that distinction matters. Never overwrites a previous recovery file for + the same note; each offline session that fails to sync gets its own + timestamped file, so nothing is silently replaced by a later one. + """ + recovery_dir = hd_root / ".hd" / "offline-recovery" + recovery_dir.mkdir(parents=True, exist_ok=True) + timestamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) + path = recovery_dir / f"{note_id}-{timestamp}.md" + path.write_text(text, encoding="utf-8") + return path + + +def update_note_cache(hd_root: Path, note_id: str, text: str) -> bool: + """After an hd-joe edit session ends, refresh .hd/notes/<id>.md and + state.json's content_hash for that ONE note -- without a full + /history-driven sync. Title/tags/symlinks are left untouched (an edit + session doesn't change them); this only exists so 'cat' on the symlink + right after quitting hd-joe shows what you just typed, instead of + whatever the last 'hdc sync' happened to see. + + No-op (returns False) if the note isn't in state yet -- e.g. it was + opened by explicit <url> <note-id> and has never been through a sync, + so there's no title/tags to safely preserve. The next 'hdc sync' will + pick it up properly via /history. + """ + hd_dir = hd_root / ".hd" + with ReconcileLock(hd_dir): + state = State.load(hd_dir) + ns = state.notes.get(note_id) + if ns is None: + return False + note_path = hd_dir / NOTES_DIRNAME / f"{note_id}.md" + note_path.write_text(text, encoding="utf-8") + try: + os.chmod(note_path, stat.S_IRUSR | stat.S_IWUSR) + except OSError: + pass + ns.content_hash = content_hash(text) + state.save(hd_dir) + return True + + +def resolve_or_create_note( + hd_root: Path, cwd: Path, name: str, url: str, cookie: str, +) -> tuple[str, bool]: + """The core of `hd-joe <name>`: figure out the tag from `cwd`, open the + matching note if a symlink for `name` already exists there, otherwise + create it on the server and register it locally. Returns (note_id, + created). Raises ValueError for a refusal (e.g. nested tag folder) that + callers should report and exit on, not retry. + """ + name = strip_md_suffix(name) # "Masten" and "Masten.md" mean the same note + tag, err = tag_from_cwd(hd_root, cwd) + if err: + raise ValueError(err) + + existing_id = find_existing_symlink(hd_root, tag, name) + if existing_id: + return existing_id, False + + hd_dir = hd_root / ".hd" + state = State.load(hd_dir) + # Only gate CREATION on this, not opening: opening an existing note in a + # messy directory is harmless, but adding a new one to a directory hd + # already can't reconcile just deepens the mess. + dir_error = check_target_dir_fresh(hd_root, cwd, state) + if dir_error: + raise ValueError(dir_error) + tags = [tag] if tag else [] + with ReconcileLock(hd_dir): + note_id, initial_text = create_note(url, cookie, name, tags) + register_note(hd_root, state, note_id, name, tags, initial_text) + state.save(hd_dir) + return note_id, True diff --git a/hd_common/requirements.txt b/hd_common/requirements.txt new file mode 100644 index 0000000..4abd3d5 --- /dev/null +++ b/hd_common/requirements.txt @@ -0,0 +1,2 @@ +python-socketio[client]>=5.11,<6 +PyYAML>=6.0,<7 diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..785cfc2 --- /dev/null +++ b/install.sh @@ -0,0 +1,310 @@ +#!/usr/bin/env bash +# Installs the binary built by build.sh over whatever 'joe' currently +# resolves to, installs Python dependencies into a venv, and links +# hdc/hd-joe onto PATH. +# +# Usage: ./install.sh [--joe-target PATH] [--bin-dir DIR] +# ./install.sh --restore [--joe-target PATH] [--bin-dir DIR] +# sudo ./install.sh --joe-only [--joe-target PATH] +# +# --joe-target PATH Where to install patched joe (default: wherever +# 'joe' currently resolves on PATH, or +# <bin-dir>/joe if there isn't one yet). +# --bin-dir DIR Where to link hd and hd-joe (default: ~/.local/bin). +# --joe-only Only back up + install the joe binary; skip the +# venv/pip/launcher setup entirely. Use this (with +# sudo, if needed) when the joe target directory +# (e.g. /usr/local/bin) isn't writable by you -- +# run the plain form (no sudo) separately for +# everything else. +# --restore Undo: put the original joe back from its backup, +# remove the hdc/hd-joe links, disable and remove +# the sync service, exit. +# --notes-dir DIR What the sync service watches (default: ~/notes, +# same default hdc itself uses). +# --sync-interval N Seconds between polls for the sync service +# (default: 30). +# --no-service Skip setting up the continuous background sync +# service entirely -- run `hdc sync --watch` +# yourself if you'd rather manage that some other +# way (cron, a different init system, by hand). +# +# NEVER run the plain form (no --joe-only) with sudo: it sets up a venv and +# launcher scripts meant for YOUR account, and running the whole thing as +# root creates them owned by root, under root's $HOME, invisible to you +# afterward. If joe's install location needs root, use --joe-only for just +# that part (with sudo) and run the rest as yourself. +set -euo pipefail + +SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" +BUILT="$SCRIPT_DIR/joe-patch/build/joe-4.8/joe/joe" +BIN_DIR="${BIN_DIR:-$HOME/.local/bin}" +NOTES_DIR="${NOTES_DIR:-$HOME/notes}" +SYNC_INTERVAL="${SYNC_INTERVAL:-30}" +# Defined here, unconditionally, not inside install_python_and_launchers(): +# install_joe() (possibly run alone, under sudo, via --joe-only, before the +# venv exists yet) needs this path too, to write it into the joe wrapper. +VENV_DIR="$SCRIPT_DIR/.venv" +JOE_TARGET="" +RESTORE=0 +JOE_ONLY=0 +NO_SERVICE=0 +SERVICE_NAME="hdc-sync.service" +SERVICE_PATH="$HOME/.config/systemd/user/$SERVICE_NAME" + +while [ $# -gt 0 ]; do + case "$1" in + --restore) RESTORE=1; shift ;; + --joe-only) JOE_ONLY=1; shift ;; + --no-service) NO_SERVICE=1; shift ;; + --joe-target) JOE_TARGET="$2"; shift 2 ;; + --bin-dir) BIN_DIR="$2"; shift 2 ;; + --notes-dir) NOTES_DIR="$2"; shift 2 ;; + --sync-interval) SYNC_INTERVAL="$2"; shift 2 ;; + -h|--help) + sed -n '2,34p' "$0" | sed 's/^# \{0,1\}//' + exit 0 ;; + *) echo "Unknown argument: $1" >&2; exit 1 ;; + esac +done + +if [ -z "$JOE_TARGET" ]; then + JOE_TARGET="$(command -v joe 2>/dev/null || true)" + [ -z "$JOE_TARGET" ] && JOE_TARGET="$BIN_DIR/joe" +fi +BACKUP="${JOE_TARGET}.pre-hedgedoc" + +install_joe() { + if [ ! -x "$BUILT" ]; then + echo "$BUILT not found -- run ./build.sh first." >&2 + exit 1 + fi + + mkdir -p "$(dirname "$JOE_TARGET")" 2>/dev/null || true + + # Back up whatever ORIGINAL, non-hd joe was at this path -- once. If + # what's there is already one of our own wrappers (re-running + # install.sh), there's nothing genuine left to preserve; regenerating + # the wrapper below is cheap and always safe to redo. + # + # Checked explicitly (not left to `set -e`) because this function runs + # as `install_joe || JOE_OK=0` in the main flow -- bash disables -e for + # every command inside a function called as part of an && / || list, + # not just its last one, so a failed cp here would otherwise fall + # through silently to the next step instead of being caught. + if [ -e "$JOE_TARGET" ] && ! grep -q "# hd-installer-generated" "$JOE_TARGET" 2>/dev/null; then + if [ -e "$BACKUP" ]; then + echo "==> Backup already exists at $BACKUP (leaving it -- it's your original, pre-hd, joe)" + else + if ! cp "$JOE_TARGET" "$BACKUP" 2>/dev/null; then + echo "$(dirname "$JOE_TARGET") isn't writable by $(whoami) -- can't even back up the existing joe there." >&2 + echo "Run just this part with sudo:" >&2 + echo " sudo $0 --joe-only --joe-target $JOE_TARGET" >&2 + echo "then run $0 again WITHOUT sudo to finish (venv, hdc, hd-joe)." >&2 + return 1 + fi + echo "==> Backed up existing joe: $JOE_TARGET -> $BACKUP" + fi + fi + + if [ ! -w "$(dirname "$JOE_TARGET")" ]; then + echo "$(dirname "$JOE_TARGET") isn't writable by $(whoami)." >&2 + echo "Run just this part with sudo:" >&2 + echo " sudo $0 --joe-only --joe-target $JOE_TARGET" >&2 + echo "then run $0 again WITHOUT sudo to finish (venv, hdc, hd-joe)." >&2 + return 1 + fi + + # joe itself is now a wrapper, not the raw binary: it routes hd-managed + # notes to hd-joe (so you can never accidentally edit a note's cache + # file directly on disk, bypassing HedgeDoc) and everything else to the + # real compiled binary, which stays at $BUILT rather than being copied + # -- see hd-joe/joe_wrapper.py for the actual decision logic. + if ! cat > "$JOE_TARGET" <<WRAPEOF 2>/dev/null +#!/usr/bin/env bash +# hd-installer-generated +exec "$VENV_DIR/bin/python3" "$SCRIPT_DIR/hd-joe/joe_wrapper.py" "\$@" +WRAPEOF + then + echo "Could not write $JOE_TARGET (permission denied)." >&2 + echo " sudo $0 --joe-only --joe-target $JOE_TARGET" >&2 + return 1 + fi + chmod 755 "$JOE_TARGET" + echo "==> Installed joe wrapper -> $JOE_TARGET" + echo " (hd-managed notes route to hd-joe automatically; everything else" + echo " still goes to the real patched joe, unchanged)" + return 0 +} + +install_python_and_launchers() { + if [ "$(id -u)" = "0" ]; then + echo "Refusing to set up the venv and hdc/hd-joe launchers as root." >&2 + echo "This part is meant to run as your own user -- re-run without sudo." >&2 + echo "(If joe's install location needs root, use --joe-only with sudo" >&2 + echo " for that part separately.)" >&2 + exit 1 + fi + + # A plain `pip install --user` fails outright on modern Debian/Ubuntu + # (PEP 668 "externally-managed-environment"), and the suggested escape + # hatch (--break-system-packages) is pip's own last resort, not a + # default a script should reach for quietly. A dedicated venv + # sidesteps the problem entirely and needs no activation -- the + # launcher scripts below call its python3 directly. + echo "==> Setting up a virtual environment at $VENV_DIR" + python3 -m venv "$VENV_DIR" + "$VENV_DIR/bin/pip" install --quiet --upgrade pip + "$VENV_DIR/bin/pip" install \ + -r "$SCRIPT_DIR/hd-cli/requirements.txt" \ + -r "$SCRIPT_DIR/hd-joe/requirements.txt" + + echo "==> Installing launchers into $BIN_DIR" + mkdir -p "$BIN_DIR" + # Wrapper scripts, not symlinks: they pin the venv's interpreter + # explicitly, so hdc/hd-joe work whether or not the venv is activated, + # and from any cwd. The marker comment is how --restore recognizes + # these as ours to remove, rather than deleting an unrelated file that + # happened to be named the same. + cat > "$BIN_DIR/hdc" <<WRAPEOF +#!/usr/bin/env bash +# hd-installer-generated +exec "$VENV_DIR/bin/python3" "$SCRIPT_DIR/hd-cli/hdc" "\$@" +WRAPEOF + cat > "$BIN_DIR/hd-joe" <<WRAPEOF +#!/usr/bin/env bash +# hd-installer-generated +exec "$VENV_DIR/bin/python3" "$SCRIPT_DIR/hd-joe/hd_joe_agent.py" "\$@" +WRAPEOF + chmod +x "$BIN_DIR/hdc" "$BIN_DIR/hd-joe" + + case ":$PATH:" in + *":$BIN_DIR:"*) ;; + *) + echo + echo "NOTE: $BIN_DIR isn't on your PATH. Add to your shell rc:" + echo " export PATH=\"$BIN_DIR:\$PATH\"" + ;; + esac + + echo + echo " hdc -> $BIN_DIR/hdc (runs via $VENV_DIR)" + echo " hd-joe -> $BIN_DIR/hd-joe (runs via $VENV_DIR)" +} + +install_sync_service() { + if [ "$(id -u)" = "0" ]; then + # Same reasoning as install_python_and_launchers(): a systemd + # --user service belongs to the invoking user's session. Enabling + # it as root would enable it for root, not you -- silently useless. + echo "Refusing to set up the sync service as root -- re-run without sudo." >&2 + return 1 + fi + if ! command -v systemctl >/dev/null 2>&1; then + echo "==> systemctl not found -- skipping the background sync service." + echo " Run 'hdc sync --dir $NOTES_DIR --watch' yourself (or via cron/tmux/screen)" + echo " to get continuous sync instead of running 'hdc sync' by hand each time." + return 0 + fi + + mkdir -p "$(dirname "$SERVICE_PATH")" + cat > "$SERVICE_PATH" <<UNITEOF +[Unit] +Description=hdc sync --watch -- continuous HedgeDoc <-> local folder sync +After=network-online.target +Wants=network-online.target +StartLimitIntervalSec=300 +StartLimitBurst=10 + +[Service] +Type=simple +ExecStart=$BIN_DIR/hdc sync --dir $NOTES_DIR --watch --interval $SYNC_INTERVAL +Restart=on-failure +RestartSec=15 + +[Install] +WantedBy=default.target +UNITEOF + echo "==> Wrote $SERVICE_PATH" + + if ! systemctl --user daemon-reload 2>/tmp/hdc-systemctl-err; then + echo "==> Couldn't reach your systemd user session ($(cat /tmp/hdc-systemctl-err 2>/dev/null))." >&2 + echo " Common cause: no active login session (e.g. a bare SSH connection)." >&2 + echo " The unit file is in place at $SERVICE_PATH -- once you have a normal" >&2 + echo " desktop/login session, run:" >&2 + echo " systemctl --user daemon-reload && systemctl --user enable --now $SERVICE_NAME" >&2 + rm -f /tmp/hdc-systemctl-err + return 0 + fi + rm -f /tmp/hdc-systemctl-err + systemctl --user enable "$SERVICE_NAME" >/dev/null 2>&1 + + if [ -d "$NOTES_DIR/.hd" ]; then + systemctl --user restart "$SERVICE_NAME" + echo "==> $SERVICE_NAME enabled and running -- watching $NOTES_DIR every ${SYNC_INTERVAL}s" + else + echo "==> $SERVICE_NAME enabled but NOT started -- $NOTES_DIR/.hd doesn't exist yet." + echo " Run 'hdc init <url> --dir $NOTES_DIR' first, then:" + echo " systemctl --user start $SERVICE_NAME" + fi +} + +# --- restore ------------------------------------------------------------- +if [ "$RESTORE" = 1 ]; then + if [ -f "$BACKUP" ]; then + if cp "$BACKUP" "$JOE_TARGET" 2>/dev/null; then + echo "Restored: $BACKUP -> $JOE_TARGET" + else + echo "$JOE_TARGET isn't writable by $(whoami) -- run:" >&2 + echo " sudo cp $BACKUP $JOE_TARGET" >&2 + fi + else + echo "No backup at $BACKUP -- nothing to restore." >&2 + fi + for name in hdc hd-joe; do + link="$BIN_DIR/$name" + if [ -f "$link" ] && grep -q "# hd-installer-generated" "$link" 2>/dev/null; then + rm "$link" && echo "Removed $link" + fi + done + if [ -f "$SERVICE_PATH" ] && command -v systemctl >/dev/null 2>&1; then + systemctl --user disable --now "$SERVICE_NAME" >/dev/null 2>&1 || true + rm -f "$SERVICE_PATH" + systemctl --user daemon-reload 2>/dev/null || true + echo "Disabled and removed $SERVICE_NAME" + fi + exit 0 +fi + +# --- joe-only -------------------------------------------------------------- +if [ "$JOE_ONLY" = 1 ]; then + install_joe + exit $? +fi + +# --- full install ---------------------------------------------------------- +install_python_and_launchers + +if [ "$NO_SERVICE" = 1 ]; then + echo + echo "==> --no-service: skipping the background sync service." +else + echo + install_sync_service +fi + +echo +JOE_OK=1 +install_joe || JOE_OK=0 + +echo +if [ "$JOE_OK" = 1 ]; then + echo "Done. joe at $JOE_TARGET has HedgeDoc support (only active when" + echo "JOE_HEDGE_SOCKET is set -- stock behavior otherwise; your original" + echo "is backed up at $BACKUP)." +else + echo "hd and hd-joe are set up. Patched joe is NOT installed yet -- see" + echo "the sudo command printed above to finish that part." +fi +echo +echo "Restore the original joe, remove hdc/hd-joe, and stop the sync service: $0 --restore" diff --git a/joe-patch/README.md b/joe-patch/README.md new file mode 100644 index 0000000..d259b86 --- /dev/null +++ b/joe-patch/README.md @@ -0,0 +1,111 @@ +# joe-4.8-hedgedoc-0.7.13.patch + +Patches **Joe's Own Editor 4.8** (the real editor, not a reimplementation) +so it can act as a live HedgeDoc client. JOE keeps owning the edit buffer +and all its normal keybindings; the patch only adds a side channel that +reports local edits out and applies remote edits in. + +## What it touches + +Six files, ~640 added lines, all under `joe/`: + +| File | Change | +| --- | --- | +| `hd_ipc.c` | **New.** The whole integration: Unix-socket client, line protocol parser, applying remote edits to a buffer, moving the cursor. | +| `hd_ipc.h` | **New.** Its header. | +| `b.c` | Hooks in `bdel()`/`binsm()` (JOE's core buffer delete/insert primitives) to report local edits out. | +| `tty.c`, `main.c` | Calls `hd_ipc_poll()` from the main loop so remote edits get applied between keystrokes. | +| `Makefile.am` | Adds `hd_ipc.c` to the build. | + +Without `JOE_HEDGE_SOCKET` set in the environment, every hook short-circuits +immediately — the patched binary behaves exactly like stock JOE, so there's +no reason to keep two builds around. + +## Building + + ../build.sh + +Clones joe 4.8, applies this patch, and builds it under `build/joe-4.8/` +(gitignored -- not part of the repo). Idempotent: safe to re-run, skips the +clone/patch step if `build/joe-4.8/joe/hd_ipc.c` already exists. `../build.sh +--clean` removes `build/` first for a from-scratch rebuild. The binary lands +at `build/joe-4.8/joe/joe`; `../install.sh` puts it wherever `joe` currently +resolves on your PATH (backing up whatever was there first -- see the +top-level README). + +Needs a C toolchain, autotools, git, and ncurses headers +(`build-essential autoconf automake libncurses-dev git` on Debian/Ubuntu); +`build.sh` checks for these upfront and says what's missing rather than +failing deep into `make`. + +<details> +<summary>Doing it by hand instead (e.g. against a source tree you already have)</summary> + + # From the directory *containing* your joe-4.8/ checkout: + patch -p1 < joe-patch/joe-4.8-hedgedoc-0.7.13.patch + cd joe-4.8 + autoreconf -fi # required: the patch changes Makefile.am, not + # the generated Makefile.in -- skip this and + # you get a binary silently missing hd_ipc.o + ./configure --prefix=$HOME/.local + make + +Set `JOE_SRC_DIR=/path/to/your/joe-4.8` before running `../build.sh` to have +it use an existing checkout (must be named `joe-4.8`, matching the patch's +own path assumptions) instead of cloning one. + +</details> + +## The wire protocol + +A tiny line-oriented protocol over a private Unix stream socket, with the +Python agent on the other end. Hex encoding avoids every quoting, locale +and newline ambiguity. + + JOE -> agent: + I <byte-offset> <hex-utf8> local insert + D <byte-offset> <byte-count> local delete + + agent -> JOE: + I <byte-offset> <hex-utf8> apply remote insert + D <byte-offset> <byte-count> apply remote delete + R <hex-utf8> replace the whole buffer (unused by + default — see CHANGES-0.7.16.md) + C <byte-offset> move the cursor + M <hex-utf8> show a status-line message (offline/ + back-online notices) via JOE's own + msgnw() -- the same mechanism behind + built-in notices like "Read only" + +Environment variables JOE reads: `JOE_HEDGE_SOCKET` (socket path — also the +on/off switch) and `JOE_HEDGE_BUFFER` (the working file). `hd-joe` sets both. + +## Two non-obvious correctness details + +Worth knowing if you modify this, because both caused real bugs that took +a while to find (full write-ups in `../CHANGES-0.7.16.md`): + +**Re-entrancy.** Applying a remote edit calls the same `bdel()`/`binsm()` +the local hooks are attached to. Without a guard, every remote edit would +be echoed straight back to the server as if the user had typed it. +`hd_ipc_applying()` is that guard — check it before reporting anything. + +**Buffer identity.** `bdel()`/`binsm()` fire for *every* buffer JOE has +open, including the search/replace/filename prompt buffers (`TYPEPW`). +Without `hd_target_buf` scoping, typing in the search box would be sent to +the server as document content, and incoming remote edits could land in +whatever prompt happened to have focus. Anything new that hooks JOE +internals needs the same check. + +**Cursor handling.** Never apply a large update as a whole-buffer replace +(`bdel` from BOF to EOF, then reinsert). That collapses every pointer in +the buffer — including the cursor — to position 0, with no way to recover +where it was. Incremental insert/delete commands only disturb pointers +inside the range that actually changed. + +## Status + +Built and tested against joe 4.8 on Linux. The editor-side behaviour +(BOF/EOF edits, cursor placement after AI block rewrites) has been verified +against a real HedgeDoc server; the rest of the stack has only been tested +against fake servers so far — see the top-level README. diff --git a/joe-patch/joe-4.8-hedgedoc-0.7.13.patch b/joe-patch/joe-4.8-hedgedoc-0.7.13.patch new file mode 100644 index 0000000..cfd6e1a --- /dev/null +++ b/joe-patch/joe-4.8-hedgedoc-0.7.13.patch @@ -0,0 +1,811 @@ +diff -ruN '--exclude=*.o' '--exclude=.deps' '--exclude=Makefile' '--exclude=Makefile.in' '--exclude=autoconf.h*' '--exclude=joe' '--exclude=.dirstamp' '--exclude=stamp-h1' joe-src/joe/Makefile.am build/joe-4.8/joe/Makefile.am +--- joe-src/joe/Makefile.am 2026-09-17 19:01:38.249981415 +0000 ++++ build/joe-4.8/joe/Makefile.am 2026-09-17 19:06:56.898941072 +0000 +@@ -12,7 +12,7 @@ + ufile.h uformat.h uisrch.h umath.h undo.h usearch.h ushell.h utag.h \ + utils.h va.h vfile.h vs.h w.h utf8.h syntax.h charmap.h mouse.h \ + lattr.h gettext.h builtin.h vt.h mmenu.h state.h options.h selinux.h \ +- unicode.h cclass.h frag.h colors.h ++ unicode.h cclass.h frag.h colors.h hd_ipc.h + + bin_PROGRAMS = joe + AM_CPPFLAGS = -DJOERC="\"$(sysconf_joedir)/\"" -DJOEDATA="\"$(data_joedir)/\"" +@@ -25,7 +25,7 @@ + undo.c usearch.c ushell.c utag.c va.c vfile.c vs.c w.c utils.c syntax.c \ + utf8.c selinux.c charmap.c mouse.c lattr.c gettext.c builtin.c \ + builtins.c vt.c mmenu.c state.c options.c unicode.c \ +- cclass.c frag.c colors.c unicat-@UNICODE_VERSION@.c ++ cclass.c frag.c colors.c hd_ipc.c unicat-@UNICODE_VERSION@.c + + distclean-local: + rm -f *~ +diff -ruN '--exclude=*.o' '--exclude=.deps' '--exclude=Makefile' '--exclude=Makefile.in' '--exclude=autoconf.h*' '--exclude=joe' '--exclude=.dirstamp' '--exclude=stamp-h1' joe-src/joe/b.c build/joe-4.8/joe/b.c +--- joe-src/joe/b.c 2026-09-17 19:01:43.044359058 +0000 ++++ build/joe-4.8/joe/b.c 2026-09-20 19:31:23.308585958 +0000 +@@ -6,6 +6,7 @@ + * This file is part of JOE (Joe's Own Editor) + */ + #include "types.h" ++#include "hd_ipc.h" + + #ifdef HAVE_PWD_H + #include <pwd.h> +@@ -1999,8 +2000,13 @@ + void bdel(P *from, P *to) + { + if (to->byte - from->byte) { ++ off_t hd_pos = from->byte; ++ off_t hd_len = to->byte - from->byte; + B *b = bcut(from, to); + ++ if (!hd_ipc_applying()) ++ hd_ipc_local_delete(from->b, hd_pos, (ptrdiff_t)hd_len); ++ + if (from->b->undo) + undodel(from->b->undo, from->byte, b); + else +@@ -2185,6 +2191,7 @@ + H *h = NULL; + ptrdiff_t hdramnt = 0; /* Only used if h is set */ + P *q; ++ off_t hd_pos = p->byte; /* captured BEFORE any mutation, mirrors bdel() */ + + if (!amnt) + return p; +@@ -2208,6 +2215,19 @@ + inschn(q, a); + } + fixupins(q, amnt, nlines1, h, hdramnt); ++ if (!hd_ipc_applying()) { ++ /* Capture position via hd_pos (set above, before any mutation) for ++ * the same defensive reason bdel() captures hd_pos before bcut(): ++ * fixupins() rewrites other pointers in the buffer's pointer list, ++ * including p, via pset(), when they shared p's pre-insertion byte ++ * offset. Testing found p->byte == hd_pos after fixupins() for ++ * ordinary typing (this was NOT the cause of the BOF/EOF bugs -- ++ * see hd_joe_agent.py's drain_pending() for the actual EOF fix), ++ * but there's no correctness reason to read a value fixupins() is ++ * free to have rewritten when the pre-mutation value is already in ++ * hand. */ ++ hd_ipc_local_insert(p->b, hd_pos, blk, amnt); ++ } + pcoalesce(q); + prm(q); + return p; +diff -ruN '--exclude=*.o' '--exclude=.deps' '--exclude=Makefile' '--exclude=Makefile.in' '--exclude=autoconf.h*' '--exclude=joe' '--exclude=.dirstamp' '--exclude=stamp-h1' joe-src/joe/hd_ipc.c build/joe-4.8/joe/hd_ipc.c +--- joe-src/joe/hd_ipc.c 1970-01-01 00:00:00.000000000 +0000 ++++ build/joe-4.8/joe/hd_ipc.c 2026-09-20 19:31:23.306292960 +0000 +@@ -0,0 +1,567 @@ ++/* ++ * HedgeDoc <-> JOE buffer IPC ++ * Copyright (C) 2026 ++ * ++ * The protocol is intentionally tiny and line-oriented: ++ * ++ * JOE -> helper: ++ * I <byte-offset> <hex-utf8> ++ * D <byte-offset> <byte-count> ++ * ++ * helper -> JOE: ++ * I <byte-offset> <hex-utf8> ++ * D <byte-offset> <byte-count> ++ * R <hex-utf8> replace the entire buffer atomically ++ * C <byte-offset> move the cursor (e.g. to the next chat prompt ++ * after an AI integration rewrites a block) ++ * M <hex-utf8> show a status-line message (e.g. an ++ * offline/back-online notice) -- same ++ * mechanism JOE's own "Read only" uses ++ * ++ * Hex avoids quoting/locale/newline ambiguity. ++ */ ++ ++#include "types.h" ++#include "hd_ipc.h" ++ ++#ifndef __MSDOS__ ++ ++#include <sys/types.h> ++#include <sys/socket.h> ++#include <sys/un.h> ++#include <unistd.h> ++#include <fcntl.h> ++#include <errno.h> ++#include <stdlib.h> ++#include <stdio.h> ++#include <string.h> ++#include <ctype.h> ++#include <stdint.h> ++ ++static int hd_fd = -1; ++static int hd_active = 0; ++static int hd_in_apply = 0; ++static char hd_rx[65536]; ++static size_t hd_rx_len = 0; ++ ++/* The one buffer this session is allowed to touch. Locked onto the first ++ * real text window we see (never a prompt window), so search/replace/ ++ * filename prompts and any other internal JOE buffer never leak edits to ++ * or from HedgeDoc. NULL until locked. */ ++static B *hd_target_buf = NULL; ++ ++typedef struct HdTx { ++ struct HdTx *next; ++ size_t off; ++ size_t len; ++ char *data; ++} HdTx; ++ ++static HdTx *hd_tx_head = NULL; ++static HdTx *hd_tx_tail = NULL; ++static size_t hd_tx_bytes = 0; ++ ++static void hd_tx_clear(void) ++{ ++ HdTx *q = hd_tx_head; ++ while (q) { ++ HdTx *next = q->next; ++ free(q->data); ++ free(q); ++ q = next; ++ } ++ hd_tx_head = hd_tx_tail = NULL; ++ hd_tx_bytes = 0; ++} ++ ++static void hd_tx_enqueue(const char *data, size_t len) ++{ ++ HdTx *q; ++ if (!len) return; ++ q = (HdTx *)malloc(sizeof(*q)); ++ if (!q) return; ++ q->data = (char *)malloc(len); ++ if (!q->data) { ++ free(q); ++ return; ++ } ++ memcpy(q->data, data, len); ++ q->next = NULL; ++ q->off = 0; ++ q->len = len; ++ if (hd_tx_tail) ++ hd_tx_tail->next = q; ++ else ++ hd_tx_head = q; ++ hd_tx_tail = q; ++ hd_tx_bytes += len; ++} ++ ++/* Flush queued JOE -> helper messages without ever blocking the editor. */ ++static void hd_tx_flush(void) ++{ ++ while (hd_fd >= 0 && hd_tx_head) { ++ HdTx *q = hd_tx_head; ++ ssize_t n = write(hd_fd, q->data + q->off, q->len - q->off); ++ if (n > 0) { ++ q->off += (size_t)n; ++ hd_tx_bytes -= (size_t)n; ++ if (q->off == q->len) { ++ hd_tx_head = q->next; ++ if (!hd_tx_head) ++ hd_tx_tail = NULL; ++ free(q->data); ++ free(q); ++ } ++ } else if (n < 0 && (errno == EINTR)) { ++ continue; ++ } else if (n < 0 && ++#ifdef EAGAIN ++#ifdef EWOULDBLOCK ++#if EAGAIN == EWOULDBLOCK ++ errno == EAGAIN ++#else ++ (errno == EAGAIN || errno == EWOULDBLOCK) ++#endif ++#else ++ errno == EAGAIN ++#endif ++#else ++ errno == EWOULDBLOCK ++#endif ++ ) { ++ return; ++ } else { ++ close(hd_fd); ++ hd_fd = -1; ++ hd_active = 0; ++ hd_rx_len = 0; ++ hd_tx_clear(); ++ return; ++ } ++ } ++} ++ ++static int hexval(int c) ++{ ++ if (c >= '0' && c <= '9') return c - '0'; ++ if (c >= 'a' && c <= 'f') return c - 'a' + 10; ++ if (c >= 'A' && c <= 'F') return c - 'A' + 10; ++ return -1; ++} ++ ++static void send_local(const char *s, size_t n) ++{ ++ if (hd_fd < 0 || hd_in_apply) return; ++ hd_tx_enqueue(s, n); ++ hd_tx_flush(); ++} ++ ++static void local_hex(const char *data, ptrdiff_t len, char *out) ++{ ++ static const char hex[] = "0123456789abcdef"; ++ ptrdiff_t i; ++ for (i = 0; i < len; ++i) { ++ unsigned char c = (unsigned char)data[i]; ++ out[i * 2] = hex[c >> 4]; ++ out[i * 2 + 1] = hex[c & 15]; ++ } ++ out[len * 2] = 0; ++} ++ ++void hd_ipc_init(void) ++{ ++ const char *path = getenv("JOE_HEDGE_SOCKET"); ++ struct sockaddr_un sa; ++ int fl; ++ ++ if (!path || !*path || hd_fd >= 0) return; ++ if (strlen(path) >= sizeof(sa.sun_path)) return; ++ ++ hd_fd = socket(AF_UNIX, SOCK_STREAM, 0); ++ if (hd_fd < 0) { ++ hd_fd = -1; ++ return; ++ } ++ ++ memset(&sa, 0, sizeof(sa)); ++ sa.sun_family = AF_UNIX; ++ strncpy(sa.sun_path, path, sizeof(sa.sun_path) - 1); ++ ++ if (connect(hd_fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) { ++ close(hd_fd); ++ hd_fd = -1; ++ return; ++ } ++ ++ fl = fcntl(hd_fd, F_GETFL, 0); ++ if (fl >= 0) (void)fcntl(hd_fd, F_SETFL, fl | O_NONBLOCK); ++ hd_active = 1; ++ hd_tx_flush(); ++} ++ ++static P *pointer_at_byte(B *b, off_t pos, const char *name) ++{ ++ P *p; ++ ++ if (!b || pos < 0 || pos > b->eof->byte) ++ return NULL; ++ ++ /* pfwrd() returns NULL when it steps through the EOF sentinel. That is ++ * inconvenient for an insertion exactly at EOF, so use the real EOF ++ * pointer directly in that case. */ ++ if (pos == b->eof->byte) ++ return pdup(b->eof, name); ++ ++ p = pdup(b->bof, name); ++ if (!pfwrd(p, pos)) { ++ prm(p); ++ return NULL; ++ } ++ return p; ++} ++ ++static void remote_insert(B *b, off_t pos, const unsigned char *data, size_t len) ++{ ++ P *p; ++ if (!b || pos < 0 || pos > b->eof->byte || len == 0) return; ++ p = pointer_at_byte(b, pos, "hd_remote_insert"); ++ if (!p) return; ++ hd_in_apply = 1; ++ binsm(p, (const char *)data, (ptrdiff_t)len); ++ hd_in_apply = 0; ++ prm(p); ++} ++ ++static void remote_delete(B *b, off_t pos, off_t len) ++{ ++ P *p, *q; ++ if (!b || pos < 0 || len <= 0 || pos + len > b->eof->byte) return; ++ p = pointer_at_byte(b, pos, "hd_remote_delete"); ++ q = pointer_at_byte(b, pos + len, "hd_remote_delete"); ++ if (!p || !q) { ++ if (p) prm(p); ++ if (q) prm(q); ++ return; ++ } ++ hd_in_apply = 1; ++ bdel(p, q); ++ hd_in_apply = 0; ++ prm(p); ++ prm(q); ++} ++ ++static void remote_replace(B *b, const unsigned char *data, size_t len) ++{ ++ P *p, *q; ++ if (!b || !b->bof || !b->eof) return; ++ ++ p = pdup(b->bof, "hd_remote_replace"); ++ q = pdup(b->eof, "hd_remote_replace"); ++ if (!p || !q) { ++ if (p) prm(p); ++ if (q) prm(q); ++ return; ++ } ++ ++ hd_in_apply = 1; ++ if (p->byte != q->byte) ++ bdel(p, q); ++ if (len) ++ binsm(p, (const char *)data, (ptrdiff_t)len); ++ hd_in_apply = 0; ++ ++ prm(p); ++ prm(q); ++} ++ ++/* Move a window's cursor to an absolute byte offset -- used after applying ++ * a remote update (e.g. an AI integration finishing an answer) so the user ++ * lands back at the next input prompt instead of wherever bdel()/binsm()'s ++ * pointer fixups happened to leave the cursor. bw is trusted to belong to ++ * hd_target_buf; callers must check that themselves. */ ++static void remote_set_cursor(BW *bw, off_t pos) ++{ ++ if (!bw || !bw->cursor || !bw->b || pos < 0 || pos > bw->b->eof->byte) return; ++ p_goto_bof(bw->cursor); ++ pfwrd(bw->cursor, pos); ++} ++ ++/* Status-line message (e.g. "OFFLINE -- edits are not syncing"), shown the ++ * same way JOE's own "Read only" / "No such command" notices are: msgnw() ++ * only stores the POINTER it's given, so the string needs storage that ++ * outlives this call -- a static buffer, overwritten each time, rather ++ * than a stack buffer or a leaked strdup() for what's a low-frequency, ++ * single-slot notification (only one message is ever shown at a time). */ ++#define HD_MSG_BUF_SIZE 256 ++static char hd_msg_buf[HD_MSG_BUF_SIZE]; ++ ++static void remote_show_message(BW *bw, const char *msg, size_t len) ++{ ++ if (!bw || !bw->parent) return; ++ if (len >= HD_MSG_BUF_SIZE) len = HD_MSG_BUF_SIZE - 1; ++ memcpy(hd_msg_buf, msg, len); ++ hd_msg_buf[len] = 0; ++ msgnw(bw->parent, hd_msg_buf); ++} ++ ++/* Apply all complete newline-terminated commands. We intentionally process ++ * at most a bounded number per editor loop so a peer cannot starve keyboard ++ * input forever. ++ */ ++void hd_ipc_poll(void) ++{ ++ ssize_t n; ++ size_t start, end; ++ const char *nl; ++ B *target; ++ BW *target_bw; ++ ++ if (hd_fd < 0) { ++ hd_ipc_init(); ++ return; ++ } ++ ++ hd_tx_flush(); ++ if (hd_fd < 0) ++ return; ++ ++ for (;;) { ++ n = read(hd_fd, hd_rx + hd_rx_len, sizeof(hd_rx) - hd_rx_len - 1); ++ if (n > 0) { ++ hd_rx_len += (size_t)n; ++ hd_rx[hd_rx_len] = 0; ++ } else if (n == 0) { ++ close(hd_fd); ++ hd_fd = -1; ++ hd_active = 0; ++ hd_rx_len = 0; ++ hd_tx_clear(); ++ return; ++ } else if (errno == EINTR) { ++ continue; ++ } else if ( ++#ifdef EAGAIN ++#ifdef EWOULDBLOCK ++#if EAGAIN == EWOULDBLOCK ++ errno == EAGAIN ++#else ++ (errno == EAGAIN || errno == EWOULDBLOCK) ++#endif ++#else ++ errno == EAGAIN ++#endif ++#else ++ errno == EWOULDBLOCK ++#endif ++ ) { ++ break; ++ } else { ++ close(hd_fd); ++ hd_fd = -1; ++ hd_active = 0; ++ hd_rx_len = 0; ++ hd_tx_clear(); ++ return; ++ } ++ if ((size_t)n == 0) break; ++ if (hd_rx_len + 1 >= sizeof(hd_rx)) { ++ hd_rx_len = 0; ++ hd_tx_clear(); ++ return; ++ } ++ } ++ ++ /* Lock onto the note's buffer the first time we see a real text window. ++ * TYPEPW (prompt windows: search/replace/filename entry) is deliberately ++ * excluded from the lock -- those are ordinary B buffers too, and locking ++ * onto one by accident would route the note's remote edits into whatever ++ * the user last typed a filename into. */ ++ if (!hd_target_buf && maint && maint->curwin && ++ (maint->curwin->watom->what & TYPETW)) { ++ hd_target_buf = ((BW *)maint->curwin->object)->b; ++ } ++ if (!hd_target_buf) return; ++ ++ target = NULL; ++ target_bw = NULL; ++ if (maint && maint->curwin && (maint->curwin->watom->what & (TYPETW | TYPEPW))) { ++ BW *bw = (BW *)maint->curwin->object; ++ if (bw->b == hd_target_buf) { ++ target_bw = bw; ++ target = bw->b; ++ } ++ } ++ if (!target) { ++ /* The locked buffer isn't the focused window right now (user has a ++ * prompt open, or split to another file). Apply directly to the ++ * buffer -- bdel()/binsm() only need P pointers into it, not a ++ * window -- and skip the redraw; it happens naturally once the ++ * user's view returns to this buffer. */ ++ target = hd_target_buf; ++ } ++ ++ start = 0; ++ while (start < hd_rx_len) { ++ nl = memchr(hd_rx + start, '\n', hd_rx_len - start); ++ if (!nl) break; ++ end = (size_t)(nl - hd_rx); ++ hd_rx[end] = 0; ++ ++ if (hd_rx[start] == 'R') { ++ char *s = hd_rx + start + 1; ++ size_t hexlen; ++ size_t bytes; ++ unsigned char *buf = NULL; ++ size_t i; ++ while (*s == ' ') ++s; ++ hexlen = strlen(s); ++ if (!(hexlen & 1) && hexlen <= 65500) { ++ bytes = hexlen / 2; ++ buf = (unsigned char *)malloc(bytes ? bytes : 1); ++ if (buf) { ++ for (i = 0; i < bytes; ++i) { ++ int hi = hexval((unsigned char)s[i * 2]); ++ int lo = hexval((unsigned char)s[i * 2 + 1]); ++ if (hi < 0 || lo < 0) break; ++ buf[i] = (unsigned char)((hi << 4) | lo); ++ } ++ if (i == bytes) ++ remote_replace(target, buf, bytes); ++ free(buf); ++ } ++ } ++ } else if (hd_rx[start] == 'I') { ++ char *s = hd_rx + start + 1; ++ char *ep; ++ unsigned long long pos = strtoull(s, &ep, 10); ++ size_t hexlen; ++ size_t bytes; ++ unsigned char *buf; ++ size_t i; ++ while (*ep == ' ') ++ep; ++ hexlen = strlen(ep); ++ if (hexlen && !(hexlen & 1) && hexlen <= 65500) { ++ bytes = hexlen / 2; ++ buf = (unsigned char *)malloc(bytes); ++ if (buf) { ++ int hi, lo; ++ for (i = 0; i < bytes; ++i) { ++ hi = hexval((unsigned char)ep[i * 2]); ++ lo = hexval((unsigned char)ep[i * 2 + 1]); ++ if (hi < 0 || lo < 0) break; ++ buf[i] = (unsigned char)((hi << 4) | lo); ++ } ++ if (i == bytes) ++ remote_insert(target, (off_t)pos, buf, bytes); ++ free(buf); ++ } ++ } ++ } else if (hd_rx[start] == 'D') { ++ char *s = hd_rx + start + 1; ++ char *ep; ++ unsigned long long pos = strtoull(s, &ep, 10); ++ unsigned long long len; ++ while (*ep == ' ') ++ep; ++ len = strtoull(ep, &ep, 10); ++ remote_delete(target, (off_t)pos, (off_t)len); ++ } else if (hd_rx[start] == 'C') { ++ char *s = hd_rx + start + 1; ++ char *ep; ++ unsigned long long pos = strtoull(s, &ep, 10); ++ if (target_bw) ++ remote_set_cursor(target_bw, (off_t)pos); ++ } else if (hd_rx[start] == 'M') { ++ char *s = hd_rx + start + 1; ++ size_t hexlen; ++ while (*s == ' ') ++s; ++ hexlen = strlen(s); ++ if (target_bw && hexlen && !(hexlen & 1) && hexlen / 2 < HD_MSG_BUF_SIZE) { ++ size_t bytes = hexlen / 2, i; ++ unsigned char buf[HD_MSG_BUF_SIZE]; ++ int hi, lo, ok = 1; ++ for (i = 0; i < bytes; ++i) { ++ hi = hexval((unsigned char)s[i * 2]); ++ lo = hexval((unsigned char)s[i * 2 + 1]); ++ if (hi < 0 || lo < 0) { ok = 0; break; } ++ buf[i] = (unsigned char)((hi << 4) | lo); ++ } ++ if (ok) ++ remote_show_message(target_bw, (const char *)buf, bytes); ++ } ++ } ++ ++ start = end + 1; ++ hd_rx[end] = '\n'; ++ } ++ ++ if (start) { ++ size_t remain = hd_rx_len - start; ++ memmove(hd_rx, hd_rx + start, remain); ++ hd_rx_len = remain; ++ } ++ ++ /* Force the text window itself to regenerate from the changed buffer. */ ++ if (target_bw) ++ bwgen(target_bw, 1, 1); ++} ++ ++void hd_ipc_local_insert(B *b, off_t pos, const char *data, ptrdiff_t len) ++{ ++ size_t outlen; ++ char *out; ++ int n; ++ ++ if (hd_fd < 0 || !hd_active || hd_in_apply || !b || len <= 0) return; ++ if (hd_target_buf && b != hd_target_buf) return; /* not the note buffer */ ++ if ((size_t)len > 32700) return; ++ outlen = (size_t)len * 2 + 64; ++ out = (char *)malloc(outlen); ++ if (!out) return; ++ n = snprintf(out, outlen, "I %lld ", (long long)pos); ++ if (n > 0 && (size_t)n < outlen) { ++ local_hex(data, len, out + n); ++ n += (int)((size_t)len * 2); ++ out[n++] = '\n'; ++ send_local(out, (size_t)n); ++ } ++ free(out); ++} ++ ++void hd_ipc_local_delete(B *b, off_t pos, ptrdiff_t len) ++{ ++ char out[128]; ++ int n; ++ if (hd_fd < 0 || !hd_active || hd_in_apply || !b || len <= 0) return; ++ if (hd_target_buf && b != hd_target_buf) return; /* not the note buffer */ ++ n = snprintf(out, sizeof(out), "D %lld %lld\n", ++ (long long)pos, (long long)len); ++ if (n > 0) send_local(out, (size_t)n); ++} ++ ++int hd_ipc_applying(void) ++{ ++ return hd_in_apply; ++} ++ ++void hd_ipc_close(void) ++{ ++ if (hd_fd >= 0) close(hd_fd); ++ hd_fd = -1; ++ hd_active = 0; ++ hd_rx_len = 0; ++ hd_tx_clear(); ++} ++ ++#else ++ ++void hd_ipc_init(void) {} ++void hd_ipc_poll(void) {} ++void hd_ipc_local_insert(B *b, off_t pos, const char *data, ptrdiff_t len) ++{ (void)b; (void)pos; (void)data; (void)len; } ++void hd_ipc_local_delete(B *b, off_t pos, ptrdiff_t len) ++{ (void)b; (void)pos; (void)len; } ++int hd_ipc_applying(void) { return 0; } ++void hd_ipc_close(void) {} ++ ++#endif +diff -ruN '--exclude=*.o' '--exclude=.deps' '--exclude=Makefile' '--exclude=Makefile.in' '--exclude=autoconf.h*' '--exclude=joe' '--exclude=.dirstamp' '--exclude=stamp-h1' joe-src/joe/hd_ipc.h build/joe-4.8/joe/hd_ipc.h +--- joe-src/joe/hd_ipc.h 1970-01-01 00:00:00.000000000 +0000 ++++ build/joe-4.8/joe/hd_ipc.h 2026-09-17 19:06:56.900359508 +0000 +@@ -0,0 +1,18 @@ ++#ifndef HD_IPC_H ++#define HD_IPC_H ++ ++/* ++ * Optional HedgeDoc editor bridge. ++ * ++ * JOE talks to a per-editor helper over a Unix domain socket. The helper ++ * owns Socket.IO/OT; JOE only reports local buffer mutations and applies ++ * remote mutations to the real B buffer. ++ */ ++void hd_ipc_init(void); ++void hd_ipc_poll(void); ++void hd_ipc_local_insert(B *b, off_t pos, const char *data, ptrdiff_t len); ++void hd_ipc_local_delete(B *b, off_t pos, ptrdiff_t len); ++int hd_ipc_applying(void); ++void hd_ipc_close(void); ++ ++#endif +diff -ruN '--exclude=*.o' '--exclude=.deps' '--exclude=Makefile' '--exclude=Makefile.in' '--exclude=autoconf.h*' '--exclude=joe' '--exclude=.dirstamp' '--exclude=stamp-h1' joe-src/joe/main.c build/joe-4.8/joe/main.c +--- joe-src/joe/main.c 2026-09-17 19:01:43.048359059 +0000 ++++ build/joe-4.8/joe/main.c 2026-09-17 19:08:38.393715715 +0000 +@@ -6,6 +6,7 @@ + * This file is part of JOE (Joe's Own Editor) + */ + #include "types.h" ++#include "hd_ipc.h" + + #ifdef MOUSE_GPM + #include <gpm.h> +@@ -131,6 +132,7 @@ + vsrm(exmsg); + exmsg = NULL; + } ++ hd_ipc_poll(); + edupd(1); + if (!ahead && !have) + ahead = 1; +diff -ruN '--exclude=*.o' '--exclude=.deps' '--exclude=Makefile' '--exclude=Makefile.in' '--exclude=autoconf.h*' '--exclude=joe' '--exclude=.dirstamp' '--exclude=stamp-h1' joe-src/joe/tty.c build/joe-4.8/joe/tty.c +--- joe-src/joe/tty.c 2026-09-17 19:01:43.052359059 +0000 ++++ build/joe-4.8/joe/tty.c 2026-09-17 19:08:38.393715715 +0000 +@@ -6,6 +6,9 @@ + * This file is part of JOE (Joe's Own Editor) + */ + #include "types.h" ++#include "hd_ipc.h" ++#include <sys/select.h> ++#include <errno.h> + + /* For MAC OS */ + #ifdef HAVE_UTIL_H +@@ -307,6 +310,9 @@ + tim *= 1000; + val.it_value.tv_sec = 0; + val.it_value.tv_usec = tim; ++ } else if (getenv("JOE_HEDGE_SOCKET")) { ++ val.it_value.tv_sec = 0; ++ val.it_value.tv_usec = 100000; + } else { + val.it_value.tv_sec = 1; + val.it_value.tv_usec = 0; +@@ -618,18 +624,66 @@ + + time_t last_time; + ++static int hd_wait_input(int *mpx_ready, int *term_ready) ++{ ++ fd_set rfds; ++ struct timeval tv; ++ int r; ++ int mfd = mpxfd; ++ int tfd = fileno(termin); ++ int maxfd = mfd > tfd ? mfd : tfd; ++ ++ FD_ZERO(&rfds); ++ if (mfd >= 0) ++ FD_SET(mfd, &rfds); ++ if (tfd >= 0) ++ FD_SET(tfd, &rfds); ++ tv.tv_sec = 0; ++ tv.tv_usec = 100000; ++ r = select(maxfd + 1, &rfds, NULL, NULL, &tv); ++ if (r < 0) { ++ if (errno == EINTR) ++ return -1; ++ return -2; ++ } ++ if (r == 0) { ++ *mpx_ready = 0; ++ *term_ready = 0; ++ return 0; ++ } ++ *mpx_ready = (mfd >= 0 && FD_ISSET(mfd, &rfds)); ++ *term_ready = (tfd >= 0 && FD_ISSET(tfd, &rfds)); ++ return 1; ++} ++ + char ttgetc(void) + { + MACRO *m; + ptrdiff_t mystat; + time_t new_time; + int flg; +- ++ int hd_mpx_ready = 1; ++ int hd_term_ready = 1; ++ int hd_enabled = (getenv("JOE_HEDGE_SOCKET") != NULL); + + tickon(); + + loop: + flg = 0; ++ if (hd_enabled && !have) { ++ int hr = hd_wait_input(&hd_mpx_ready, &hd_term_ready); ++ if (hr == 0) { ++ hd_ipc_poll(); ++ edupd(1); ++ goto loop; ++ } ++ if (hr == -1) ++ goto loop; ++ if (hr == -2) { ++ ttsig(0); ++ return 0; ++ } ++ } + /* Status line clock */ + new_time = time(NULL); + if (new_time != last_time) { +@@ -657,11 +711,12 @@ + ttflsh(); + } + if (ticked) { ++ hd_ipc_poll(); + edupd(flg); + ttflsh(); + tickon(); + } +- if (ackkbd != -1) { ++ if (ackkbd != -1 && (hd_mpx_ready || !hd_enabled)) { + if (!have) { /* Wait for input */ + mystat = read(mpxfd, &pack, pack.data - (char *)&pack); + +@@ -699,6 +754,15 @@ + } + if (have) { + have = 0; ++ } else if (hd_enabled) { ++ if (!hd_term_ready) ++ goto loop; ++ if (read(fileno(termin), &havec, 1) < 1) { ++ if (winched || ticked) ++ goto loop; ++ else ++ ttsig(0); ++ } + } else { + if (read(fileno(termin), &havec, 1) < 1) { + if (winched || ticked) +Binary files joe-src/joe/util/checkwidths and build/joe-4.8/joe/util/checkwidths differ +Binary files joe-src/joe/util/stringify and build/joe-4.8/joe/util/stringify differ +Binary files joe-src/joe/util/termidx and build/joe-4.8/joe/util/termidx differ +Binary files joe-src/joe/util/uniproc and build/joe-4.8/joe/util/uniproc differ