Initial import of LogDarioSeq baseline

Establishes version control for the personal Logseq DB fork before
starting the server-client architecture migration and domain features
described in docs/agent-guide and the approved implementation plan.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5 committed 2026-08-25 15:32:15 +02:00
commit 40631362b3
2016 files changed
+543898

No files matched your search

+322
View File
@@ -0,0 +1,322 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<'USAGE'
Usage: agent_bridge_demo.sh [options]
Creates a fresh Logseq graph, starts `logseq agent bridge`, writes a routable
task after the bridge listener is ready, and verifies that a fake Codex master
session received the task dispatch.
Options:
--cli PATH Path to static/logseq-cli.js. Default: <repo-root>/static/logseq-cli.js
--root-dir DIR Logseq CLI root dir. Default: a new temp dir
--graph NAME Graph name. Default: agent-bridge-demo-<timestamp>
--repo-root DIR Repository root. Default: inferred from this script
--timeout-sec N Wait timeout for bridge events. Default: 45
-h, --help Show this help
USAGE
}
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$script_dir/../.." && pwd)"
cli_path=""
root_dir=""
graph="agent-bridge-demo-$(date +%s)"
timeout_sec=45
agent_name="AgentBridgeDemo"
task_title="AgentBridge demo task: mark this block in review"
expected_session="thread-agent-bridge-demo"
bridge_pid=""
graph_created=0
while [[ $# -gt 0 ]]; do
case "$1" in
--cli)
cli_path="$2"
shift 2
;;
--root-dir)
root_dir="$2"
shift 2
;;
--graph)
graph="$2"
shift 2
;;
--repo-root)
repo_root="$2"
shift 2
;;
--timeout-sec)
timeout_sec="$2"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown option: $1" >&2
usage >&2
exit 2
;;
esac
done
cli_path="${cli_path:-$repo_root/static/logseq-cli.js}"
root_dir="${root_dir:-$(mktemp -d "${TMPDIR:-/tmp}/logseq-agent-bridge-demo.XXXXXX")}"
config_path="$root_dir/cli.edn"
work_dir="$root_dir/agent-bridge-demo"
fake_bin="$work_dir/fake-bin"
bridge_log="$work_dir/agent-bridge.log"
bridge_err="$work_dir/agent-bridge.err"
codex_log="$work_dir/codex-invocations.jsonl"
cleanup() {
local status=$?
if [[ -n "${bridge_pid:-}" ]] && kill -0 "$bridge_pid" 2>/dev/null; then
kill "$bridge_pid" 2>/dev/null || true
wait "$bridge_pid" 2>/dev/null || true
fi
if [[ "$graph_created" -eq 1 ]]; then
node "$cli_path" --root-dir "$root_dir" --config "$config_path" --output json server stop --graph "$graph" >/dev/null 2>&1 || true
fi
exit "$status"
}
trap cleanup EXIT INT TERM
require_command() {
if ! command -v "$1" >/dev/null 2>&1; then
echo "Required command is missing: $1" >&2
exit 2
fi
}
json_result() {
python3 -c 'import json,sys; print(json.load(sys.stdin)["data"]["result"])'
}
json_result_first() {
python3 -c 'import json,sys; r=json.load(sys.stdin)["data"]["result"]; print(r[0] if isinstance(r, list) else r)'
}
run_cli_json() {
node "$cli_path" --root-dir "$root_dir" --config "$config_path" --output json "$@"
}
wait_for_file_text() {
local path="$1"
local text="$2"
local deadline=$((SECONDS + timeout_sec))
while (( SECONDS < deadline )); do
if [[ -f "$path" ]] && grep -Fq "$text" "$path"; then
return 0
fi
if [[ -n "${bridge_pid:-}" ]] && ! kill -0 "$bridge_pid" 2>/dev/null; then
echo "agent bridge exited before '$text'" >&2
[[ -f "$bridge_log" ]] && cat "$bridge_log" >&2
[[ -f "$bridge_err" ]] && cat "$bridge_err" >&2
exit 1
fi
sleep 0.2
done
echo "Timed out waiting for '$text' in $path" >&2
[[ -f "$bridge_log" ]] && cat "$bridge_log" >&2
[[ -f "$bridge_err" ]] && cat "$bridge_err" >&2
exit 1
}
query_task_status() {
run_cli_json query --graph "$graph" --query "[:find ?status-ident . :where [$1 :logseq.property/status ?status] [?status :db/ident ?status-ident]]" | json_result
}
query_agent_session() {
local payload
payload="$(run_cli_json query --graph "$graph" --query "[:find ?session . :where [$1 :logseq.property.agent/session-id ?session]]")"
python3 - "$root_dir" "$config_path" "$graph" "$cli_path" "$payload" <<'PY'
import json
import subprocess
import sys
payload = json.loads(sys.argv[5])
value = payload.get("data", {}).get("result")
if isinstance(value, int):
root_dir, config_path, graph, cli_path = sys.argv[1:5]
query = f"[:find ?title . :where [{value} :block/title ?title]]"
resolved = subprocess.check_output(
[
"node",
cli_path,
"--root-dir",
root_dir,
"--config",
config_path,
"--output",
"json",
"query",
"--graph",
graph,
"--query",
query,
],
text=True,
)
value = json.loads(resolved)["data"]["result"]
print("" if value is None else value)
PY
}
write_fake_codex() {
mkdir -p "$fake_bin"
cat > "$fake_bin/codex" <<'FAKE_CODEX'
#!/usr/bin/env bash
set -euo pipefail
if [[ "$#" -eq 1 && "$1" == "--version" ]]; then
echo "codex-cli 0.0.0-agent-bridge-demo"
exit 0
fi
if [[ "$#" -ge 6 && "$1" == "--sandbox" && "$2" == "danger-full-access" && "$3" == "exec" && "$4" == "--json" && "$5" == "--skip-git-repo-check" ]]; then
prompt="$6"
python3 - "$CODEX_FAKE_LOG" "$prompt" "$@" <<'PY'
import json
import pathlib
import sys
log_path = pathlib.Path(sys.argv[1])
prompt = sys.argv[2]
args = sys.argv[3:]
log_path.parent.mkdir(parents=True, exist_ok=True)
with log_path.open("a", encoding="utf8") as f:
f.write(json.dumps({"event": "start", "args": args, "prompt": prompt}, ensure_ascii=False) + "\n")
PY
printf '{"type":"thread.started","thread_id":"thread-agent-bridge-demo"}\n'
exit 0
fi
if [[ "$#" -ge 8 && "$1" == "--sandbox" && "$2" == "danger-full-access" && "$3" == "exec" && "$4" == "resume" && "$5" == "--json" && "$6" == "--skip-git-repo-check" ]]; then
session_id="$7"
prompt="$8"
python3 - "$CODEX_FAKE_LOG" "$session_id" "$prompt" "$@" <<'PY'
import json
import pathlib
import sys
log_path = pathlib.Path(sys.argv[1])
session_id = sys.argv[2]
prompt = sys.argv[3]
args = sys.argv[4:]
log_path.parent.mkdir(parents=True, exist_ok=True)
with log_path.open("a", encoding="utf8") as f:
f.write(json.dumps({"event": "resume", "session": session_id, "args": args, "prompt": prompt}, ensure_ascii=False) + "\n")
PY
block_uuid="$(python3 - "$prompt" <<'PY'
import re
import sys
match = re.search(r"^Block UUID:\s*([0-9a-fA-F-]+)\s*$", sys.argv[1], re.MULTILINE)
if not match:
raise SystemExit("Block UUID not found in AgentBridge prompt")
print(match.group(1))
PY
)"
node "$DEMO_CLI" --root-dir "$DEMO_ROOT_DIR" --config "$DEMO_CONFIG" --output json upsert task --graph "$DEMO_GRAPH" --uuid "$block_uuid" --status in-review >/dev/null
node "$DEMO_CLI" --root-dir "$DEMO_ROOT_DIR" --config "$DEMO_CONFIG" --output json upsert block --graph "$DEMO_GRAPH" --uuid "$block_uuid" --update-properties '{"Agent Session ID" "thread-agent-bridge-demo"}' >/dev/null
printf '{"type":"thread.started","thread_id":"%s"}\n' "$session_id"
exit 0
fi
echo "unexpected codex args: $*" >&2
exit 2
FAKE_CODEX
chmod +x "$fake_bin/codex"
}
require_command node
require_command python3
mkdir -p "$work_dir"
printf '{:output-format :json :agent-name "%s"}\n' "$agent_name" > "$config_path"
write_fake_codex
echo "creating graph: $graph"
echo "root dir: $root_dir"
run_cli_json graph create --graph "$graph" >/dev/null
graph_created=1
echo "starting agent bridge"
PATH="$fake_bin:$PATH" \
CODEX_FAKE_LOG="$codex_log" \
DEMO_CLI="$cli_path" \
DEMO_ROOT_DIR="$root_dir" \
DEMO_CONFIG="$config_path" \
DEMO_GRAPH="$graph" \
node "$cli_path" --root-dir "$root_dir" --config "$config_path" --output human agent bridge --graph "$graph" >"$bridge_log" 2>"$bridge_err" &
bridge_pid=$!
wait_for_file_text "$bridge_log" "listening graph changes"
task_id="$(run_cli_json upsert task --graph "$graph" --target-page AgentBridgeDemo --content "$task_title" --status todo | json_result_first)"
run_cli_json upsert block --graph "$graph" --id "$task_id" --update-properties "{\"Assignee\" \"$agent_name\"}" >/dev/null
deadline=$((SECONDS + timeout_sec))
task_status=""
agent_session=""
while (( SECONDS < deadline )); do
task_status="$(query_task_status "$task_id")"
agent_session="$(query_agent_session "$task_id")"
if [[ "$task_status" == "logseq.property/status.in-review" && "$agent_session" == "$expected_session" ]]; then
break
fi
if [[ -n "${bridge_pid:-}" ]] && ! kill -0 "$bridge_pid" 2>/dev/null; then
echo "agent bridge exited before verification completed" >&2
cat "$bridge_log" >&2
cat "$bridge_err" >&2
exit 1
fi
sleep 0.5
done
if [[ "$task_status" != "logseq.property/status.in-review" ]]; then
echo "Expected task status in-review, got: ${task_status:-<empty>}" >&2
cat "$bridge_log" >&2
cat "$bridge_err" >&2
exit 1
fi
if [[ "$agent_session" != "$expected_session" ]]; then
echo "Expected agent-session-id $expected_session, got: ${agent_session:-<empty>}" >&2
cat "$bridge_log" >&2
cat "$bridge_err" >&2
exit 1
fi
python3 - "$codex_log" "$task_title" "$graph" <<'PY'
import json
import pathlib
import sys
log_path = pathlib.Path(sys.argv[1])
task_title = sys.argv[2]
graph = sys.argv[3]
lines = [json.loads(line) for line in log_path.read_text(encoding="utf8").splitlines() if line.strip()]
resume_lines = [line for line in lines if line.get("event") == "resume"]
if len(resume_lines) != 1:
raise SystemExit(f"expected one Codex resume invocation, got {len(resume_lines)}")
prompt = resume_lines[0]["prompt"]
if task_title not in prompt:
raise SystemExit("task title missing from Codex prompt")
if f"Graph: {graph}" not in prompt:
raise SystemExit("graph missing from Codex prompt")
if "Block UUID:" not in prompt:
raise SystemExit("block uuid missing from Codex prompt")
if "Request kind: task" not in prompt:
raise SystemExit("request kind missing from Codex prompt")
PY
echo "task status: in-review"
echo "agent-session-id: $agent_session"
echo "agent bridge demo completed"
+685
View File
@@ -0,0 +1,685 @@
#!/usr/bin/env python3
import argparse
import json
import os
import pathlib
import subprocess
import time
TASK_TITLE = "Test AgentBridge task routing and completion status"
EXPECTED_SESSION = "thread-e2e-agent-bridge"
PARALLEL_TASK_TITLES = [
"测试 agent bridge 并行执行任务 1",
"测试 agent bridge 并行执行任务 2",
]
def write_fake_codex(fake_bin):
fake_codex = fake_bin / "codex"
fake_codex.parent.mkdir(parents=True, exist_ok=True)
fake_codex.write_text(
"""#!/usr/bin/env python3
import json
import os
import pathlib
import re
import sys
import time
args = sys.argv[1:]
if args == ["--version"]:
print("codex-cli 0.0.0-e2e")
sys.exit(0)
if args[:5] == ["--sandbox", "danger-full-access", "exec", "--json", "--skip-git-repo-check"]:
prompt = args[5] if len(args) > 5 else ""
block_uuid_match = re.search(r"^Block UUID: (.+)$", prompt, re.MULTILINE)
block_uuid = block_uuid_match.group(1) if block_uuid_match else None
log_path = pathlib.Path(os.environ["CODEX_FAKE_LOG"])
log_path.parent.mkdir(parents=True, exist_ok=True)
with log_path.open("a", encoding="utf8") as f:
f.write(json.dumps(
{"event": "start", "time": time.time(), "args": args, "prompt": prompt, "block_uuid": block_uuid},
ensure_ascii=False) + "\\n")
delay = float(os.environ.get("CODEX_FAKE_DELAY_SECONDS", "0"))
if delay > 0:
time.sleep(delay)
if os.environ.get("CODEX_FAKE_SESSION_BY_UUID") == "1" and block_uuid:
session_id = "thread-e2e-agent-bridge-" + re.sub(r"[^A-Za-z0-9]", "", block_uuid)[-12:]
else:
session_id = "thread-e2e-agent-bridge"
with log_path.open("a", encoding="utf8") as f:
f.write(json.dumps(
{"event": "session", "time": time.time(), "session": session_id, "block_uuid": block_uuid},
ensure_ascii=False) + "\\n")
print(json.dumps({"type": "thread.started", "thread_id": session_id}), flush=True)
sys.exit(0)
if args[:6] == ["--sandbox", "danger-full-access", "exec", "resume", "--json", "--skip-git-repo-check"]:
session_id = args[6] if len(args) > 6 else ""
prompt = args[7] if len(args) > 7 else ""
comment_uuid_match = re.search(r"^Comment UUID: (.+)$", prompt, re.MULTILINE)
comment_uuid = comment_uuid_match.group(1) if comment_uuid_match else None
block_uuid_match = re.search(r"^Block UUID: (.+)$", prompt, re.MULTILINE)
block_uuid = block_uuid_match.group(1) if block_uuid_match else None
log_path = pathlib.Path(os.environ["CODEX_FAKE_LOG"])
log_path.parent.mkdir(parents=True, exist_ok=True)
with log_path.open("a", encoding="utf8") as f:
f.write(json.dumps(
{"event": "resume", "time": time.time(), "args": args, "prompt": prompt, "comment_uuid": comment_uuid, "block_uuid": block_uuid, "session": session_id},
ensure_ascii=False) + "\\n")
delay = float(os.environ.get("CODEX_FAKE_DELAY_SECONDS", "0"))
if delay > 0:
time.sleep(delay)
with log_path.open("a", encoding="utf8") as f:
f.write(json.dumps(
{"event": "resume-complete", "time": time.time(), "comment_uuid": comment_uuid, "block_uuid": block_uuid, "session": session_id},
ensure_ascii=False) + "\\n")
print(json.dumps({"type": "thread.started", "thread_id": session_id}), flush=True)
sys.exit(0)
print("unexpected codex args: " + repr(args), file=sys.stderr)
sys.exit(2)
""",
encoding="utf8",
)
fake_codex.chmod(0o755)
def run_json(cli, repo_root, root_dir, config, graph, query):
result = subprocess.run(
cli
+ [
"--root-dir",
root_dir,
"--config",
config,
"--output",
"json",
"query",
"--graph",
graph,
"--query",
query,
],
cwd=repo_root,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if result.returncode != 0:
return None
return json.loads(result.stdout).get("data", {}).get("result")
def run_cli(cli, repo_root, root_dir, config, graph, extra_args):
result = subprocess.run(
cli
+ [
"--root-dir",
root_dir,
"--config",
config,
"--output",
"json",
]
+ extra_args,
cwd=repo_root,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if result.returncode != 0:
raise SystemExit(
"CLI command failed: {}\nstdout:\n{}\nstderr:\n{}".format(
" ".join(extra_args), result.stdout, result.stderr
)
)
return json.loads(result.stdout) if result.stdout.strip() else None
def run_cli_with_env(cli, repo_root, root_dir, config, extra_args, env):
result = subprocess.run(
cli
+ [
"--root-dir",
root_dir,
"--config",
config,
"--output",
"json",
]
+ extra_args,
cwd=repo_root,
env=env,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return result
def deref_session_value(cli, repo_root, root_dir, config, graph, value):
if not isinstance(value, int):
return value
return run_json(
cli,
repo_root,
root_dir,
config,
graph,
f"[:find ?title . :where [{value} :block/title ?title]]",
)
def read_text(path):
return path.read_text(encoding="utf8", errors="replace")
def wait_for_log(path, text, process):
deadline = time.time() + 30
while time.time() < deadline:
if path.exists() and text in read_text(path):
return
if process.poll() is not None:
raise SystemExit(
"agent bridge exited before {}\nstdout:\n{}".format(
text, read_text(path)
)
)
time.sleep(0.2)
raise SystemExit("agent bridge did not log {!r}\nstdout:\n{}".format(text, read_text(path)))
def find_task_id(cli, repo_root, root_dir, config, graph, title):
task_id = run_json(
cli,
repo_root,
root_dir,
config,
graph,
'[:find ?e . :where [?e :block/title "{}"]]'.format(title),
)
if task_id is None:
raise SystemExit("task block was not found: {}".format(title))
return task_id
def find_task_uuid(cli, repo_root, root_dir, config, graph, title):
task_uuid = run_json(
cli,
repo_root,
root_dir,
config,
graph,
'[:find ?uuid . :where [?e :block/title "{}"] [?e :block/uuid ?uuid]]'.format(title),
)
if task_uuid is None:
raise SystemExit("task block uuid was not found: {}".format(title))
return task_uuid
def create_task(cli, repo_root, root_dir, config, graph, title):
run_cli(
cli,
repo_root,
root_dir,
config,
graph,
[
"upsert",
"task",
"--graph",
graph,
"--target-page",
"AgentBridgeE2E",
"--content",
title,
"--status",
"todo",
],
)
def assign_task(cli, repo_root, root_dir, config, graph, title=TASK_TITLE):
task_id = find_task_id(cli, repo_root, root_dir, config, graph, title)
run_cli(
cli,
repo_root,
root_dir,
config,
graph,
[
"upsert",
"block",
"--graph",
graph,
"--id",
str(task_id),
"--update-properties",
'{{"Assignee" "{}"}}'.format(os.uname().nodename),
],
)
def read_codex_events(codex_log):
if not codex_log.exists():
return []
return [
json.loads(line)
for line in codex_log.read_text(encoding="utf8").splitlines()
if line.strip()
]
def session_query_for_title(title):
return (
'[:find ?session . :where [?e :block/title "{}"] '
"[?e :logseq.property.agent/session-id ?session]]"
).format(title)
def wait_for_task_sessions(cli, repo_root, root_dir, config, graph, titles, bridge, bridge_log, bridge_err):
deadline = time.time() + 45
sessions = {}
while time.time() < deadline:
sessions = {
title: deref_session_value(
cli,
repo_root,
root_dir,
config,
graph,
run_json(cli, repo_root, root_dir, config, graph, session_query_for_title(title)),
)
for title in titles
}
if all(sessions.values()):
return sessions
if bridge.poll() is not None:
raise SystemExit(
"agent bridge exited early with {}\nstdout:\n{}\nstderr:\n{}".format(
bridge.returncode, read_text(bridge_log), read_text(bridge_err)
)
)
time.sleep(0.5)
raise SystemExit(
"agent-session-id was not written for every task; last sessions={!r}\nstdout:\n{}\nstderr:\n{}".format(
sessions, read_text(bridge_log), read_text(bridge_err)
)
)
def wait_for_codex_event(codex_log, event_name, bridge, bridge_log, bridge_err):
deadline = time.time() + 30
events = []
while time.time() < deadline:
events = read_codex_events(codex_log)
matches = [event for event in events if event.get("event") == event_name]
if matches:
return matches
if bridge.poll() is not None:
raise SystemExit(
"agent bridge exited early with {}\nstdout:\n{}\nstderr:\n{}".format(
bridge.returncode, read_text(bridge_log), read_text(bridge_err)
)
)
time.sleep(0.5)
raise SystemExit("codex event {!r} was not observed; events={!r}".format(event_name, events))
def wait_for_codex_events(codex_log, event_name, count, bridge, bridge_log, bridge_err):
deadline = time.time() + 45
events = []
while time.time() < deadline:
events = read_codex_events(codex_log)
matches = [event for event in events if event.get("event") == event_name]
if len(matches) >= count:
return matches
if bridge.poll() is not None:
raise SystemExit(
"agent bridge exited early with {}\nstdout:\n{}\nstderr:\n{}".format(
bridge.returncode, read_text(bridge_log), read_text(bridge_err)
)
)
time.sleep(0.5)
raise SystemExit("codex event {!r} count {} was not observed; events={!r}".format(event_name, count, events))
def write_comment_blocks_file(path, task_uuid, hostname):
path.write_text(
"""[{{:block/title "Comments"
:block/tags [:logseq.class/Comments]
:logseq.property.comments/blocks [[:block/uuid #uuid "{task_uuid}"]]
:block/children [{{:block/title "[[{hostname}]] please continue from the comment"
:block/tags [:logseq.class/Comment]}}]}}]""".format(
task_uuid=task_uuid,
hostname=hostname,
),
encoding="utf8",
)
def run_comment_mention_check(cli, repo_root, root_dir, config, graph, tmp_dir):
create_task(cli, repo_root, root_dir, config, graph, TASK_TITLE)
fake_bin = tmp_dir / "fake-bin"
bridge_log = tmp_dir / "agent-bridge.log"
bridge_err = tmp_dir / "agent-bridge.err"
codex_log = tmp_dir / "codex-invocations.jsonl"
env = os.environ.copy()
env["PATH"] = str(fake_bin) + os.pathsep + env.get("PATH", "")
env["CODEX_FAKE_LOG"] = str(codex_log)
with bridge_log.open("wb") as out, bridge_err.open("wb") as err:
bridge = subprocess.Popen(
cli
+ [
"--root-dir",
root_dir,
"--config",
config,
"--output",
"human",
"agent",
"bridge",
"--graph",
graph,
],
cwd=repo_root,
env=env,
stdout=out,
stderr=err,
)
try:
wait_for_log(bridge_log, "listening graph changes", bridge)
assign_task(cli, repo_root, root_dir, config, graph)
start_events = wait_for_codex_event(codex_log, "start", bridge, bridge_log, bridge_err)
session_events = wait_for_codex_event(codex_log, "session", bridge, bridge_log, bridge_err)
session = session_events[0].get("session")
resume_events = wait_for_codex_event(codex_log, "resume", bridge, bridge_log, bridge_err)
task_prompt = resume_events[0].get("prompt", "")
assert resume_events[0].get("session") == session, resume_events[0]
assert "Request kind: task" in task_prompt, task_prompt
assert TASK_TITLE in task_prompt, task_prompt
task_id = find_task_id(cli, repo_root, root_dir, config, graph, TASK_TITLE)
task_uuid = find_task_uuid(cli, repo_root, root_dir, config, graph, TASK_TITLE)
blocks_file = tmp_dir / "comment-blocks.edn"
write_comment_blocks_file(blocks_file, task_uuid, os.uname().nodename)
run_cli(
cli,
repo_root,
root_dir,
config,
graph,
[
"upsert",
"block",
"--graph",
graph,
"--target-id",
str(task_id),
"--pos",
"last-child",
"--blocks-file",
str(blocks_file),
],
)
resume_events = wait_for_codex_events(codex_log, "resume", 2, bridge, bridge_log, bridge_err)
comment_event = resume_events[-1]
if comment_event.get("session") != session:
raise SystemExit("comment resumed the wrong master session: {!r}".format(comment_event))
prompt = comment_event.get("prompt", "")
assert "You are handling a Logseq AgentBridge master dispatch request." in prompt, prompt
assert "Request kind: comment" in prompt, prompt
assert "Comment target context:" in prompt, prompt
assert "Requesting comment:" in prompt, prompt
print("agent bridge dispatched comment request to master " + session)
finally:
if bridge.poll() is None:
bridge.terminate()
try:
bridge.wait(timeout=5)
except subprocess.TimeoutExpired:
bridge.kill()
bridge.wait(timeout=5)
def run_parallel_assignment_check(cli, repo_root, root_dir, config, graph, tmp_dir):
for title in PARALLEL_TASK_TITLES:
create_task(cli, repo_root, root_dir, config, graph, title)
fake_bin = tmp_dir / "fake-bin"
bridge_log = tmp_dir / "agent-bridge.log"
bridge_err = tmp_dir / "agent-bridge.err"
codex_log = tmp_dir / "codex-invocations.jsonl"
env = os.environ.copy()
env["PATH"] = str(fake_bin) + os.pathsep + env.get("PATH", "")
env["CODEX_FAKE_LOG"] = str(codex_log)
env["CODEX_FAKE_DELAY_SECONDS"] = "5"
env["CODEX_FAKE_SESSION_BY_UUID"] = "1"
with bridge_log.open("wb") as out, bridge_err.open("wb") as err:
bridge = subprocess.Popen(
cli
+ [
"--root-dir",
root_dir,
"--config",
config,
"--output",
"human",
"agent",
"bridge",
"--graph",
graph,
],
cwd=repo_root,
env=env,
stdout=out,
stderr=err,
)
try:
wait_for_log(bridge_log, "listening graph changes", bridge)
for title in PARALLEL_TASK_TITLES:
assign_task(cli, repo_root, root_dir, config, graph, title)
events = read_codex_events(codex_log)
start_events = [event for event in events if event.get("event") == "start"]
resume_events = wait_for_codex_events(codex_log, "resume", 2, bridge, bridge_log, bridge_err)
complete_events = wait_for_codex_events(codex_log, "resume-complete", 2, bridge, bridge_log, bridge_err)
if len(start_events) != 1 or len(resume_events) != 2:
raise SystemExit("expected one master start and two master resumes, got: {!r}".format(read_codex_events(codex_log)))
first_complete_time = min(event["time"] for event in complete_events)
latest_resume_time = max(event["time"] for event in resume_events)
if latest_resume_time >= first_complete_time:
raise SystemExit(
"master dispatch resumes did not overlap; resumes={!r}, completes={!r}".format(
[event["time"] for event in resume_events],
[event["time"] for event in complete_events],
)
)
prompts = "\n".join(event["prompt"] for event in resume_events)
for title in PARALLEL_TASK_TITLES:
assert title in prompts, prompts
print("agent bridge dispatched tasks concurrently to master")
finally:
if bridge.poll() is None:
bridge.terminate()
try:
bridge.wait(timeout=5)
except subprocess.TimeoutExpired:
bridge.kill()
bridge.wait(timeout=5)
def run_duplicate_bridge_check(cli, repo_root, root_dir, config, graph, tmp_dir):
fake_bin = tmp_dir / "fake-bin"
bridge_log = tmp_dir / "agent-bridge.log"
bridge_err = tmp_dir / "agent-bridge.err"
codex_log = tmp_dir / "codex-invocations.jsonl"
env = os.environ.copy()
env["PATH"] = str(fake_bin) + os.pathsep + env.get("PATH", "")
env["CODEX_FAKE_LOG"] = str(codex_log)
with bridge_log.open("wb") as out, bridge_err.open("wb") as err:
bridge = subprocess.Popen(
cli
+ [
"--root-dir",
root_dir,
"--config",
config,
"--output",
"human",
"agent",
"bridge",
"--graph",
graph,
],
cwd=repo_root,
env=env,
stdout=out,
stderr=err,
)
try:
wait_for_log(bridge_log, "listening graph changes", bridge)
duplicate = subprocess.run(
cli
+ [
"--root-dir",
root_dir,
"--config",
config,
"--output",
"json",
"agent",
"bridge",
"--graph",
graph,
],
cwd=repo_root,
env=env,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=15,
)
output = duplicate.stdout + duplicate.stderr
if duplicate.returncode == 0:
raise SystemExit("duplicate bridge unexpectedly succeeded:\n{}".format(output))
if "agent-bridge-already-running" not in output and "already running" not in output:
raise SystemExit("duplicate bridge did not report the expected lock error:\n{}".format(output))
print("agent bridge rejected duplicate process")
finally:
if bridge.poll() is None:
bridge.terminate()
try:
bridge.wait(timeout=5)
except subprocess.TimeoutExpired:
bridge.kill()
bridge.wait(timeout=5)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--cli", required=True)
parser.add_argument("--root-dir", required=True)
parser.add_argument("--config", required=True)
parser.add_argument("--graph", required=True)
parser.add_argument("--tmp-dir", required=True)
parser.add_argument("--repo-root", required=True)
parser.add_argument("--prepare-fake-codex-only", action="store_true")
parser.add_argument("--assign-after-start", action="store_true")
parser.add_argument("--parallel-assignment-check", action="store_true")
parser.add_argument("--comment-mention-check", action="store_true")
parser.add_argument("--duplicate-bridge-check", action="store_true")
args = parser.parse_args()
repo_root = pathlib.Path(args.repo_root)
tmp_dir = pathlib.Path(args.tmp_dir)
fake_bin = tmp_dir / "fake-bin"
bridge_log = tmp_dir / "agent-bridge.log"
bridge_err = tmp_dir / "agent-bridge.err"
codex_log = tmp_dir / "codex-invocations.jsonl"
cli = ["node", args.cli]
write_fake_codex(fake_bin)
if args.prepare_fake_codex_only:
return
if args.parallel_assignment_check:
run_parallel_assignment_check(cli, repo_root, args.root_dir, args.config, args.graph, tmp_dir)
return
if args.comment_mention_check:
run_comment_mention_check(cli, repo_root, args.root_dir, args.config, args.graph, tmp_dir)
return
if args.duplicate_bridge_check:
run_duplicate_bridge_check(cli, repo_root, args.root_dir, args.config, args.graph, tmp_dir)
return
env = os.environ.copy()
env["PATH"] = str(fake_bin) + os.pathsep + env.get("PATH", "")
env["CODEX_FAKE_LOG"] = str(codex_log)
with bridge_log.open("wb") as out, bridge_err.open("wb") as err:
bridge = subprocess.Popen(
cli
+ [
"--root-dir",
args.root_dir,
"--config",
args.config,
"--output",
"human",
"agent",
"bridge",
"--graph",
args.graph,
],
cwd=repo_root,
env=env,
stdout=out,
stderr=err,
)
try:
if args.assign_after_start:
wait_for_log(bridge_log, "listening graph changes", bridge)
assign_task(cli, repo_root, args.root_dir, args.config, args.graph)
start_events = [event for event in read_codex_events(codex_log) if event.get("event") == "start"]
resume_events = wait_for_codex_event(codex_log, "resume", bridge, bridge_log, bridge_err)
assert len(start_events) == 1, start_events
prompt = resume_events[0]["prompt"]
assert TASK_TITLE in prompt, prompt
assert "Graph: " + args.graph in prompt, prompt
assert "Block UUID:" in prompt, prompt
assert "Request kind: task" in prompt, prompt
print("agent bridge dispatched task to master " + resume_events[0]["session"])
finally:
if bridge.poll() is None:
bridge.terminate()
try:
bridge.wait(timeout=5)
except subprocess.TimeoutExpired:
bridge.kill()
bridge.wait(timeout=5)
if __name__ == "__main__":
main()
+181
View File
@@ -0,0 +1,181 @@
#!/usr/bin/env python3
"""Compare normalized query payloads between two cli graph contexts."""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
from pathlib import Path
from typing import Any, Dict
IGNORED_KEYS = {
"db/id",
"db/created-at",
"db/updated-at",
"block/uuid",
"block/updated-at",
"block/created-at",
}
def fail(message: str, **context: object) -> None:
payload = {"status": "error", "message": message}
if context:
payload["context"] = context
print(json.dumps(payload), file=sys.stderr)
raise SystemExit(1)
def normalize(value: Any) -> Any:
if isinstance(value, dict):
normalized = {}
for key in sorted(value.keys(), key=str):
key_str = str(key)
if key_str in IGNORED_KEYS:
continue
normalized[key_str] = normalize(value[key])
return normalized
if isinstance(value, list):
normalized_list = [normalize(item) for item in value]
try:
return sorted(normalized_list, key=lambda item: json.dumps(item, sort_keys=True))
except TypeError:
return normalized_list
return value
def run_query(cli_path: Path, config_path: Path, root_dir: Path, graph: str, query: str) -> Dict[str, Any]:
command = [
"node",
str(cli_path),
"--root-dir",
str(root_dir),
"--config",
str(config_path),
"--output",
"json",
"query",
"--graph",
graph,
"--query",
query,
]
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
fail(
"query command failed",
command=command,
exit=result.returncode,
stdout=result.stdout,
stderr=result.stderr,
)
try:
payload = json.loads(result.stdout)
except json.JSONDecodeError as error:
fail(
"query command did not return valid JSON",
command=command,
stdout=result.stdout,
stderr=result.stderr,
detail=str(error),
)
if payload.get("status") != "ok":
fail("query command returned non-ok status", command=command, payload=payload)
data = payload.get("data") or {}
return {
"payload": payload,
"result": data.get("result"),
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Compare normalized query payloads between two cli contexts")
parser.add_argument("--cli", required=True, help="Path to static/logseq-cli.js")
parser.add_argument("--graph", required=True)
parser.add_argument("--query", required=True, action="append")
parser.add_argument("--config-a", required=True)
parser.add_argument("--root-dir-a", required=True)
parser.add_argument("--config-b", required=True)
parser.add_argument("--root-dir-b", required=True)
parser.add_argument("--require-result", action="store_true")
return parser.parse_args()
def main() -> None:
args = parse_args()
cli_path = Path(args.cli).expanduser().resolve()
if not cli_path.exists():
fail("cli entry file does not exist", cli=str(cli_path))
queries = args.query
left_config = Path(args.config_a).expanduser().resolve()
left_root_dir = Path(args.root_dir_a).expanduser().resolve()
right_config = Path(args.config_b).expanduser().resolve()
right_root_dir = Path(args.root_dir_b).expanduser().resolve()
normalized_results = {}
for query in queries:
left = run_query(
cli_path,
left_config,
left_root_dir,
args.graph,
query,
)
right = run_query(
cli_path,
right_config,
right_root_dir,
args.graph,
query,
)
left_result = left["result"]
right_result = right["result"]
if args.require_result and (left_result is None or right_result is None):
fail(
"query result is empty",
query=query,
left_result=left_result,
right_result=right_result,
)
left_normalized = normalize(left_result)
right_normalized = normalize(right_result)
if left_normalized != right_normalized:
fail(
"normalized query results differ",
query=query,
left_result=left_normalized,
right_result=right_normalized,
left_payload=left["payload"],
right_payload=right["payload"],
)
normalized_results[query] = left_normalized
payload_key = "result" if len(normalized_results) == 1 else "results"
payload_value = next(iter(normalized_results.values())) if len(normalized_results) == 1 else normalized_results
print(
json.dumps(
{
"status": "ok",
payload_key: payload_value,
}
)
)
if __name__ == "__main__":
main()
+297
View File
@@ -0,0 +1,297 @@
#!/usr/bin/env python3
"""Manage local db-sync server process for cli-e2e sync suite."""
from __future__ import annotations
import argparse
import base64
import ctypes
import json
import os
import signal
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
from typing import Any, Dict, Optional
DEFAULT_COGNITO_ISSUER = "https://cognito-idp.us-east-2.amazonaws.com/us-east-2_kAqZcxIeM"
DEFAULT_COGNITO_CLIENT_ID = "1qi1uijg8b6ra70nejvbptis0q"
def fail(message: str, **context: object) -> None:
payload = {"status": "error", "message": message}
if context:
payload["context"] = context
print(json.dumps(payload), file=sys.stderr)
raise SystemExit(1)
def load_pid(pid_file: Path) -> Optional[int]:
if not pid_file.exists():
return None
raw = pid_file.read_text(encoding="utf-8").strip()
if not raw:
return None
try:
return int(raw)
except ValueError:
return None
def process_running(pid: int) -> bool:
if pid <= 0:
return False
if os.name == "nt":
kernel32 = ctypes.windll.kernel32
access = 0x00100000 | 0x1000 # SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION
handle = kernel32.OpenProcess(access, False, pid)
if handle:
kernel32.CloseHandle(handle)
return True
return ctypes.get_last_error() == 5
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
else:
return True
def terminate_process(pid: int, force: bool) -> bool:
if pid <= 0:
return True
if os.name == "nt":
cmd = ["taskkill", "/PID", str(pid), "/T"]
if force:
cmd.append("/F")
result = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
return result.returncode == 0 or not process_running(pid)
try:
os.kill(pid, signal.SIGKILL if force else signal.SIGTERM)
except ProcessLookupError:
return True
except PermissionError:
return False
return True
def parse_json_file(path: Path) -> Dict[str, Any]:
if not path.exists():
fail("sync auth file is missing", auth_path=str(path), hint="Run `logseq login` first.")
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as error:
fail("sync auth file is invalid JSON", auth_path=str(path), detail=str(error))
if not isinstance(payload, dict):
fail("sync auth file must be a JSON object", auth_path=str(path))
return payload
def decode_jwt_claims(token: str) -> Optional[Dict[str, Any]]:
if not isinstance(token, str):
return None
parts = token.split(".")
if len(parts) != 3:
return None
payload = parts[1]
padded = payload + "=" * ((4 - (len(payload) % 4)) % 4)
try:
decoded = base64.urlsafe_b64decode(padded.encode("utf-8")).decode("utf-8")
claims = json.loads(decoded)
except (ValueError, UnicodeDecodeError, json.JSONDecodeError):
return None
return claims if isinstance(claims, dict) else None
def auth_cognito_from_auth_file(auth_path: Path) -> Dict[str, str]:
payload = parse_json_file(auth_path)
token = payload.get("id-token") or payload.get("access-token")
claims = decode_jwt_claims(token) if isinstance(token, str) else None
issuer = claims.get("iss") if isinstance(claims, dict) else None
client_id = None
if isinstance(claims, dict):
client_id = claims.get("aud") or claims.get("client_id")
return {
"issuer": issuer if isinstance(issuer, str) and issuer else "",
"client_id": client_id if isinstance(client_id, str) and client_id else "",
}
def wait_health(base_url: str, timeout_s: float, interval_s: float) -> bool:
deadline = time.time() + timeout_s
url = base_url.rstrip("/") + "/health"
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
while time.time() < deadline:
try:
with opener.open(url, timeout=2) as response:
if response.status == 200:
return True
except (urllib.error.URLError, TimeoutError, socket.timeout):
pass
time.sleep(interval_s)
return False
def add_node_path(env: Dict[str, str], path: Path) -> None:
existing = env.get("NODE_PATH")
next_path = str(path)
env["NODE_PATH"] = next_path if not existing else next_path + os.pathsep + existing
def start_server(args: argparse.Namespace) -> None:
repo_root = Path(args.repo_root).expanduser().resolve()
entry = repo_root / "deps" / "db-sync" / "worker" / "dist" / "node-adapter.js"
if not entry.exists():
fail("db-sync node adapter build artifact is missing", entry=str(entry), hint="Run: yarn --cwd deps/db-sync build:node-adapter")
pid_file = Path(args.pid_file).expanduser().resolve()
log_file = Path(args.log_file).expanduser().resolve()
data_dir = Path(args.data_dir).expanduser().resolve()
pid_file.parent.mkdir(parents=True, exist_ok=True)
log_file.parent.mkdir(parents=True, exist_ok=True)
data_dir.mkdir(parents=True, exist_ok=True)
existing_pid = load_pid(pid_file)
if existing_pid and process_running(existing_pid):
fail("db-sync server already running", pid=existing_pid, pid_file=str(pid_file))
auth_path = Path(args.auth_path).expanduser().resolve() if args.auth_path else None
auth_derived = auth_cognito_from_auth_file(auth_path) if auth_path else {"issuer": "", "client_id": ""}
issuer = args.cognito_issuer or auth_derived.get("issuer") or DEFAULT_COGNITO_ISSUER
client_id = args.cognito_client_id or auth_derived.get("client_id") or DEFAULT_COGNITO_CLIENT_ID
jwks_url = args.cognito_jwks_url or f"{issuer}/.well-known/jwks.json"
env = os.environ.copy()
add_node_path(env, repo_root / "deps" / "db-sync" / "node_modules")
env.update(
{
"DB_SYNC_PORT": str(args.port),
"DB_SYNC_DATA_DIR": str(data_dir),
"COGNITO_ISSUER": issuer,
"COGNITO_CLIENT_ID": client_id,
"COGNITO_JWKS_URL": jwks_url,
# CLI e2e sync suite should remain runnable without outbound internet.
"DB_SYNC_ALLOW_UNVERIFIED_JWT_CLAIMS": "true",
}
)
with log_file.open("a", encoding="utf-8") as stream:
stream.write(f"\n=== cli-e2e db-sync start {time.strftime('%Y-%m-%d %H:%M:%S')} ===\n")
stream.flush()
process = subprocess.Popen(
["node", str(entry)],
stdout=stream,
stderr=stream,
cwd=str(repo_root),
env=env,
start_new_session=True,
)
base_url = f"http://{args.host}:{args.port}"
if not wait_health(base_url, args.startup_timeout_s, args.poll_interval_s):
terminate_process(process.pid, force=False)
fail(
"db-sync server failed health check before timeout",
base_url=base_url,
pid=process.pid,
log_file=str(log_file),
)
pid_file.write_text(f"{process.pid}\n", encoding="utf-8")
print(
json.dumps(
{
"status": "ok",
"pid": process.pid,
"pid_file": str(pid_file),
"log_file": str(log_file),
"base_url": base_url,
"data_dir": str(data_dir),
"cognito_issuer": issuer,
"cognito_client_id": client_id,
"auth_path": str(auth_path) if auth_path else None,
}
)
)
def stop_server(args: argparse.Namespace) -> None:
pid_file = Path(args.pid_file).expanduser().resolve()
pid = load_pid(pid_file)
if pid is None:
print(json.dumps({"status": "ok", "stopped": False, "reason": "pid-file-missing-or-empty", "pid_file": str(pid_file)}))
return
if not process_running(pid):
try:
pid_file.unlink(missing_ok=True)
except OSError:
pass
print(json.dumps({"status": "ok", "stopped": False, "reason": "process-not-running", "pid": pid, "pid_file": str(pid_file)}))
return
if not terminate_process(pid, force=False):
fail("db-sync server stop failed", pid=pid, signal="SIGTERM", pid_file=str(pid_file))
deadline = time.time() + args.shutdown_timeout_s
while time.time() < deadline:
if not process_running(pid):
pid_file.unlink(missing_ok=True)
print(json.dumps({"status": "ok", "stopped": True, "signal": "SIGTERM", "pid": pid, "pid_file": str(pid_file)}))
return
time.sleep(args.poll_interval_s)
if not terminate_process(pid, force=True):
fail("db-sync server force stop failed", pid=pid, signal="SIGKILL", pid_file=str(pid_file))
pid_file.unlink(missing_ok=True)
print(json.dumps({"status": "ok", "stopped": True, "signal": "SIGKILL", "pid": pid, "pid_file": str(pid_file)}))
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Manage db-sync local server for cli-e2e sync tests")
subparsers = parser.add_subparsers(dest="command", required=True)
start = subparsers.add_parser("start", help="Start server and wait for /health")
start.add_argument("--repo-root", required=True)
start.add_argument("--pid-file", required=True)
start.add_argument("--log-file", required=True)
start.add_argument("--data-dir", required=True)
start.add_argument("--host", default="127.0.0.1")
start.add_argument("--port", type=int, default=8080)
start.add_argument("--startup-timeout-s", type=float, default=25.0)
start.add_argument("--poll-interval-s", type=float, default=0.5)
start.add_argument("--auth-path", default="~/logseq/auth.json")
start.add_argument("--cognito-issuer")
start.add_argument("--cognito-client-id")
start.add_argument("--cognito-jwks-url")
stop = subparsers.add_parser("stop", help="Stop server if running")
stop.add_argument("--pid-file", required=True)
stop.add_argument("--shutdown-timeout-s", type=float, default=10.0)
stop.add_argument("--poll-interval-s", type=float, default=0.25)
return parser
def main() -> None:
args = build_parser().parse_args()
if args.command == "start":
start_server(args)
elif args.command == "stop":
stop_server(args)
else:
fail("unknown command", command=args.command)
if __name__ == "__main__":
main()
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Prepare per-case CLI config for sync e2e tests."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
DEFAULT_OAUTH_TOKEN_ENDPOINT = "https://logseq-prod.auth.us-east-1.amazoncognito.com/oauth2/token"
def fail(message: str, **context: object) -> None:
payload = {"status": "error", "message": message}
if context:
payload["context"] = context
print(json.dumps(payload), file=sys.stderr)
raise SystemExit(1)
def read_auth(auth_path: Path) -> dict:
if not auth_path.exists():
fail("sync auth file is missing", auth_path=str(auth_path), hint="Run `logseq login` first.")
try:
payload = json.loads(auth_path.read_text(encoding="utf-8"))
except json.JSONDecodeError as error:
fail("sync auth file is invalid JSON", auth_path=str(auth_path), detail=str(error))
has_token = any(payload.get(key) for key in ("refresh-token", "id-token", "access-token"))
if not has_token:
fail(
"sync auth file does not contain usable tokens",
auth_path=str(auth_path),
required_any_of=["refresh-token", "id-token", "access-token"],
)
return payload
def write_config(output_path: Path, http_base: str, ws_url: str, oauth_token_endpoint: str) -> None:
output_path.parent.mkdir(parents=True, exist_ok=True)
payload = "\n".join(
[
"{",
" :output-format :json",
f' :http-base "{http_base}"',
f' :ws-url "{ws_url}"',
f' :oauth-token-endpoint "{oauth_token_endpoint}"',
"}",
"",
]
)
output_path.write_text(payload, encoding="utf-8")
def main() -> None:
parser = argparse.ArgumentParser(description="Prepare cli.edn for sync e2e")
parser.add_argument("--output", required=True)
parser.add_argument("--auth-path", default="~/logseq/auth.json")
parser.add_argument("--http-base", required=True)
parser.add_argument("--ws-url", required=True)
parser.add_argument("--oauth-token-endpoint", default=DEFAULT_OAUTH_TOKEN_ENDPOINT)
args = parser.parse_args()
auth_path = Path(args.auth_path).expanduser().resolve()
_auth = read_auth(auth_path)
output_path = Path(args.output).expanduser().resolve()
write_config(output_path, args.http_base, args.ws_url, args.oauth_token_endpoint)
print(
json.dumps(
{
"status": "ok",
"auth_path": str(auth_path),
"config_path": str(output_path),
"http_base": args.http_base,
"ws_url": args.ws_url,
"oauth_token_endpoint": args.oauth_token_endpoint,
}
)
)
if __name__ == "__main__":
main()
@@ -0,0 +1,480 @@
#!/usr/bin/env python3
"""Run randomized bidirectional block operations on two synced graph peers."""
from __future__ import annotations
import argparse
import json
import random
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List
class CliCommandError(RuntimeError):
"""Raised when a CLI command does not complete successfully."""
def __init__(self, message: str, *, context: Dict[str, Any]) -> None:
super().__init__(message)
self.context = context
@dataclass(frozen=True)
class ClientContext:
name: str
config: Path
root_dir: Path
def fail(message: str, **context: object) -> None:
payload = {"status": "error", "message": message}
if context:
payload["context"] = context
print(json.dumps(payload), file=sys.stderr)
raise SystemExit(1)
def run_cli_json(
*,
cli_path: Path,
graph: str,
client: ClientContext,
args: List[str],
) -> Dict[str, Any]:
command = [
"node",
str(cli_path),
"--root-dir",
str(client.root_dir),
"--config",
str(client.config),
"--output",
"json",
*args,
"--graph",
graph,
]
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
raise CliCommandError(
"cli command exited with non-zero status",
context={
"client": client.name,
"command": command,
"exit": result.returncode,
"stdout": result.stdout,
"stderr": result.stderr,
},
)
try:
payload = json.loads(result.stdout)
except json.JSONDecodeError as error:
raise CliCommandError(
"cli command did not return valid json",
context={
"client": client.name,
"command": command,
"stdout": result.stdout,
"stderr": result.stderr,
"detail": str(error),
},
) from error
if payload.get("status") != "ok":
raise CliCommandError(
"cli command returned non-ok status",
context={
"client": client.name,
"command": command,
"payload": payload,
},
)
return payload
def page_block_ids(
*,
cli_path: Path,
graph: str,
client: ClientContext,
page_title: str,
) -> List[int]:
query = (
"[:find [?e ...] "
":where "
f"[?p :block/title {json.dumps(page_title)}] "
"[?e :block/page ?p] "
"[?e :block/uuid]]"
)
payload = run_cli_json(
cli_path=cli_path,
graph=graph,
client=client,
args=["query", "--query", query],
)
result = (payload.get("data") or {}).get("result")
if not isinstance(result, list):
return []
output: List[int] = []
for item in result:
try:
output.append(int(item))
except (TypeError, ValueError):
continue
return output
def upsert_page(
*,
cli_path: Path,
graph: str,
client: ClientContext,
page_title: str,
) -> None:
run_cli_json(
cli_path=cli_path,
graph=graph,
client=client,
args=["upsert", "page", "--page", page_title],
)
def create_block(
*,
cli_path: Path,
graph: str,
client: ClientContext,
page_title: str,
content: str,
ids: List[int],
rng: random.Random,
) -> None:
if ids and rng.random() < 0.6:
target_id = str(rng.choice(ids))
run_cli_json(
cli_path=cli_path,
graph=graph,
client=client,
args=[
"upsert",
"block",
"--target-id",
target_id,
"--pos",
"first-child",
"--content",
content,
],
)
return
run_cli_json(
cli_path=cli_path,
graph=graph,
client=client,
args=[
"upsert",
"block",
"--target-page",
page_title,
"--content",
content,
],
)
def move_block(
*,
cli_path: Path,
graph: str,
client: ClientContext,
page_title: str,
ids: List[int],
rng: random.Random,
) -> bool:
if not ids:
return False
source_id = str(rng.choice(ids))
run_cli_json(
cli_path=cli_path,
graph=graph,
client=client,
args=[
"upsert",
"block",
"--id",
source_id,
"--target-page",
page_title,
"--pos",
"last-child",
],
)
return True
def delete_block(
*,
cli_path: Path,
graph: str,
client: ClientContext,
ids: List[int],
rng: random.Random,
) -> bool:
if len(ids) <= 2:
return False
source_id = str(rng.choice(ids))
run_cli_json(
cli_path=cli_path,
graph=graph,
client=client,
args=["remove", "block", "--id", source_id],
)
return True
def feasible(operation: str, ids: List[int]) -> bool:
if operation == "create":
return True
if operation == "move":
return len(ids) >= 1
if operation == "delete":
return len(ids) > 2
return False
def choose_operation(op_counts: Dict[str, int], ids: List[int], rng: random.Random) -> str:
for required in ("create", "move", "delete"):
if op_counts.get(required, 0) == 0 and feasible(required, ids):
return required
candidates = ["create", "create", "move"]
if feasible("delete", ids):
candidates.append("delete")
if feasible("move", ids):
candidates.append("move")
return rng.choice(candidates)
def apply_operation(
*,
cli_path: Path,
graph: str,
client: ClientContext,
page_title: str,
op_counts: Dict[str, int],
round_index: int,
rng: random.Random,
) -> None:
last_error: Dict[str, Any] | None = None
for attempt in range(1, 7):
ids = page_block_ids(
cli_path=cli_path,
graph=graph,
client=client,
page_title=page_title,
)
operation = choose_operation(op_counts, ids, rng)
content = f"{client.name}-rnd-{round_index:03d}-{rng.randint(100000, 999999)}"
try:
if operation == "create":
create_block(
cli_path=cli_path,
graph=graph,
client=client,
page_title=page_title,
content=content,
ids=ids,
rng=rng,
)
op_counts["create"] = op_counts.get("create", 0) + 1
return
if operation == "move":
moved = move_block(
cli_path=cli_path,
graph=graph,
client=client,
page_title=page_title,
ids=ids,
rng=rng,
)
if moved:
op_counts["move"] = op_counts.get("move", 0) + 1
return
continue
if operation == "delete":
deleted = delete_block(
cli_path=cli_path,
graph=graph,
client=client,
ids=ids,
rng=rng,
)
if deleted:
op_counts["delete"] = op_counts.get("delete", 0) + 1
return
continue
except CliCommandError as error:
last_error = {
"attempt": attempt,
"operation": operation,
"context": error.context,
}
continue
fail(
"failed to apply random operation after retries",
client=client.name,
round_index=round_index,
last_error=last_error,
)
def ensure_non_empty_page(
*,
cli_path: Path,
graph: str,
client: ClientContext,
page_title: str,
rng: random.Random,
) -> None:
ids = page_block_ids(
cli_path=cli_path,
graph=graph,
client=client,
page_title=page_title,
)
if ids:
return
content = f"{client.name}-reseed-{rng.randint(100000, 999999)}"
create_block(
cli_path=cli_path,
graph=graph,
client=client,
page_title=page_title,
content=content,
ids=[],
rng=rng,
)
PROFILE_DEFAULT_ROUNDS = {
"default": 40,
"high-stress": 100,
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Run randomized bidirectional block operations on two synced graph clients"
)
parser.add_argument("--cli", required=True, help="Path to static/logseq-cli.js")
parser.add_argument("--graph", required=True)
parser.add_argument("--config-a", required=True)
parser.add_argument("--root-dir-a", required=True)
parser.add_argument("--config-b", required=True)
parser.add_argument("--root-dir-b", required=True)
parser.add_argument("--page", required=True)
parser.add_argument(
"--profile",
choices=sorted(PROFILE_DEFAULT_ROUNDS.keys()),
default="default",
help="Execution profile controlling default stress level",
)
parser.add_argument("--rounds-per-client", type=int, default=None)
parser.add_argument("--seed", type=int, default=424242)
args = parser.parse_args()
if args.rounds_per_client is None:
args.rounds_per_client = PROFILE_DEFAULT_ROUNDS[args.profile]
return args
def main() -> None:
args = parse_args()
cli_path = Path(args.cli).expanduser().resolve()
if not cli_path.exists():
fail("cli path does not exist", cli=str(cli_path))
rng = random.Random(args.seed)
client_a = ClientContext(
name="a",
config=Path(args.config_a).expanduser().resolve(),
root_dir=Path(args.root_dir_a).expanduser().resolve(),
)
client_b = ClientContext(
name="b",
config=Path(args.config_b).expanduser().resolve(),
root_dir=Path(args.root_dir_b).expanduser().resolve(),
)
clients = [client_a, client_b]
for client in clients:
upsert_page(
cli_path=cli_path,
graph=args.graph,
client=client,
page_title=args.page,
)
# Seed both peers so move/delete have available targets from the beginning.
for seed_round in range(3):
for client in clients:
create_block(
cli_path=cli_path,
graph=args.graph,
client=client,
page_title=args.page,
content=f"{client.name}-seed-{seed_round}-{rng.randint(100000, 999999)}",
ids=[],
rng=rng,
)
op_stats: Dict[str, Dict[str, int]] = {
client.name: {"create": 0, "move": 0, "delete": 0} for client in clients
}
for round_index in range(args.rounds_per_client):
for client in clients:
apply_operation(
cli_path=cli_path,
graph=args.graph,
client=client,
page_title=args.page,
op_counts=op_stats[client.name],
round_index=round_index,
rng=rng,
)
for client in clients:
ensure_non_empty_page(
cli_path=cli_path,
graph=args.graph,
client=client,
page_title=args.page,
rng=rng,
)
print(
json.dumps(
{
"status": "ok",
"graph": args.graph,
"page": args.page,
"rounds_per_client": args.rounds_per_client,
"seed": args.seed,
"stats": op_stats,
"total_operations": args.rounds_per_client * len(clients),
}
)
)
if __name__ == "__main__":
main()
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env python3
"""Exercise `logseq sync asset download` in an isolated sync e2e graph."""
from __future__ import annotations
import argparse
import hashlib
import json
import subprocess
import sys
import time
from pathlib import Path
from typing import Any, Dict, Iterable, List
def fail(message: str, **context: object) -> None:
payload = {"status": "error", "message": message}
if context:
payload["context"] = context
print(json.dumps(payload), file=sys.stderr)
raise SystemExit(1)
def cli_base(cli: Path, root_dir: Path, config: Path) -> List[str]:
return [
"node",
str(cli),
"--root-dir",
str(root_dir),
"--config",
str(config),
"--output",
"json",
]
def run_cli_json(command: List[str], *, allow_error: bool = False) -> Dict[str, Any]:
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0 and not allow_error:
fail(
"cli command failed",
command=command,
exit=result.returncode,
stdout=result.stdout,
stderr=result.stderr,
)
try:
payload = json.loads(result.stdout)
except json.JSONDecodeError as error:
fail(
"cli command did not return valid JSON",
command=command,
exit=result.returncode,
stdout=result.stdout,
stderr=result.stderr,
detail=str(error),
)
if payload.get("status") != "ok" and not allow_error:
fail("cli command returned non-ok status", command=command, payload=payload)
return payload
def contains_key(value: Any, key: str) -> bool:
if isinstance(value, dict):
return key in value or any(contains_key(child, key) for child in value.values())
if isinstance(value, list):
return any(contains_key(child, key) for child in value)
return False
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(8192), b""):
digest.update(chunk)
return digest.hexdigest()
def wait_for_checksum(path: Path, checksum: str, timeout_s: float = 60.0) -> None:
deadline = time.time() + timeout_s
last_state = "missing"
while time.time() < deadline:
if path.exists():
current = sha256_file(path)
if current == checksum:
return
last_state = f"checksum:{current}"
time.sleep(1.0)
fail("asset file did not reach expected checksum", path=str(path), expected=checksum, last_state=last_state)
def get_asset(cli: Path, root_dir: Path, config: Path, graph: str, title: str) -> Dict[str, Any]:
query = (
'[:find (pull ?e [:db/id :block/uuid '
':logseq.property.asset/type :logseq.property.asset/checksum '
':logseq.property.asset/remote-metadata]) . '
f':where [?e :block/title "{title}"]]'
)
payload = run_cli_json(
cli_base(cli, root_dir, config)
+ ["query", "--graph", graph, "--query", query]
)
asset = (payload.get("data") or {}).get("result")
if not isinstance(asset, dict):
fail("asset query did not return an entity", payload=payload)
required = [
"db/id",
"block/uuid",
"logseq.property.asset/type",
"logseq.property.asset/checksum",
"logseq.property.asset/remote-metadata",
]
missing = [key for key in required if not asset.get(key)]
if missing:
fail("asset entity is missing required fields", asset=asset, missing=missing)
return asset
def sync_asset_download_by_id(cli: Path, root_dir: Path, config: Path, graph: str, asset_id: Any) -> Dict[str, Any]:
return run_cli_json(
cli_base(cli, root_dir, config)
+ ["sync", "asset", "download", "--graph", graph, "--id", str(asset_id)]
)
def sync_asset_download_by_uuid(cli: Path, root_dir: Path, config: Path, graph: str, asset_uuid: str) -> Dict[str, Any]:
return run_cli_json(
cli_base(cli, root_dir, config)
+ ["sync", "asset", "download", "--graph", graph, "--uuid", asset_uuid]
)
def assert_data(payload: Dict[str, Any], expected: Dict[str, Any]) -> None:
data = payload.get("data") or {}
for key, value in expected.items():
if data.get(key) != value:
fail("unexpected sync asset download data", expected=expected, actual=data, payload=payload)
if contains_key(payload, "local-path"):
fail("sync asset download output leaked local-path", payload=payload)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Run sync asset download e2e assertions")
parser.add_argument("--cli", required=True)
parser.add_argument("--graph", required=True)
parser.add_argument("--asset-title", required=True)
parser.add_argument("--config-b", required=True)
parser.add_argument("--root-dir-b", required=True)
return parser.parse_args()
def main() -> None:
args = parse_args()
cli = Path(args.cli).expanduser().resolve()
root_b = Path(args.root_dir_b).expanduser().resolve()
config_b = Path(args.config_b).expanduser().resolve()
asset = get_asset(cli, root_b, config_b, args.graph, args.asset_title)
asset_id = asset["db/id"]
asset_uuid = asset["block/uuid"]
asset_type = asset["logseq.property.asset/type"]
checksum = asset["logseq.property.asset/checksum"]
asset_path = root_b / "graphs" / args.graph / "assets" / f"{asset_uuid}.{asset_type}"
if asset_path.exists():
asset_path.unlink()
requested = sync_asset_download_by_uuid(cli, root_b, config_b, args.graph, asset_uuid)
assert_data(
requested,
{
"asset-id": asset_id,
"asset-uuid": asset_uuid,
"asset-type": asset_type,
"download-requested?": True,
"checksum-status": "missing",
},
)
wait_for_checksum(asset_path, checksum)
skipped = sync_asset_download_by_id(cli, root_b, config_b, args.graph, asset_id)
assert_data(
skipped,
{
"asset-id": asset_id,
"asset-uuid": asset_uuid,
"asset-type": asset_type,
"download-requested?": False,
"checksum-status": "match",
"skipped-reason": "already-downloaded",
},
)
asset_path.write_text("corrupted local asset", encoding="utf-8")
mismatched = sync_asset_download_by_id(cli, root_b, config_b, args.graph, asset_id)
assert_data(
mismatched,
{
"asset-id": asset_id,
"asset-uuid": asset_uuid,
"asset-type": asset_type,
"download-requested?": True,
"checksum-status": "mismatch",
},
)
hint = (mismatched.get("data") or {}).get("hint") or ""
if "checksum" not in hint:
fail("checksum mismatch hint is missing", payload=mismatched)
wait_for_checksum(asset_path, checksum)
run_cli_json(cli_base(cli, root_b, config_b) + ["sync", "stop", "--graph", args.graph])
inactive = run_cli_json(
cli_base(cli, root_b, config_b)
+ ["sync", "asset", "download", "--graph", args.graph, "--id", str(asset_id)],
allow_error=True,
)
if inactive.get("status") != "error":
fail("inactive sync command unexpectedly succeeded", payload=inactive)
error = inactive.get("error") or {}
if error.get("code") != "sync-not-started":
fail("inactive sync command returned wrong error", payload=inactive)
if "sync start" not in (error.get("hint") or ""):
fail("inactive sync command did not include start hint", payload=inactive)
print(
json.dumps(
{
"status": "ok",
"data": {
"asset-id": asset_id,
"asset-uuid": asset_uuid,
"asset-type": asset_type,
"download-requested?": True,
"checksum-status": "mismatch",
"pending-local": 0,
"pending-asset": 0,
"pending-server": 0,
"last-error": None,
},
}
)
)
if __name__ == "__main__":
main()
+302
View File
@@ -0,0 +1,302 @@
#!/usr/bin/env python3
"""Poll `logseq sync status` until queues settle and tx converges."""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import time
from pathlib import Path
from typing import Any, Dict
def fail(message: str, **context: object) -> None:
payload = {"status": "error", "message": message}
if context:
payload["context"] = context
print(json.dumps(payload), file=sys.stderr)
raise SystemExit(1)
def parse_int(value: Any) -> int:
if value is None:
return 0
if isinstance(value, bool):
return int(value)
if isinstance(value, (int, float)):
return int(value)
try:
return int(str(value))
except (TypeError, ValueError):
return 0
def status_command(args: argparse.Namespace) -> list[str]:
existing = getattr(args, "status_command", None)
if existing is not None:
return existing
command = [
"node",
str(Path(args.cli).expanduser().resolve()),
"--root-dir",
str(Path(args.root_dir).expanduser().resolve()),
"--config",
str(Path(args.config).expanduser().resolve()),
"--output",
"json",
"sync",
"status",
"--graph",
args.graph,
]
args.status_command = command
return command
def run_status(args: argparse.Namespace) -> Dict[str, Any]:
command = status_command(args)
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
fail(
"sync status command failed",
command=command,
exit=result.returncode,
stdout=result.stdout,
stderr=result.stderr,
)
try:
payload = json.loads(result.stdout)
except json.JSONDecodeError as error:
fail(
"sync status command did not return valid JSON",
command=command,
stdout=result.stdout,
stderr=result.stderr,
detail=str(error),
)
if payload.get("status") != "ok":
fail("sync status returned non-ok status", payload=payload)
return payload
def pending_counts(status_payload: Dict[str, Any]) -> Dict[str, int]:
data = status_payload.get("data") or {}
return {
"pending-local": parse_int(data.get("pending-local")),
"pending-asset": parse_int(data.get("pending-asset")),
"pending-server": parse_int(data.get("pending-server")),
}
def all_settled(counts: Dict[str, int]) -> bool:
required_keys = ("pending-local", "pending-asset", "pending-server")
return all(counts.get(key, 0) == 0 for key in required_keys)
def parse_required_int(value: Any) -> int | None:
if value is None:
return None
if isinstance(value, str) and value.strip() == "":
return None
if isinstance(value, bool):
return int(value)
if isinstance(value, (int, float)):
return int(value)
try:
return int(str(value))
except (TypeError, ValueError):
return None
def tx_sync_status(status_payload: Dict[str, Any]) -> Dict[str, Any]:
data = status_payload.get("data") or {}
local_tx = parse_required_int(data.get("local-tx"))
remote_tx = parse_required_int(data.get("remote-tx"))
synced = (
local_tx is not None
and remote_tx is not None
and local_tx == remote_tx
)
return {
"local-tx": local_tx,
"remote-tx": remote_tx,
"synced": synced,
}
def tx_deltas(
tx_status: Dict[str, Any],
baseline_tx: Dict[str, Any],
) -> Dict[str, int | None]:
local_tx = tx_status.get("local-tx")
remote_tx = tx_status.get("remote-tx")
baseline_local_tx = baseline_tx.get("local-tx")
baseline_remote_tx = baseline_tx.get("remote-tx")
local_tx_delta = (
None
if local_tx is None or baseline_local_tx is None
else local_tx - baseline_local_tx
)
remote_tx_delta = (
None
if remote_tx is None or baseline_remote_tx is None
else remote_tx - baseline_remote_tx
)
return {
"local-tx-delta": local_tx_delta,
"remote-tx-delta": remote_tx_delta,
}
def min_tx_delta_reached(
tx_status: Dict[str, Any],
baseline_tx: Dict[str, Any],
min_tx_delta: int,
) -> bool:
if min_tx_delta <= 0:
return True
deltas = tx_deltas(tx_status, baseline_tx)
local_tx_delta = deltas.get("local-tx-delta")
remote_tx_delta = deltas.get("remote-tx-delta")
if local_tx_delta is None or remote_tx_delta is None:
return False
return local_tx_delta >= min_tx_delta and remote_tx_delta >= min_tx_delta
def main() -> None:
parser = argparse.ArgumentParser(
description="Wait for sync status to settle"
)
parser.add_argument(
"--cli",
required=True,
help="Path to static/logseq-cli.js",
)
parser.add_argument("--root-dir", required=True)
parser.add_argument("--config", required=True)
parser.add_argument("--graph", required=True)
parser.add_argument("--timeout-s", type=float, default=120.0)
parser.add_argument("--interval-s", type=float, default=1.0)
parser.add_argument(
"--min-tx-delta",
type=int,
default=0,
help=(
"Require synced tx delta to be >= this value: "
"(new-tx - old-tx) >= min-tx-delta "
"(default: 0)"
),
)
parser.add_argument(
"--baseline-tx",
type=int,
default=None,
help=(
"Optional explicit baseline tx used as old-tx for both local "
"and remote; if omitted, first observed tx values "
"are used"
),
)
args = parser.parse_args()
if args.min_tx_delta < 0:
invalid_min_tx_delta = args.min_tx_delta
fail(
"min-tx-delta must be non-negative",
min_tx_delta=invalid_min_tx_delta,
)
started = time.time()
deadline = started + args.timeout_s
last_payload: Dict[str, Any] | None = None
baseline_tx: Dict[str, Any] | None = (
{
"local-tx": args.baseline_tx,
"remote-tx": args.baseline_tx,
}
if args.baseline_tx is not None
else None
)
while time.time() < deadline:
payload = run_status(args)
last_payload = payload
data = payload.get("data") or {}
last_error = data.get("last-error")
if last_error is not None:
fail("sync status reports last-error", payload=payload)
counts = pending_counts(payload)
tx_status = tx_sync_status(payload)
if baseline_tx is None:
baseline_tx = {
"local-tx": tx_status.get("local-tx"),
"remote-tx": tx_status.get("remote-tx"),
}
deltas = tx_deltas(tx_status, baseline_tx)
if (
all_settled(counts)
and tx_status["synced"]
and min_tx_delta_reached(
tx_status,
baseline_tx,
args.min_tx_delta,
)
):
print(
json.dumps(
{
"status": "ok",
"elapsed_s": round(time.time() - started, 3),
"counts": counts,
"tx": {
"local-tx": tx_status["local-tx"],
"remote-tx": tx_status["remote-tx"],
},
"tx-delta": deltas,
"baseline-tx": baseline_tx,
"min_tx_delta": args.min_tx_delta,
"payload": payload,
}
)
)
return
time.sleep(max(args.interval_s, 0.0))
last_tx_status = tx_sync_status(last_payload or {})
last_baseline_tx = baseline_tx or {"local-tx": None, "remote-tx": None}
fail(
(
"sync status polling timed out before queues settled, tx synced, "
"and min tx delta reached"
),
timeout_s=args.timeout_s,
min_tx_delta=args.min_tx_delta,
baseline_tx=last_baseline_tx,
last_payload=last_payload,
last_counts=pending_counts(last_payload or {}),
last_tx=last_tx_status,
last_tx_delta=tx_deltas(
last_tx_status,
last_baseline_tx,
),
)
if __name__ == "__main__":
main()