refactor: convert Marqdo into the ecosystem integration repository
This commit is contained in:
1 parent
1c55baabd5
commit
4c5c102593
1880 files changed
+998
-308724
No files matched your search
@@ -1,83 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Wave B1 — offline constitution / OKF harness (no network required).
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
MQ="${MARQDO_BIN:-$ROOT/target/release/marqdo}"
|
||||
export MARQDO_EXT="${MARQDO_EXT:-$ROOT/ext}"
|
||||
export MARQDO_AGENT_PLUGIN="${MARQDO_AGENT_PLUGIN:-$ROOT/target/release/libagent.so}"
|
||||
# Offline golds that construct an llm handle need a dummy key (no network).
|
||||
export OPENAI_API_KEY="${OPENAI_API_KEY:-sk-test}"
|
||||
|
||||
if [[ ! -x "$MQ" ]]; then
|
||||
echo "missing $MQ — run: cargo build --release -p marqdo -p marqdo_plugin_agent" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
fail=0
|
||||
run() {
|
||||
local f="$1"
|
||||
echo "==> $f"
|
||||
if ! "$MQ" run "$f"; then
|
||||
echo "FAIL $f" >&2
|
||||
fail=1
|
||||
fi
|
||||
}
|
||||
|
||||
run tests/ext/agent-constitution-b0.mq.md
|
||||
run tests/ext/agent-dump-context.mq.md
|
||||
run tests/ext/agent-writeback-shadow.mq.md
|
||||
run tests/ext/agent-kb-plan-hit.mq.md
|
||||
run tests/ext/agent-context-budget-a3.mq.md
|
||||
run tests/ext/agent-workbook-patch-a0.mq.md
|
||||
run tests/ext/agent-v2-learn.mq.md
|
||||
run tests/ext/agent-p4-route.mq.md
|
||||
run tests/ext/agent-small-llm-route.mq.md
|
||||
run tests/ext/agent-mcp-client.mq.md
|
||||
run tests/ext/agent-resume.mq.md
|
||||
run tests/ext/agent-zero-llm.mq.md
|
||||
run tests/ext/agent-plan-preserve.mq.md
|
||||
run examples/agent-okf-flywheel/index.mq.md
|
||||
run examples/agent-pong/index.mq.md
|
||||
run examples/agent-sandbox-okf/index.mq.md
|
||||
run tests/ext/agent-sandbox-optin.mq.md
|
||||
run tests/ext/agent-sandbox-promote.mq.md
|
||||
|
||||
# Skill Lift subset (O2 B3/E1): with-skill vs without — constitution / writeback / call_site markers.
|
||||
skill_lift_pass=0
|
||||
skill_lift_fail=0
|
||||
assert_out_has() {
|
||||
local f="$1"
|
||||
local needle="$2"
|
||||
local label="$3"
|
||||
local out
|
||||
out="$("$MQ" run "$f" 2>/dev/null || true)"
|
||||
if printf '%s' "$out" | grep -q -- "$needle"; then
|
||||
echo "SkillLift OK $label ($needle)"
|
||||
skill_lift_pass=$((skill_lift_pass + 1))
|
||||
else
|
||||
echo "SkillLift MISS $label (need $needle)" >&2
|
||||
skill_lift_fail=$((skill_lift_fail + 1))
|
||||
fail=1
|
||||
fi
|
||||
}
|
||||
assert_out_has tests/ext/agent-constitution-b0.mq.md "constitution-ok" "constitution"
|
||||
assert_out_has tests/ext/agent-writeback-shadow.mq.md "writeback-shadow-ok" "writeback"
|
||||
assert_out_has tests/ext/agent-dump-context.mq.md "dump-context-ok" "call_site"
|
||||
echo "SkillLift summary: pass=$skill_lift_pass fail=$skill_lift_fail"
|
||||
|
||||
if [[ "${AGENT_HARNESS_LIVE:-}" == "1" ]]; then
|
||||
export AGENT_LIVE=1
|
||||
if [[ ! -f "$ROOT/.env" ]]; then
|
||||
echo "AGENT_HARNESS_LIVE=1 needs repo-root .env (see .env.example)" >&2
|
||||
exit 1
|
||||
fi
|
||||
run examples/agent-pong/index.mq.md
|
||||
run tests/ext/agent-run-live.mq.md
|
||||
fi
|
||||
|
||||
if [[ "$fail" -ne 0 ]]; then
|
||||
echo "agent harness: FAILED" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "agent harness: OK"
|
||||
@@ -1,6 +0,0 @@
|
||||
# Generate HTML next to public/*.mq.md via the Marqdo interpreter.
|
||||
$ErrorActionPreference = "Stop"
|
||||
Set-Location (Split-Path $PSScriptRoot -Parent)
|
||||
cargo build --release -q
|
||||
& .\target\release\marqdo.exe view output public -o public
|
||||
Write-Host "OK → public/index.html + public/pages/ (sources: public/**/*.mq.md)"
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Generate HTML next to public/*.mq.md via the Marqdo interpreter.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
cargo build --release -q
|
||||
./target/release/marqdo view output public -o public
|
||||
echo "OK → public/index.html + public/pages/ (sources: public/**/*.mq.md)"
|
||||
@@ -1,29 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build Marqdo web plugin (Go → C shared library).
|
||||
# Canonical output: plugins/web/build/libweb.so (Linux) / libweb.dylib / web.dll
|
||||
# Also copies into target/{debug,release}/ for ext CLI and release packaging.
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$ROOT/plugins/web"
|
||||
mkdir -p build
|
||||
export PATH="${HOME}/.local/go/bin:/usr/local/go/bin:${PATH}"
|
||||
if ! command -v go >/dev/null 2>&1; then
|
||||
echo "error: go not found (install Go 1.22+ or set PATH)" >&2
|
||||
exit 1
|
||||
fi
|
||||
OUT="build/libweb.so"
|
||||
case "$(uname -s)" in
|
||||
Darwin) OUT="build/libweb.dylib" ;;
|
||||
MINGW*|MSYS*|CYGWIN*|Windows_NT) OUT="build/web.dll" ;;
|
||||
esac
|
||||
echo "building $OUT (go $(go version | awk '{print $3}'))…"
|
||||
CGO_ENABLED=1 go build -buildmode=c-shared -o "$OUT" .
|
||||
ABS="$ROOT/plugins/web/$OUT"
|
||||
BASE="$(basename "$OUT")"
|
||||
for dir in "$ROOT/target/debug" "$ROOT/target/release"; do
|
||||
mkdir -p "$dir"
|
||||
cp -f "$ABS" "$dir/$BASE"
|
||||
done
|
||||
echo "ok: $ABS"
|
||||
echo "also: $ROOT/target/debug/$BASE $ROOT/target/release/$BASE"
|
||||
echo "hint: plugin.native_path name=web resolves these; override with MARQDO_WEB_PLUGIN=$ABS"
|
||||
@@ -1,163 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reproducible marketing captures from the actual Marqdo 2.7.1 Linux CLI.
|
||||
|
||||
All procurement outputs are simulation-only. The GIF is a curated display of
|
||||
the real function-call JSON responses, not a filmed human typing session.
|
||||
The screenshot is taken with a real headless browser from marqdo view output.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "assets" / "marketing"
|
||||
SRC = "examples/procurement/index.mq.md"
|
||||
|
||||
def invoke(cli, fn, args=(), effects=None):
|
||||
cmd = [str(cli), "call", SRC, fn, *args]
|
||||
if effects:
|
||||
cmd += ["--effects", effects]
|
||||
cmd.append("--json")
|
||||
p = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, timeout=45)
|
||||
if p.returncode != 0:
|
||||
raise RuntimeError("Command failed:\n" + " ".join(cmd) + "\n" + p.stdout + "\n" + p.stderr)
|
||||
try:
|
||||
result = json.loads(p.stdout)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise RuntimeError(f"Non-JSON CLI response {p.stdout!r}") from exc
|
||||
if not result.get("ok"):
|
||||
raise RuntimeError("Marqdo call rejected: " + p.stdout)
|
||||
print("VERIFIED", fn, json.dumps(result, ensure_ascii=False))
|
||||
return result["result"]
|
||||
|
||||
def font(size, bold=False):
|
||||
for name in (
|
||||
"/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc" if bold else "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
):
|
||||
try:
|
||||
return ImageFont.truetype(name, size)
|
||||
except OSError:
|
||||
continue
|
||||
return ImageFont.load_default()
|
||||
|
||||
def frame(index, headline, invocation, details, emphasis=None, danger=False):
|
||||
W, H = 1200, 660
|
||||
img = Image.new("RGB", (W,H), (14,22,37))
|
||||
d = ImageDraw.Draw(img)
|
||||
gold = (238,201,145); muted = (159,178,204)
|
||||
d.rounded_rectangle((24,22,1175,635), radius=25, fill=(22,32,51), outline=(59,77,101), width=2)
|
||||
d.text((53,49), "Marqdo", font=font(30,True), fill=gold)
|
||||
d.text((231,57), "EXECUTABLE SKILLS / PROCUREMENT",font=font(19),fill=muted)
|
||||
d.rounded_rectangle((976,44,1138,82), radius=16, fill=(39,54,75))
|
||||
d.text((1000,54),"v2.7.1",font=font(18),fill=(216,227,239))
|
||||
d.text((53,139),headline,font=font(32,True),fill=(245,244,239))
|
||||
d.text((54,188),"CALL",font=font(16,True),fill=gold)
|
||||
d.rounded_rectangle((49,208,1150,293),radius=11,fill=(12,19,33))
|
||||
for i,line in enumerate(invocation):
|
||||
d.text((66,223+i*34),line,font=font(19),fill=(194,221,240))
|
||||
d.text((54,336),"ACTUAL CLI RESULT / DOMAIN FIELDS",font=font(16,True),fill=gold)
|
||||
d.rounded_rectangle((49,352,1150,536),radius=11,fill=(16,26,43))
|
||||
for i,line in enumerate(details[:5]):
|
||||
d.text((69,371+i*33),line,font=font(20),fill=(219,233,241))
|
||||
if emphasis:
|
||||
accent=(245,153,159) if danger else (155,231,185)
|
||||
d.rounded_rectangle((52,554,1149,609),radius=10,fill=(68,38,48) if danger else (30,67,57))
|
||||
d.text((71,569),emphasis,font=font(22,True),fill=accent)
|
||||
for i in range(5):
|
||||
x=79+i*219
|
||||
d.rounded_rectangle((x,621,x+204,628),radius=3,fill=gold if i<=index else (69,81,99))
|
||||
d.text((855,641),f"FRAME {index+1} / 5 · SIMULATED ONLY",font=font(13),fill=muted)
|
||||
return img
|
||||
|
||||
def make_gif(cli):
|
||||
suppliers=invoke(cli,"查询采购商",["采购商状态='正常'"])
|
||||
quote=invoke(cli,"查询采购商价格",["采购商标识符='SUP_JN'","数量=8","有效秒数=300"])
|
||||
balance=invoke(cli,"查询余额",["已花费=120"])
|
||||
orderargs=["采购商标识符='SUP_JN'","数量=8","单价=36","交付要求天数=7"]
|
||||
good=invoke(cli,"向采购商发工单",orderargs+["已花费=120"],effects="time.read,process.control")
|
||||
bad=invoke(cli,"向采购商发工单",orderargs+["已花费=360"],effects="time.read,process.control")
|
||||
assert isinstance(suppliers,list) and any(x.get("标识符")=="SUP_JN" for x in suppliers), suppliers
|
||||
assert quote["单价"]==36 and quote["报价总额"]==288,quote
|
||||
assert balance["可用余额"]==480,balance
|
||||
assert good["ok"] is True and good["value"]["工单金额"]==288 and good["value"]["状态"]=="本地模拟,未发送",good
|
||||
assert bad["ok"] is False and "采购金额超过" in bad["error"],bad
|
||||
|
||||
frames=[
|
||||
frame(0,"01 / Supplier approval",
|
||||
["$ marqdo call ... 查询采购商", " 采购商状态='正常'"],
|
||||
[f"result: {len(suppliers)} approved suppliers", "SUP_JN / 江南配件 / 正常", "Paused and blacklisted suppliers excluded."],
|
||||
"✓ SUP_JN passes supplier status"),
|
||||
frame(1,"02 / Quote lookup",
|
||||
["$ marqdo call ... 查询采购商价格", " 采购商标识符='SUP_JN' 数量=8 有效秒数=300"],
|
||||
[f"单价: ¥{quote['单价']}",f"数量: {quote['数量']}",f"报价总额: ¥{quote['报价总额']}","报价来源: 示例目录(未接实时接口)"],
|
||||
"✓ ¥36 × 8 = ¥288 — example quote"),
|
||||
frame(2,"03 / Budget check",
|
||||
["$ marqdo call ... 查询余额 已花费=120"],
|
||||
[f"最高预算: ¥{balance['最高预算']}",f"已花费: ¥{balance['已花费']}",f"可用余额: ¥{balance['可用余额']}","还能下单: "+str(balance["还能下单"])],
|
||||
"✓ ¥480 ≥ ¥288 — budget check passes"),
|
||||
frame(3,"04 / Callable simulated order",
|
||||
["$ marqdo call ... 向采购商发工单", " SUP_JN 数量=8 单价=36 已花费=120"],
|
||||
[f"result.ok: {str(good['ok']).lower()}", f"工单金额: ¥{good['value']['工单金额']}",f"状态: {good['value']['状态']}","No ERP message, payment or purchase was made."],
|
||||
"✓ SIMULATED ORDER ONLY — NOT SENT"),
|
||||
frame(4,"05 / Over-budget request denied",
|
||||
["$ marqdo call ... 向采购商发工单", " SUP_JN 数量=8 单价=36 已花费=360"],
|
||||
[f"result.ok: {str(bad['ok']).lower()}","最高预算: ¥600","剩余额度: ¥240","工单金额: ¥288", "错误: "+bad["error"]],
|
||||
"× WORK ORDER REFUSED AT RUNTIME",danger=True)
|
||||
]
|
||||
OUT.mkdir(parents=True,exist_ok=True)
|
||||
name=OUT/"procurement-cli.gif"
|
||||
frames[0].save(name,save_all=True,append_images=frames[1:],duration=[1600,1600,1600,1900,2300],loop=0,optimize=True)
|
||||
assert name.stat().st_size>10000, name
|
||||
print("GIF_WRITTEN",name,name.stat().st_size)
|
||||
|
||||
def make_screenshot(cli):
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
import time
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
dest=Path(td)/"view"
|
||||
cmd=[str(cli),"view","output","examples/procurement","--out",str(dest),"--no-exec"]
|
||||
p=subprocess.run(cmd,cwd=ROOT,text=True,capture_output=True,timeout=90)
|
||||
if p.returncode:
|
||||
raise RuntimeError("View output error:\n"+p.stdout+"\n"+p.stderr)
|
||||
pages=sorted(dest.rglob("*.html"),key=lambda p:len(p.parts))
|
||||
print("VIEW_PAGES",[str(p.relative_to(dest)) for p in pages[:40]])
|
||||
if not pages:
|
||||
raise RuntimeError("No HTML pages emitted by Marqdo View")
|
||||
chosen=next((p for p in pages if "向采购商发工单" in p.read_text(encoding="utf-8",errors="replace")),pages[0])
|
||||
opts=Options()
|
||||
for arg in ["--headless=new","--no-sandbox","--disable-dev-shm-usage","--disable-gpu","--window-size=1500,1000"]:
|
||||
opts.add_argument(arg)
|
||||
driver=webdriver.Chrome(options=opts)
|
||||
try:
|
||||
driver.set_window_size(1500,1000)
|
||||
driver.get(chosen.as_uri())
|
||||
time.sleep(2)
|
||||
headings=driver.find_elements(By.CSS_SELECTOR,"h1,h2,h3,h4")
|
||||
matches=[el for el in headings if "向采购商发工单" in el.text]
|
||||
print("VIEW_HEADINGS",[(el.tag_name,el.text[:65]) for el in headings[:25]])
|
||||
if not matches:
|
||||
raise RuntimeError("Couldn't find procurement function heading in exported View")
|
||||
target=matches[0]
|
||||
driver.execute_script("arguments[0].scrollIntoView({block:'start'}); window.scrollBy(0,-115);",target)
|
||||
time.sleep(1)
|
||||
shot=OUT/"procurement-view.png"
|
||||
driver.save_screenshot(str(shot))
|
||||
assert shot.stat().st_size>20000,shot
|
||||
print("VIEW_SCREENSHOT_WRITTEN",shot,shot.stat().st_size)
|
||||
finally:
|
||||
driver.quit()
|
||||
|
||||
if __name__=="__main__":
|
||||
a=argparse.ArgumentParser()
|
||||
a.add_argument("--cli",required=True)
|
||||
args=a.parse_args()
|
||||
make_gif(Path(args.cli).resolve())
|
||||
make_screenshot(Path(args.cli).resolve())
|
||||
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import graphlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
NAME = r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*"
|
||||
FIELDS = {"id", "path", "kind", "state", "owner", "scope", "requires", "checks_with", "release"}
|
||||
ROOT_FILES = {".gitattributes", ".gitignore", ".gitmodules", "AGENTS.md", "LICENSE", "README.md", "components.toml"}
|
||||
ROOT_DIRS = {".gitea", ".woodpecker", "docs", "examples", "scripts"}
|
||||
RELEASE_ROLES = {"core": "base", "stdlib": "base", "extension": "optional", "tool": "optional", "test": "none"}
|
||||
|
||||
|
||||
def git(*args, cwd=ROOT):
|
||||
return subprocess.check_output(["git", "-C", cwd, *args]).decode()
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def catalog(revision):
|
||||
components = tomllib.loads(git("show", f"{revision}:components.toml"))
|
||||
require(set(components) == {"component"} and isinstance(components["component"], list), "invalid catalog")
|
||||
by_id = {}
|
||||
paths = set()
|
||||
for component in components["component"]:
|
||||
state = component.get("state")
|
||||
fields = FIELDS | ({"entry"} if state == "active" else set())
|
||||
require(set(component) == fields and state in {"active", "planned"}, f"invalid fields: {component}")
|
||||
id = component["id"]
|
||||
kind = component["kind"]
|
||||
require(isinstance(id, str) and re.fullmatch(NAME, id) and id not in by_id, f"invalid or duplicate id: {id}")
|
||||
require(kind in RELEASE_ROLES and component["release"] == RELEASE_ROLES[kind], f"invalid release role: {id}")
|
||||
path = component["path"]
|
||||
expected = {
|
||||
"core": "cli" if id == "cli" else None,
|
||||
"test": "tests/conformance" if id == "conformance" else None,
|
||||
"stdlib": f"stdlib/{id.removeprefix('std-')}" if id.startswith("std-") else None,
|
||||
"extension": f"extensions/{id}",
|
||||
"tool": f"tools/{id}",
|
||||
}[kind]
|
||||
require(path == expected and path not in paths, f"invalid or duplicate path: {path}")
|
||||
for key in ("owner", "scope"):
|
||||
require(isinstance(component[key], str) and component[key].strip(), f"missing {key}: {id}")
|
||||
for key in ("requires", "checks_with"):
|
||||
items = component[key]
|
||||
require(isinstance(items, list) and all(isinstance(item, str) for item in items), f"invalid {key}: {id}")
|
||||
require(id not in items and len(set(items)) == len(items), f"invalid {key}: {id}")
|
||||
if state == "active":
|
||||
require(re.fullmatch(r"(?:[a-zA-Z0-9_-]+/)*[a-zA-Z0-9_-][a-zA-Z0-9_.-]*", component["entry"]), f"unsafe entry: {id}")
|
||||
paths.add(path)
|
||||
by_id[id] = component
|
||||
|
||||
for id, component in by_id.items():
|
||||
for field in ("requires", "checks_with"):
|
||||
for dependency in component[field]:
|
||||
require(dependency in by_id, f"unknown dependency: {id} -> {dependency}")
|
||||
target = by_id[dependency]
|
||||
require(component["state"] != "active" or target["state"] == "active", f"active depends on planned: {id} -> {dependency}")
|
||||
if field == "requires":
|
||||
require(component["kind"] != "stdlib" or target["kind"] in {"core", "stdlib"}, f"stdlib dependency violation: {id} -> {dependency}")
|
||||
require(component["kind"] != "tool" or target["kind"] == "core", f"tool dependency violation: {id} -> {dependency}")
|
||||
tuple(graphlib.TopologicalSorter({id: item["requires"] for id, item in by_id.items()}).static_order())
|
||||
return by_id
|
||||
|
||||
|
||||
def tree(revision):
|
||||
entries = {}
|
||||
for record in git("ls-tree", "-rz", "--full-tree", revision).split("\0"):
|
||||
if record:
|
||||
metadata, path = record.split("\t", 1)
|
||||
mode, _, sha = metadata.split()
|
||||
entries[path] = (mode, sha)
|
||||
return entries
|
||||
|
||||
|
||||
def validate(revision, checkouts):
|
||||
components = catalog(revision)
|
||||
active = {item["path"]: item for item in components.values() if item["state"] == "active"}
|
||||
entries = tree(revision)
|
||||
gitlinks = {path: sha for path, (mode, sha) in entries.items() if mode == "160000"}
|
||||
require(gitlinks.keys() == active.keys(), f"gitlink/catalog mismatch: {sorted(gitlinks.keys() ^ active.keys())}")
|
||||
for path, (mode, _) in entries.items():
|
||||
root = path.split("/", 1)[0]
|
||||
require(
|
||||
path in active or (mode in {"100644", "100755"} and (
|
||||
path in ROOT_FILES or root in ROOT_DIRS and "/" in path or path.startswith("tests/integration/")
|
||||
)),
|
||||
f"unexpected tracked path or mode: {path} ({mode})",
|
||||
)
|
||||
|
||||
config = {}
|
||||
for record in git("config", "--null", "--blob", f"{revision}:.gitmodules", "--list").split("\0"):
|
||||
if record:
|
||||
key, value = record.split("\n", 1)
|
||||
require(key not in config, f"duplicate submodule setting: {key}")
|
||||
config[key] = value
|
||||
for path, item in active.items():
|
||||
prefix = f"submodule.{path}."
|
||||
require(config.pop(prefix + "path", None) == path, f"missing or invalid submodule path: {path}")
|
||||
url = config.pop(prefix + "url", "")
|
||||
require(re.fullmatch(rf"https://git\.cflmy\.cn/cflmy/marqdo-{NAME}\.git", url), f"invalid submodule URL: {path}")
|
||||
if item["kind"] == "stdlib":
|
||||
require(url.endswith(f"/marqdo-{item['id']}.git"), f"invalid standard library repo name: {path}")
|
||||
if item["kind"] == "extension":
|
||||
require(url.endswith(f"/marqdo-ext-{item['id']}.git"), f"invalid extension repo name: {path}")
|
||||
if checkouts:
|
||||
checkout = ROOT / path
|
||||
sha = gitlinks[path]
|
||||
require(checkout.resolve() == checkout and (checkout / ".git").exists(), f"missing submodule checkout: {path}")
|
||||
require(git("rev-parse", "HEAD", cwd=checkout).strip() == sha, f"wrong checked-out commit: {path}")
|
||||
require(not git("status", "--porcelain", cwd=checkout), f"dirty submodule: {path}")
|
||||
entry = checkout / item["entry"]
|
||||
require(entry.is_file() and entry.resolve() == entry, f"missing or symbolic entry: {path}/{item['entry']}")
|
||||
print(f"{item['id']} {path} {gitlinks[path]}")
|
||||
require(not config, f"unexpected submodule settings: {sorted(config)}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Validate a Marqdo ecosystem Git tree")
|
||||
parser.add_argument("revision", nargs="?", default="HEAD")
|
||||
parser.add_argument("--checkouts", action="store_true")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
validate(git("rev-parse", "--verify", args.revision + "^{commit}").strip(), args.checkouts)
|
||||
except (AttributeError, KeyError, OSError, subprocess.CalledProcessError, TypeError, ValueError) as error:
|
||||
sys.exit(f"layout: {error}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,33 +0,0 @@
|
||||
#!/bin/sh
|
||||
# 校验内嵌语义底座(src/prove/driver.rs include_str!)与
|
||||
# doc/verification/skill-proof/MarqdoProof.lean 一致,并输出其 sha256。
|
||||
# 用法:scripts/check-proof-library.sh [LEAN_BIN]
|
||||
# LEAN_BIN 缺省用 PATH/MARQDO_PROOF_LEAN 里的 lean。
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
LIB=doc/verification/skill-proof/MarqdoProof.lean
|
||||
LEAN_BIN="${1:-${MARQDO_PROOF_LEAN:-lean}}"
|
||||
|
||||
# 1) 内嵌源必须与仓库里的底座逐字节一致(发布二进制自带它)。
|
||||
# driver.rs 的 include_str! 在编译期锁定该路径;这里再防人手改跑偏。
|
||||
grep -q 'include_str!("../../doc/verification/skill-proof/MarqdoProof.lean")' src/prove/driver.rs
|
||||
|
||||
# 2) 底座 sha256(写进判定证书,判定可复核)。
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
SHA=$(sha256sum "$LIB" | cut -d' ' -f1)
|
||||
else
|
||||
SHA=$(shasum -a 256 "$LIB" | cut -d' ' -f1)
|
||||
fi
|
||||
echo "MarqdoProof.lean sha256: $SHA"
|
||||
|
||||
# 3) (可选)真机验底座本身可编译。
|
||||
if command -v "$LEAN_BIN" >/dev/null 2>&1; then
|
||||
TMP=$(mktemp -d)
|
||||
cp "$LIB" "$TMP/MarqdoProof.lean"
|
||||
(cd "$TMP" && "$LEAN_BIN" -o MarqdoProof.olean MarqdoProof.lean)
|
||||
rm -rf "$TMP"
|
||||
echo "MarqdoProof.lean compiles with $LEAN_BIN"
|
||||
else
|
||||
echo "(未找到 $LEAN_BIN,跳过底座编译验证)"
|
||||
fi
|
||||
@@ -1,52 +0,0 @@
|
||||
# Deploy public/ static site to branch gh-pages.
|
||||
$ErrorActionPreference = "Stop"
|
||||
$Root = Split-Path $PSScriptRoot -Parent
|
||||
Set-Location $Root
|
||||
|
||||
function Invoke-Git {
|
||||
param([Parameter(ValueFromRemainingArguments = $true)][string[]]$GitArgs)
|
||||
$prev = $ErrorActionPreference
|
||||
$ErrorActionPreference = "Continue"
|
||||
& git @GitArgs 2>&1 | Out-Null
|
||||
$code = $LASTEXITCODE
|
||||
$ErrorActionPreference = $prev
|
||||
if ($code -ne 0) { throw "git $($GitArgs -join ' ') failed (exit $code)" }
|
||||
}
|
||||
|
||||
if (-not (Test-Path "public\index.html")) {
|
||||
Write-Host "Building public site..."
|
||||
cargo build --release -q
|
||||
& .\target\release\marqdo.exe view output public -o public
|
||||
}
|
||||
|
||||
$staging = Join-Path $Root "dist\gh-pages-publish"
|
||||
if (Test-Path $staging) {
|
||||
$prev = $ErrorActionPreference
|
||||
$ErrorActionPreference = "Continue"
|
||||
git worktree remove $staging -f 2>&1 | Out-Null
|
||||
$ErrorActionPreference = $prev
|
||||
Remove-Item $staging -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
Invoke-Git fetch origin gh-pages
|
||||
Invoke-Git worktree add -B gh-pages $staging origin/gh-pages
|
||||
|
||||
Get-ChildItem $staging -Force | Where-Object { $_.Name -ne ".git" } | Remove-Item -Recurse -Force
|
||||
Copy-Item -Recurse (Join-Path $Root "public\*") $staging -Force
|
||||
|
||||
Set-Location $staging
|
||||
Invoke-Git add -A
|
||||
$status = git status --porcelain
|
||||
if ($status) {
|
||||
Invoke-Git commit -m "Deploy public site for v0.1.2"
|
||||
Invoke-Git push origin gh-pages
|
||||
Write-Host "Pushed gh-pages"
|
||||
} else {
|
||||
Write-Host "gh-pages unchanged"
|
||||
}
|
||||
|
||||
Set-Location $Root
|
||||
$prev = $ErrorActionPreference
|
||||
$ErrorActionPreference = "Continue"
|
||||
git worktree remove $staging -f 2>&1 | Out-Null
|
||||
$ErrorActionPreference = $prev
|
||||
@@ -1,48 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Marqdo dev environment.
|
||||
#
|
||||
# Usage: source scripts/dev-env.sh
|
||||
#
|
||||
# If a bundled toolchain is present under target/toolchain/, it is preferred;
|
||||
# otherwise the script keeps using tools already installed on PATH. This makes
|
||||
# the script work both in the maintained sandbox image and on a normal dev host.
|
||||
#
|
||||
# Two non-obvious constraints this script encodes:
|
||||
# 1. $HOME is not writable -> zig/rust caches must be redirected explicitly.
|
||||
# 2. /tmp is a noexec tmpfs -> anything a build *executes* from a temp dir
|
||||
# fails with "AccessDenied" (zig link step) or "signal: aborted" (go link
|
||||
# step via gcc). TMPDIR must point at a writable+executable dir.
|
||||
|
||||
_marqdo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
_tc="$_marqdo_root/target/toolchain"
|
||||
_zshim="${MARQDO_ZIG_SHIM:-$_marqdo_root/.tools/zigcc}"
|
||||
|
||||
_prepend_existing() {
|
||||
[ -d "$1" ] && PATH="$1:$PATH"
|
||||
}
|
||||
|
||||
export RUSTUP_HOME="${RUSTUP_HOME:-$_tc/rustup}"
|
||||
export CARGO_HOME="${CARGO_HOME:-$_tc/cargo}"
|
||||
export GOCACHE="${GOCACHE:-$_tc/gocache}"
|
||||
export GOPATH="${GOPATH:-$_tc/gopath}"
|
||||
export TMPDIR="${TMPDIR:-$_tc/tmp}"
|
||||
export ZIG_GLOBAL_CACHE_DIR="${ZIG_GLOBAL_CACHE_DIR:-$_tc/zigcache}"
|
||||
export ZIG_LOCAL_CACHE_DIR="${ZIG_LOCAL_CACHE_DIR:-$_tc/zigcache}"
|
||||
|
||||
_prepend_existing "$_zshim/bin"
|
||||
_prepend_existing "$_tc/bin"
|
||||
_prepend_existing "$_tc/python/bin"
|
||||
_prepend_existing "$_tc/go/bin"
|
||||
_prepend_existing "$_tc/cargo/bin"
|
||||
|
||||
# Rust: link through zig cc pinned to glibc 2.36 so the binary runs on this host.
|
||||
if [ -x "$_zshim/cc" ] && [ -x "$_zshim/ar" ]; then
|
||||
export CC="$_zshim/cc"
|
||||
export CXX="$_zshim/cc"
|
||||
export AR="$_zshim/ar"
|
||||
export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER="$_zshim/cc"
|
||||
fi
|
||||
|
||||
mkdir -p "$TMPDIR" "$GOCACHE" "$GOPATH" "$ZIG_GLOBAL_CACHE_DIR"
|
||||
|
||||
echo "marqdo dev-env: rust=$(rustc --version 2>/dev/null | cut -d' ' -f2 || echo missing) go=$(go version 2>/dev/null | awk '{print $3}' || echo missing) python=$(python3 --version 2>&1 | awk '{print $2}' || echo missing)"
|
||||
Executable
+87
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
root="$PWD"
|
||||
python3 scripts/check-layout.py --checkouts
|
||||
active="$(git ls-tree -r HEAD | awk '$1 == "160000" { print $4 }')"
|
||||
expected=$'cli\ntests/conformance\ntools/knowledge\ntools/lint\ntools/prove\ntools/view'
|
||||
if [[ "$active" != "$expected" ]]; then
|
||||
echo "UNVERIFIED: update the integration plan for the changed active component set" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p .integration-work
|
||||
work="$(mktemp -d "$root/.integration-work/run.XXXXXX")"
|
||||
echo "integration evidence: $work"
|
||||
exec > >(tee "$work/run.log") 2>&1
|
||||
set -x
|
||||
git rev-parse HEAD
|
||||
git submodule status
|
||||
uname -m
|
||||
ldd --version
|
||||
cargo --version
|
||||
python3 --version
|
||||
python3 -c 'import jsonschema'
|
||||
|
||||
unset MARQDO_STDLIB_DIR
|
||||
export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}"
|
||||
mkdir "$work/frozen"
|
||||
frozen="$root/tools/view/scripts/frozen-beta.sh"
|
||||
metadata="$("$frozen" metadata)"
|
||||
artifact="$(sed -n 's/^artifact=//p' <<<"$metadata")"
|
||||
if [[ -n "${MARQDO_INTEGRATION_ARCHIVE:-}" ]]; then
|
||||
archive="$(realpath "$MARQDO_INTEGRATION_ARCHIVE")"
|
||||
archive_sha="$(sed -n 's/^archive_sha=//p' <<<"$metadata")"
|
||||
printf '%s %s\n' "$archive_sha" "$archive" | sha256sum -c -
|
||||
tar -xzf "$archive" -C "$work/frozen"
|
||||
MARQDO_BIN="$work/frozen/$artifact/marqdo"
|
||||
"$frozen" verify "$MARQDO_BIN"
|
||||
else
|
||||
MARQDO_BIN="$("$frozen" fetch "$work/frozen")"
|
||||
archive="$work/frozen/$artifact.tar.gz"
|
||||
fi
|
||||
export MARQDO_BIN
|
||||
source_sha="$(git -C cli rev-parse HEAD)"
|
||||
test "$(cat "$(dirname "$MARQDO_BIN")/SOURCE_SHA")" = "$source_sha"
|
||||
sha256sum "$archive" "$MARQDO_BIN" "$(dirname "$MARQDO_BIN")/marqdo-provider-worker"
|
||||
|
||||
python3 cli/tools/release/smoke.py --archive "$archive"
|
||||
python3 cli/tools/ci/verify_extension_contracts.py \
|
||||
--source-repo cli --tested-sha "$source_sha" --cli "$MARQDO_BIN" \
|
||||
--release-info "$(dirname "$MARQDO_BIN")/RELEASE_INFO.json" \
|
||||
--fixtures tests/conformance --out "$work/conformance.json"
|
||||
|
||||
(
|
||||
cd tools/view
|
||||
export MARQDO_TOOL_HOME="$work/view-registry"
|
||||
scripts/package.sh
|
||||
"$MARQDO_BIN" tool install dist/marqdo-view/tool.json
|
||||
"$MARQDO_BIN" view verify examples/mixed-modes/index.mq.md
|
||||
"$MARQDO_BIN" view export examples/tables-math --out "$work/view-export"
|
||||
python3 scripts/check-observation.py stream-snapshot
|
||||
"$MARQDO_BIN" tool remove view
|
||||
if "$MARQDO_BIN" view --version; then
|
||||
echo "view still dispatches after removal" >&2
|
||||
exit 1
|
||||
fi
|
||||
)
|
||||
|
||||
(
|
||||
cd tools/knowledge
|
||||
MARQDO_TEST_BIN="$MARQDO_BIN" cargo test --locked --test core_cli --test compile
|
||||
)
|
||||
(
|
||||
cd tools/prove
|
||||
cargo test --locked --test analysis_document --test document_contract
|
||||
)
|
||||
(
|
||||
cd tools/lint
|
||||
export MARQDO_TOOL_HOME="$work/lint-registry"
|
||||
scripts/package-tool.sh "$work/lint"
|
||||
"$MARQDO_BIN" tool install "$work/lint/tool.json"
|
||||
"$MARQDO_BIN" lint examples/nested/inventory.mq.md --format json
|
||||
"$MARQDO_BIN" tool remove lint
|
||||
)
|
||||
|
||||
echo "PASS: ecosystem RC.4 candidate checks"
|
||||
@@ -1,369 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Make a 16:9 Marqdo promotional video from checked-in repository assets.
|
||||
|
||||
Inputs: GIF generated from actual v2.7.1 CLI results, and screenshot captured
|
||||
from actual v2.7.1 View. The budget scenario is explicitly simulated.
|
||||
Everything used to reproduce this movie is in the repository.
|
||||
No third-party soundtrack or music clips are used.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import wave
|
||||
from bisect import bisect_right
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ASSETS = ROOT / "assets" / "marketing"
|
||||
GIF = ASSETS / "procurement-cli.gif"
|
||||
VIEW = ASSETS / "procurement-view.png"
|
||||
PROC = ROOT / "examples" / "procurement" / "index.mq.md"
|
||||
OUT = ASSETS / "marqdo-2.7.1-promo.mp4"
|
||||
POSTER = ASSETS / "marqdo-2.7.1-poster.jpg"
|
||||
SUBTITLES = ASSETS / "marqdo-2.7.1-promo.srt"
|
||||
W, H, FPS = 1280, 720, 24
|
||||
DURATION = 32.0
|
||||
CUTS = [0.0, 3.9, 9.0, 17.4, 23.4, 29.0, DURATION]
|
||||
DARK = (11, 19, 32)
|
||||
GOLD = (232, 187, 123)
|
||||
LIGHT = (248, 246, 238)
|
||||
MUTED = (155, 174, 197)
|
||||
GREEN = (125, 224, 174)
|
||||
RED = (251, 151, 155)
|
||||
|
||||
def rgb(c):
|
||||
return tuple(c)
|
||||
|
||||
def choose_font(size, bold=False, serif=False):
|
||||
paths = [
|
||||
"/usr/share/fonts/opentype/noto/NotoSerifCJK-Bold.ttc" if serif and bold else "",
|
||||
"/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc" if serif else "",
|
||||
"/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc" if bold else "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
]
|
||||
for p in paths:
|
||||
if not p:
|
||||
continue
|
||||
try:
|
||||
return ImageFont.truetype(p, size)
|
||||
except OSError:
|
||||
continue
|
||||
return ImageFont.load_default()
|
||||
|
||||
F = {
|
||||
"hero": choose_font(72, True),
|
||||
"big": choose_font(55, True),
|
||||
"h1": choose_font(42, True),
|
||||
"h2": choose_font(31, True),
|
||||
"mid": choose_font(25, True),
|
||||
"code": choose_font(23),
|
||||
"body": choose_font(22),
|
||||
"small": choose_font(17),
|
||||
"micro": choose_font(14),
|
||||
"zh": choose_font(28, serif=True),
|
||||
}
|
||||
|
||||
def text(draw, xy, msg, font, color=LIGHT, anchor=None):
|
||||
draw.text(xy, str(msg), font=font, fill=color, anchor=anchor)
|
||||
|
||||
def panel(draw, xy, fill=(24,35,54), outline=(51,67,89), rad=23, width=2):
|
||||
draw.rounded_rectangle(xy, radius=rad, fill=fill, outline=outline, width=width)
|
||||
|
||||
def mix(a, b, t):
|
||||
return a + (b-a)*t
|
||||
|
||||
def ease(x):
|
||||
u = max(0., min(1., x))
|
||||
return u*u*(3-2*u)
|
||||
|
||||
def appear(t, delay=0., span=.65):
|
||||
return ease((t-delay)/span)
|
||||
|
||||
def xshift(t, delay=.0):
|
||||
return int(38*(1-appear(t,delay)))
|
||||
|
||||
def opacity_overlay(base, overlay, alpha):
|
||||
return Image.blend(base, overlay, max(0.,min(1.,alpha)))
|
||||
|
||||
def clipped(src, size, center=(.5,.5), zoom=1):
|
||||
w,h=size
|
||||
if zoom > 1:
|
||||
p=ImageOps.fit(src,(int(w*zoom),int(h*zoom)),method=Image.Resampling.LANCZOS,centering=center)
|
||||
z=(p.width-w)//2
|
||||
v=(p.height-h)//2
|
||||
return p.crop((z,v,z+w,v+h))
|
||||
return ImageOps.fit(src,size,method=Image.Resampling.LANCZOS,centering=center)
|
||||
|
||||
def background(seed=0):
|
||||
im = Image.new("RGB",(W,H),DARK)
|
||||
pix=im.load()
|
||||
for y in range(H):
|
||||
for x in range(W):
|
||||
glow= max(0,1-math.hypot((x-1090)/1.3,(y-95)/1.1)/520)
|
||||
edge= max(0,1-math.hypot((x-25),y-690)/500)
|
||||
pix[x,y]=(int(11+14*glow+7*edge),int(19+9*glow+7*edge),int(32+13*glow+10*edge))
|
||||
d=ImageDraw.Draw(im)
|
||||
for x in range(45,W,82):
|
||||
d.line((x,0,x,H),fill=(18,29,45),width=1)
|
||||
for y in range(48,H,82):
|
||||
d.line((0,y,W,y),fill=(18,29,45),width=1)
|
||||
return im
|
||||
|
||||
BG=background()
|
||||
|
||||
def base_frame(t,scene):
|
||||
im=BG.copy()
|
||||
d=ImageDraw.Draw(im)
|
||||
# top identity, bottom running progress
|
||||
text(d,(63,35),"MARQDO",F["small"],GOLD)
|
||||
text(d,(168,36),"/ EXECUTABLE AI SKILLS",F["micro"],MUTED)
|
||||
d.rounded_rectangle((1079,21,1211,57),radius=15,fill=(40,51,68))
|
||||
text(d,(1095,30),"v2.7.1",F["small"],LIGHT)
|
||||
d.line((62,76,1214,76),fill=(48,61,80),width=2)
|
||||
d.line((62,694,1214,694),fill=(47,61,80),width=2)
|
||||
d.line((62,694,62+int((1152)*(t/DURATION)),694),fill=GOLD,width=4)
|
||||
text(d,(64,705),"DOCUMENT → FUNCTION → TOOL",F["micro"],(104,120,141))
|
||||
text(d,(1115,705),"%02d / 06" % (scene+1),F["micro"],(104,120,141))
|
||||
return im,d
|
||||
|
||||
def scene_hero(local,global_t):
|
||||
im,d=base_frame(global_t,0)
|
||||
a=appear(local,.07)
|
||||
yy=xshift(local,.08)
|
||||
text(d,(69,167+yy),"Your SKILL",F["hero"],LIGHT)
|
||||
text(d,(69,264+yy),"is now a",F["hero"],LIGHT)
|
||||
text(d,(69,361+yy),"TOOL.",F["hero"],GOLD)
|
||||
# typographic bar
|
||||
x=69
|
||||
d.rounded_rectangle((x,485,x+min(643,int(643*a)),489),radius=2,fill=GOLD)
|
||||
text(d,(71,520),"Write it. Inspect it. Call it.",F["mid"],LIGHT)
|
||||
text(d,(71,573),"让可读文档中的函数,真正成为可调用工具。",F["zh"],(224,219,205))
|
||||
d.rounded_rectangle((975,207,1169,493),radius=25,fill=(26,37,57),outline=(84,99,118),width=2)
|
||||
text(d,(1017,276),".mq.md",F["h2"],GOLD)
|
||||
text(d,(1017,357),"01 Read",F["small"],MUTED)
|
||||
text(d,(1017,399),"02 Call",F["small"],MUTED)
|
||||
text(d,(1017,441),"03 Check",F["small"],MUTED)
|
||||
return im
|
||||
|
||||
SOURCE_LINES=[
|
||||
"## 向采购商发工单",
|
||||
"采购商标识符 数量 单价 已花费",
|
||||
"",
|
||||
"正常商户 = 查询采购商(...)",
|
||||
"报价 = 查询采购商价格(...)",
|
||||
"预算 = 查询余额(已花费=...)",
|
||||
"",
|
||||
"1. 剩余额度 < 本单金额",
|
||||
" → 拒绝模拟工单",
|
||||
]
|
||||
def scene_source(local,global_t):
|
||||
im,d=base_frame(global_t,1)
|
||||
text(d,(71,110),"ONE DOCUMENT.",F["h1"],LIGHT)
|
||||
text(d,(71,159),"Contract, data, policy and implementation in the same .mq.md.",F["body"],MUTED)
|
||||
panel(d,(67,205,842,642),fill=(18,28,44),outline=(72,91,113))
|
||||
d.rounded_rectangle((67,205,842,254),radius=17,fill=(35,48,67))
|
||||
text(d,(93,218),"index.mq.md / procurement skill",F["small"],GOLD)
|
||||
ready=int(len(SOURCE_LINES)*ease((local-.40)/3.8))
|
||||
for i,ln in enumerate(SOURCE_LINES[:ready]):
|
||||
clr=GOLD if i in (0,7) else GREEN if i==8 else (178,204,232)
|
||||
text(d,(101,279+i*37),ln,F["code"],clr)
|
||||
panel(d,(863,205,1214,642),fill=(24,35,55),outline=(74,88,107))
|
||||
for j,(label,desc) in enumerate([
|
||||
("01 READ","human-readable"),
|
||||
("02 CHECK","typed contracts"),
|
||||
("03 CALL","marqdo call"),
|
||||
("04 RETURN","structured values")
|
||||
]):
|
||||
y=268+j*96
|
||||
d.rounded_rectangle((888,y,1187,y+66),radius=13,fill=(30,48,65))
|
||||
text(d,(907,y+11),label,F["small"],GOLD)
|
||||
text(d,(907,y+34),desc,F["micro"],(186,203,220))
|
||||
text(d,(71,662),"Excerpt simplified for screen layout; the full source is linked in the repository.",F["micro"],(110,135,154))
|
||||
return im
|
||||
|
||||
GIF_FRAMES=[]
|
||||
GIF_DURATIONS=[]
|
||||
if GIF.exists():
|
||||
im=Image.open(GIF)
|
||||
for i in range(getattr(im,"n_frames",1)):
|
||||
im.seek(i)
|
||||
GIF_FRAMES.append(im.convert("RGB").copy())
|
||||
GIF_DURATIONS.append(max(.3, im.info.get("duration",1600)/1000))
|
||||
if len(GIF_FRAMES) < 5:
|
||||
raise RuntimeError(f"Expected >= 5 real CLI demonstration frames, found {len(GIF_FRAMES)}")
|
||||
else:
|
||||
raise FileNotFoundError(GIF)
|
||||
GIF_CUM=[0.]
|
||||
for dur in GIF_DURATIONS:
|
||||
GIF_CUM.append(GIF_CUM[-1]+dur)
|
||||
GIF_CYCLE=GIF_CUM[-1]
|
||||
GIF_FITTED=[clipped(im,(1136,620)) for im in GIF_FRAMES]
|
||||
|
||||
def scene_cli(local,global_t):
|
||||
im,d=base_frame(global_t,2)
|
||||
# The 5 panels are constructed from real calls and validated in the original capture script.
|
||||
k=min(len(GIF_FITTED)-1,bisect_right(GIF_CUM,(local+.3)%GIF_CYCLE)-1)
|
||||
im.paste(GIF_FITTED[k],(72,73))
|
||||
d=ImageDraw.Draw(im)
|
||||
d.rectangle((73,73,1210,113),fill=(15,24,37))
|
||||
text(d,(91,82),"REAL CLI RETURNS / CURATED ANIMATED WALKTHROUGH",F["small"],GOLD)
|
||||
d.rectangle((76,664,1206,688),fill=(15,24,37))
|
||||
text(d,(87,665),"Supplier → Quote → Balance → Mock order → Over-budget refusal",F["small"],LIGHT)
|
||||
return im
|
||||
|
||||
def scene_outcomes(local,global_t):
|
||||
im,d=base_frame(global_t,3)
|
||||
text(d,(70,113),"THE LIMIT IS EXECUTED.",F["h1"])
|
||||
text(d,(70,164),"Two calls. Same unit price. Different accumulated spend.",F["body"],MUTED)
|
||||
q=ease((local-.6)/1.5)
|
||||
left=120+int(288*q)
|
||||
right=360+int(288*q)
|
||||
panel(d,(70,219,616,610),fill=(17,49,43),outline=(69,124,102))
|
||||
panel(d,(652,219,1202,610),fill=(55,29,39),outline=(150,78,90))
|
||||
text(d,(99,253),"ALLOWED · SIMULATION",F["small"],GREEN)
|
||||
text(d,(681,253),"DENIED · RUNTIME CHECK",F["small"],RED)
|
||||
text(d,(99,304),"¥120 + ¥288",F["h2"],LIGHT)
|
||||
text(d,(681,304),"¥360 + ¥288",F["h2"],LIGHT)
|
||||
text(d,(99,396),"¥"+str(left),F["hero"],GREEN)
|
||||
text(d,(681,396),"¥"+str(right),F["hero"],RED)
|
||||
text(d,(103,445),"≤ ¥600",F["mid"],(196,239,212))
|
||||
text(d,(686,445),"> ¥600",F["mid"],(255,202,211))
|
||||
d.line((100,476,581,476),fill=(77,119,101),width=2)
|
||||
d.line((681,476,1170,476),fill=(135,80,90),width=2)
|
||||
text(d,(101,497),"ok: true",F["mid"],GREEN)
|
||||
text(d,(680,497),"ok: false",F["mid"],RED)
|
||||
text(d,(101,553),"本地模拟,未发送",F["body"],(211,233,220))
|
||||
text(d,(680,553),"采购金额超过剩余额度",F["body"],(251,213,217))
|
||||
text(d,(71,651),"The function re-checks its own budget constraints. This is an offline example, not a real purchase.",F["micro"],MUTED)
|
||||
return im
|
||||
|
||||
VIEW_IMAGE=Image.open(VIEW).convert("RGB")
|
||||
VIEW_PANEL=(101,195,1179,635)
|
||||
VIEW_MASK=Image.new("L",(VIEW_PANEL[2]-VIEW_PANEL[0],VIEW_PANEL[3]-VIEW_PANEL[1]),0)
|
||||
ImageDraw.Draw(VIEW_MASK).rounded_rectangle((0,0,VIEW_MASK.width-1,VIEW_MASK.height-1),radius=18,fill=255)
|
||||
|
||||
def scene_view(local,global_t):
|
||||
im,d=base_frame(global_t,4)
|
||||
text(d,(70,111),"THE SAME SOURCE, BEAUTIFULLY INSPECTABLE.",F["h2"])
|
||||
text(d,(71,158),"Marqdo 2.7.1 View — an actual screenshot of the procurement function.",F["body"],MUTED)
|
||||
factor=1+.06*ease(local/5)
|
||||
content=clipped(VIEW_IMAGE,(VIEW_MASK.width,VIEW_MASK.height),center=(.50,.38),zoom=factor)
|
||||
im.paste(content,(VIEW_PANEL[0],VIEW_PANEL[1]),VIEW_MASK)
|
||||
d=ImageDraw.Draw(im)
|
||||
d.rounded_rectangle(VIEW_PANEL,radius=18,outline=(199,165,118),width=3)
|
||||
text(d,(104,665),"From marqdo view output • function 向采购商发工单",F["small"],(187,207,222))
|
||||
return im
|
||||
|
||||
def scene_outro(local,global_t):
|
||||
im,d=base_frame(global_t,5)
|
||||
text(d,(71,163),"One .mq.md",F["hero"],LIGHT)
|
||||
text(d,(71,260),"Many ways to use it.",F["h1"],GOLD)
|
||||
d.rounded_rectangle((70,365,1212,436),radius=19,fill=(33,49,67),outline=(81,101,124),width=2)
|
||||
text(d,(107,381),"Write it. Inspect it. Call it.",F["h2"],LIGHT)
|
||||
text(d,(73,490),"github.com/cflmy/marqdo",F["h1"],GOLD)
|
||||
text(d,(73,548),"Marqdo 2.7.1 • Rust-based document-native runtime",F["body"],MUTED)
|
||||
text(d,(73,613),"Demo uses simulated supplier data. No ERP connection or actual purchase.",F["small"],(176,190,204))
|
||||
return im
|
||||
|
||||
SCENE_FNS=[scene_hero,scene_source,scene_cli,scene_outcomes,scene_view,scene_outro]
|
||||
def render(t):
|
||||
i=min(len(SCENE_FNS)-1,bisect_right(CUTS,t)-1)
|
||||
im=SCENE_FNS[i](t-CUTS[i],t)
|
||||
end=CUTS[i+1]
|
||||
if i<len(SCENE_FNS)-1 and t > end-.43:
|
||||
other=SCENE_FNS[i+1](0,t)
|
||||
im=Image.blend(im,other,ease((t-(end-.43))/.43))
|
||||
return im
|
||||
|
||||
def make_audio(path):
|
||||
sr=24000
|
||||
count=round(DURATION*sr)
|
||||
times=np.arange(count,dtype=np.float64)/sr
|
||||
signal=np.zeros(count,dtype=np.float64)
|
||||
chords=[(110.0,164.8,220.0),(123.5,185.0,246.9),(130.8,196.0,261.6),(110.0,174.6,220.0),(123.5,185.0,246.9),(130.8,196.0,261.6)]
|
||||
for idx in range(6):
|
||||
start,end=CUTS[idx],CUTS[idx+1]
|
||||
mask=(times>=start)&(times<end)
|
||||
t=times[mask]-start
|
||||
fade=np.minimum(1,np.minimum(t/.8, (end-start-t)/.85).clip(min=0))
|
||||
notes=chords[idx]
|
||||
wavepad=(np.sin(2*np.pi*notes[0]*t)*0.54+
|
||||
np.sin(2*np.pi*notes[1]*t)*0.18+
|
||||
np.sin(2*np.pi*notes[2]*t)*0.12)
|
||||
signal[mask] += 0.12*fade*wavepad
|
||||
for at in CUTS[:-1]:
|
||||
start=int(at*sr)
|
||||
length=int(.16*sr)
|
||||
n=np.arange(length,dtype=np.float64)/sr
|
||||
chirp=(np.sin(2*np.pi*(640*n+680*n*n))*np.exp(-24*n))*0.12
|
||||
signal[start:start+length] += chirp
|
||||
signal *= np.minimum(1,np.minimum(times/1.2, (DURATION-times)/1.2).clip(min=0))
|
||||
pcm=np.clip(signal*32767,-32767,32767).astype(np.int16)
|
||||
with wave.open(str(path),"wb") as wav:
|
||||
wav.setnchannels(1);wav.setsampwidth(2);wav.setframerate(sr)
|
||||
wav.writeframes(pcm.tobytes())
|
||||
|
||||
def make_srt():
|
||||
times=[("00:00:00,000","00:00:03,900","Your SKILL is now a TOOL.\n让 SKILL 真正成为工具。"),
|
||||
("00:00:03,900","00:00:09,000","One readable document. Callable business logic.\n规则、数据、工具在同一份文档里。"),
|
||||
("00:00:09,000","00:00:17,400","Five verified CLI calls, from quote to decision.\n真实 CLI 结果:询价、预算、模拟发单。"),
|
||||
("00:00:17,400","00:00:23,400","¥120 spent: mock order. ¥360 spent: rejected.\n¥120 时模拟通过;¥360 时预算不足。"),
|
||||
("00:00:23,400","00:00:29,000","Inspect the actual document in Marqdo View.\n查看 Marqdo 真实 View 页面。"),
|
||||
("00:00:29,000","00:00:32,000","github.com/cflmy/marqdo\n开源 · Marqdo 2.7.1")]
|
||||
txt="\n\n".join(f"{i+1}\n{a} --> {b}\n{c}" for i,(a,b,c) in enumerate(times))+"\n"
|
||||
SUBTITLES.write_text(txt,encoding="utf-8")
|
||||
|
||||
def main():
|
||||
if not PROC.exists() or not VIEW.exists():
|
||||
raise FileNotFoundError("Expected procurement source and actual View screenshot")
|
||||
source=PROC.read_text("utf-8")
|
||||
assert "## 向采购商发工单" in source and "查询余额" in source
|
||||
assert VIEW_IMAGE.width >= 1200 and VIEW_IMAGE.height >= 700
|
||||
OUT.parent.mkdir(parents=True,exist_ok=True)
|
||||
POSTER_IMG=render(1.8)
|
||||
POSTER_IMG.save(POSTER,quality=92,optimize=True)
|
||||
make_srt()
|
||||
frames=int(DURATION*FPS)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
unscored=Path(tmp)/"silent.mp4"
|
||||
music=Path(tmp)/"music.wav"
|
||||
cmd=["ffmpeg","-y","-hide_banner","-loglevel","error","-f","rawvideo",
|
||||
"-pixel_format","rgb24","-video_size",f"{W}x{H}","-framerate",str(FPS),
|
||||
"-i","pipe:0","-an","-c:v","libx264","-preset","veryfast","-crf","21",
|
||||
"-pix_fmt","yuv420p","-movflags","+faststart",str(unscored)]
|
||||
proc=subprocess.Popen(cmd,stdin=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||
try:
|
||||
for k in range(frames):
|
||||
fr=render(k/FPS)
|
||||
proc.stdin.write(fr.tobytes())
|
||||
if k%120==0:
|
||||
print("rendered",k,"/",frames,flush=True)
|
||||
finally:
|
||||
if proc.stdin:
|
||||
proc.stdin.close()
|
||||
stderr=proc.stderr.read().decode(errors="replace")
|
||||
rc=proc.wait(timeout=70)
|
||||
if rc:
|
||||
raise RuntimeError("Video encoder error: "+stderr)
|
||||
make_audio(music)
|
||||
subprocess.run(["ffmpeg","-y","-hide_banner","-loglevel","error",
|
||||
"-i",str(unscored),"-i",str(music),"-c:v","copy","-c:a",
|
||||
"aac","-b:a","128k","-shortest","-movflags","+faststart",
|
||||
str(OUT)],check=True,timeout=90)
|
||||
print("VIDEO_WRITTEN",OUT,OUT.stat().st_size,flush=True)
|
||||
print("POSTER_WRITTEN",POSTER,POSTER.stat().st_size,flush=True)
|
||||
print("SUBTITLES_WRITTEN",SUBTITLES,SUBTITLES.stat().st_size,flush=True)
|
||||
ffprobe=subprocess.run(["ffprobe","-v","error","-show_entries",
|
||||
"format=duration,size:stream=codec_name,width,height",
|
||||
"-of","json",str(OUT)],capture_output=True,text=True,check=True)
|
||||
print("FFPROBE",ffprobe.stdout,flush=True)
|
||||
assert OUT.stat().st_size>1000000, "Suspiciously small encoded video"
|
||||
|
||||
if __name__=="__main__":
|
||||
main()
|
||||
@@ -1,78 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Migrate branch arms: + cond -> N. cond (params + `name` unchanged)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SKIP_DIRS = {"target", ".git", "node_modules"}
|
||||
|
||||
PARAM_LINE = re.compile(r"^(\s{4,})\+ `([^`]+)`(=.*)?\s*$")
|
||||
ORDERED = re.compile(r"^(\s*)(\d+)\.\s+(.*)$")
|
||||
PLUS_BRANCH = re.compile(r"^(\s*)\+ (.+)$")
|
||||
|
||||
|
||||
def migrate_text(text: str) -> str:
|
||||
lines = text.splitlines(keepends=True)
|
||||
out: list[str] = []
|
||||
arm = 0
|
||||
for line in lines:
|
||||
raw = line.rstrip("\n\r")
|
||||
end = line[len(raw) :]
|
||||
if not raw.strip():
|
||||
arm = 0
|
||||
out.append(line)
|
||||
continue
|
||||
if PARAM_LINE.match(raw):
|
||||
arm = 0
|
||||
out.append(line)
|
||||
continue
|
||||
m = PLUS_BRANCH.match(raw)
|
||||
if m:
|
||||
arm += 1
|
||||
indent, rest = m.groups()
|
||||
out.append(f"{indent}{arm}. {rest}{end}")
|
||||
continue
|
||||
om = ORDERED.match(raw)
|
||||
if om:
|
||||
arm = int(om.group(2))
|
||||
out.append(line)
|
||||
continue
|
||||
stripped = raw.lstrip()
|
||||
indent = raw[: len(raw) - len(stripped)]
|
||||
if indent == 0 and (
|
||||
stripped.startswith("#")
|
||||
or stripped.startswith(">")
|
||||
or (stripped.startswith("*") and stripped.endswith("*"))
|
||||
or stripped.startswith("`")
|
||||
or stripped.startswith("|")
|
||||
or stripped.startswith("---")
|
||||
):
|
||||
arm = 0
|
||||
out.append(line)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def should_skip(path: Path) -> bool:
|
||||
return any(part in SKIP_DIRS for part in path.parts)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
changed = 0
|
||||
for path in sorted(ROOT.rglob("*.mq.md")):
|
||||
if should_skip(path):
|
||||
continue
|
||||
text = path.read_text(encoding="utf-8")
|
||||
new_text = migrate_text(text)
|
||||
if new_text != text:
|
||||
path.write_text(new_text, encoding="utf-8")
|
||||
print(path.relative_to(ROOT))
|
||||
changed += 1
|
||||
print(f"migrated {changed} files")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,61 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-shot migrate v0.2: params + `name`, foreach [`i`](`xs`)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SKIP_DIRS = {"man-test", "target", ".git", "node_modules"}
|
||||
|
||||
PARAM_RE = re.compile(
|
||||
r"^(\s+)- ([A-Za-z_\u4e00-\u9fff][A-Za-z0-9_\u4e00-\u9fff]*)(=(.*))?\s*$"
|
||||
)
|
||||
FOREACH_RE = re.compile(r"^(\s*)- \[([^\]]+)\]\(([^)]+)\)\s*$")
|
||||
|
||||
|
||||
def wrap_id(name: str) -> str:
|
||||
name = name.strip()
|
||||
if name.startswith("`") and name.endswith("`"):
|
||||
return name
|
||||
return f"`{name}`"
|
||||
|
||||
|
||||
def migrate_line(line: str) -> str:
|
||||
m = FOREACH_RE.match(line)
|
||||
if m:
|
||||
indent, item, coll = m.groups()
|
||||
return f"{indent}- [{wrap_id(item)}]({wrap_id(coll)})\n"
|
||||
m = PARAM_RE.match(line)
|
||||
if m:
|
||||
indent, name, _, default = m.groups()
|
||||
if default is not None:
|
||||
return f"{indent}+ {wrap_id(name)}={default.rstrip()}\n"
|
||||
return f"{indent}+ {wrap_id(name)}\n"
|
||||
return line
|
||||
|
||||
|
||||
def should_skip(path: Path) -> bool:
|
||||
return any(part in SKIP_DIRS for part in path.parts)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
changed = 0
|
||||
for path in sorted(ROOT.rglob("*.mq.md")):
|
||||
if should_skip(path):
|
||||
continue
|
||||
text = path.read_text(encoding="utf-8")
|
||||
lines = text.splitlines(keepends=True)
|
||||
out = [migrate_line(ln) for ln in lines]
|
||||
new_text = "".join(out)
|
||||
if new_text != text:
|
||||
path.write_text(new_text, encoding="utf-8")
|
||||
print(path.relative_to(ROOT))
|
||||
changed += 1
|
||||
print(f"migrated {changed} files")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,45 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# O4 — style gate: flag json.set dict chains and mixed EN/ZH API hints in .mq.md.
|
||||
# Exit 0 when clean; 1 when findings (unless MQ_STYLE_LINT_SOFT=1).
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
TARGETS=("$@")
|
||||
if [[ ${#TARGETS[@]} -eq 0 ]]; then
|
||||
TARGETS=(ext/ai/sandbox.mq.md ext/ai/policies examples/agent-sandbox-okf)
|
||||
fi
|
||||
|
||||
fail=0
|
||||
findings=0
|
||||
|
||||
scan_file() {
|
||||
local f="$1"
|
||||
[[ -f "$f" ]] || return 0
|
||||
# Long json.set pipelines (3+ consecutive) — style bug per marqdo-dev.
|
||||
if awk '
|
||||
/json\.set/ { c++; if (c >= 3) { found=1 } next }
|
||||
{ c=0 }
|
||||
END { exit found ? 0 : 1 }
|
||||
' "$f"; then
|
||||
echo "STYLE json.set-chain: $f" >&2
|
||||
findings=$((findings + 1))
|
||||
fail=1
|
||||
fi
|
||||
# Same file imports both EN agent and ZH 智能体 (or web/网页) — mixed surface.
|
||||
if grep -qE 'import[[:space:]]+agent:|import[[:space:]]+web:' "$f" \
|
||||
&& grep -qE '导入[[:space:]]+(智能体|网页):' "$f"; then
|
||||
echo "STYLE mixed-EN/ZH-import: $f" >&2
|
||||
findings=$((findings + 1))
|
||||
fail=1
|
||||
fi
|
||||
}
|
||||
|
||||
while IFS= read -r -d '' f; do
|
||||
scan_file "$f"
|
||||
done < <(find "${TARGETS[@]}" -type f -name '*.mq.md' -print0 2>/dev/null)
|
||||
|
||||
echo "mq-style-lint: findings=$findings"
|
||||
if [[ "${MQ_STYLE_LINT_SOFT:-}" == "1" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
exit "$fail"
|
||||
@@ -1,58 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# O5 — offline standing / policy rewrite hint (GEPA-like, products stay repo files).
|
||||
# Does NOT change the runtime agent path. Reads harness failure log + current files,
|
||||
# writes a suggested patch under .marqdo/optimize/ for human review.
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
LOG="${1:-}"
|
||||
STANDING="${2:-ext/ai/agent.mq.md}"
|
||||
POLICY="${3:-ext/ai/policies/step-route.mq.md}"
|
||||
OUT_DIR="${OUT_DIR:-.marqdo/optimize}"
|
||||
mkdir -p "$OUT_DIR"
|
||||
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
REPORT="$OUT_DIR/standing-policy-$STAMP.md"
|
||||
|
||||
{
|
||||
echo "# Offline standing / policy optimize suggestion"
|
||||
echo
|
||||
echo "Generated: $STAMP"
|
||||
echo
|
||||
echo "This is a **review artifact**, not an automatic runtime rewrite."
|
||||
echo "Strong models may rewrite \`standing\` / \`policies/*.mq.md\` offline;"
|
||||
echo "commit only after harness green."
|
||||
echo
|
||||
echo "## Inputs"
|
||||
echo
|
||||
echo "- standing source: \`$STANDING\`"
|
||||
echo "- policy source: \`$POLICY\`"
|
||||
if [[ -n "$LOG" && -f "$LOG" ]]; then
|
||||
echo "- harness log: \`$LOG\`"
|
||||
echo
|
||||
echo "## Harness failure excerpt"
|
||||
echo
|
||||
echo '```'
|
||||
tail -n 80 "$LOG" || true
|
||||
echo '```'
|
||||
else
|
||||
echo "- harness log: _(none — pass path as \$1)_"
|
||||
fi
|
||||
echo
|
||||
echo "## Current policy table (copy)"
|
||||
echo
|
||||
if [[ -f "$POLICY" ]]; then
|
||||
echo '```markdown'
|
||||
cat "$POLICY"
|
||||
echo '```'
|
||||
else
|
||||
echo "_missing $POLICY_"
|
||||
fi
|
||||
echo
|
||||
echo "## Suggested next edits"
|
||||
echo
|
||||
echo "1. Keep step-class → backend as a **GFM table** (no json glue)."
|
||||
echo "2. Quarantine failing skills (\`status: quarantine\`) before promoting again."
|
||||
echo "3. Re-run \`scripts/agent-harness.sh\` and confirm Skill Lift summary."
|
||||
} > "$REPORT"
|
||||
|
||||
echo "wrote $REPORT"
|
||||
@@ -1,263 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build a signed Ubuntu *source* package for Launchpad PPA.
|
||||
# Usage: ./scripts/ppa-build-source.sh [series]
|
||||
# Example: ./scripts/ppa-build-source.sh noble
|
||||
#
|
||||
# Launchpad builders have no network and noble's cargo (1.75) cannot read
|
||||
# Cargo.lock v4. For a *new* upstream SemVer this script:
|
||||
# 1) cargo vendor → vendor/
|
||||
# 2) installs a modern Rust toolchain into third_party/rust (cached)
|
||||
# 3) packs both into the .orig.tar.xz for offline debuild on Launchpad
|
||||
#
|
||||
# For debian-only bumps (same upstream X.Y.Z already in the PPA):
|
||||
# - Reuse the published marqdo_X.Y.Z.orig.tar.xz (never rewrite it)
|
||||
# - debuild -S -sd (do not re-upload .orig)
|
||||
# Override: MARQDO_PPA_FORCE_ORIG=1 rebuilds orig; MARQDO_PPA_ORIG=/path uses that file.
|
||||
set -euo pipefail
|
||||
|
||||
SERIES="${1:-noble}"
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
# File authoring uses the interpreter being released, including in package staging.
|
||||
MARQDO_TOOL="${MARQDO_BIN:-$ROOT/target/debug/marqdo}"
|
||||
if [ ! -x "$MARQDO_TOOL" ]; then
|
||||
MARQDO_TOOL="$ROOT/target/release/marqdo"
|
||||
fi
|
||||
if [ ! -x "$MARQDO_TOOL" ]; then
|
||||
MARQDO_TOOL="$(command -v marqdo || true)"
|
||||
fi
|
||||
if [ -z "$MARQDO_TOOL" ] || [ ! -x "$MARQDO_TOOL" ]; then
|
||||
echo "error: build Marqdo or set MARQDO_BIN before packaging" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
need() { command -v "$1" >/dev/null || { echo "missing tool: $1 (sudo apt install $2)"; exit 1; }; }
|
||||
need cargo cargo
|
||||
need debuild devscripts
|
||||
need dpkg-parsechangelog dpkg-dev
|
||||
need curl curl
|
||||
need tar tar
|
||||
need xz xz-utils
|
||||
|
||||
# /tmp is often a small tmpfs; vendor + Rust extract exceed quota. Prefer disk.
|
||||
if [ -z "${TMPDIR:-}" ] || [ "$TMPDIR" = /tmp ] || [ "$TMPDIR" = /var/tmp ]; then
|
||||
TMPDIR="${HOME}/.cache/marqdo-ppa/work"
|
||||
fi
|
||||
mkdir -p "$TMPDIR"
|
||||
export TMPDIR
|
||||
|
||||
# The callable handbook owns metadata parsing; stdout contains the exact text.
|
||||
VER="$("$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" upstream \
|
||||
--require-ok --effects fs.read --fs-root "$ROOT")"
|
||||
DEB_VER="$("$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" debian_version \
|
||||
"series=\"$SERIES\"" --require-ok --effects fs.read --fs-root "$ROOT")"
|
||||
PKG_ROOT="${TMPDIR}/marqdo-ppa/${VER}"
|
||||
BUILD_AREA="${ROOT}/../build-area"
|
||||
GPG_KEY="${MARQDO_PPA_GPG_KEY:-505943294D04C803}"
|
||||
RUST_VER="${MARQDO_PPA_RUST_VERSION:-1.85.0}"
|
||||
RUST_TRIPLE="${MARQDO_PPA_RUST_TRIPLE:-x86_64-unknown-linux-gnu}"
|
||||
RUST_NAME="rust-${RUST_VER}-${RUST_TRIPLE}"
|
||||
RUST_CACHE="${MARQDO_PPA_RUST_CACHE:-${HOME}/.cache/marqdo-ppa}"
|
||||
RUST_TARBALL="${RUST_CACHE}/${RUST_NAME}.tar.gz"
|
||||
RUST_URL="${MARQDO_PPA_RUST_URL:-https://static.rust-lang.org/dist/${RUST_NAME}.tar.gz}"
|
||||
PPA_OWNER="${MARQDO_PPA_OWNER:-cflmy}"
|
||||
PPA_NAME="${MARQDO_PPA_NAME:-marqdo}"
|
||||
ORIG_NAME="marqdo_${VER}.orig.tar.xz"
|
||||
FORCE_ORIG="${MARQDO_PPA_FORCE_ORIG:-0}"
|
||||
|
||||
resolve_existing_orig() {
|
||||
local candidate
|
||||
if [ -n "${MARQDO_PPA_ORIG:-}" ]; then
|
||||
candidate="${MARQDO_PPA_ORIG}"
|
||||
if [ ! -f "$candidate" ]; then
|
||||
echo "error: MARQDO_PPA_ORIG not a file: $candidate" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "$candidate"
|
||||
return 0
|
||||
fi
|
||||
for candidate in \
|
||||
"$BUILD_AREA/$ORIG_NAME" \
|
||||
"$RUST_CACHE/$ORIG_NAME" \
|
||||
"$HOME/.cache/marqdo-ppa/$ORIG_NAME"
|
||||
do
|
||||
if [ -f "$candidate" ]; then
|
||||
echo "$candidate"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
download_published_orig() {
|
||||
local dest="$1"
|
||||
local urls=(
|
||||
"https://ppa.launchpadcontent.net/${PPA_OWNER}/${PPA_NAME}/ubuntu/pool/main/m/marqdo/${ORIG_NAME}"
|
||||
"https://launchpad.net/~${PPA_OWNER}/+archive/ubuntu/${PPA_NAME}/+files/${ORIG_NAME}"
|
||||
)
|
||||
local url
|
||||
mkdir -p "$(dirname "$dest")"
|
||||
for url in "${urls[@]}"; do
|
||||
echo " trying ${url}"
|
||||
if curl -fL --retry 3 --retry-delay 2 --connect-timeout 30 \
|
||||
-o "${dest}.partial" "$url"; then
|
||||
mv "${dest}.partial" "$dest"
|
||||
return 0
|
||||
fi
|
||||
rm -f "${dest}.partial"
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
echo "==> upstream ${VER} → debian ${DEB_VER} (${SERIES})"
|
||||
rm -rf "$PKG_ROOT"
|
||||
mkdir -p "$PKG_ROOT" "$BUILD_AREA" "$RUST_CACHE"
|
||||
|
||||
REUSE_ORIG=0
|
||||
ORIG_PUBLISHED=0
|
||||
ORIG_SRC=""
|
||||
if [ "$FORCE_ORIG" != "1" ]; then
|
||||
# Prefer the bytes already accepted by Launchpad (rewriting .orig is rejected).
|
||||
if download_published_orig "$RUST_CACHE/$ORIG_NAME"; then
|
||||
ORIG_SRC="$RUST_CACHE/$ORIG_NAME"
|
||||
ORIG_PUBLISHED=1
|
||||
elif ORIG_SRC="$(resolve_existing_orig)"; then
|
||||
echo "warning: could not fetch PPA ${ORIG_NAME}; using local ${ORIG_SRC}" >&2
|
||||
echo "warning: if its sha256 differs from the archive, Launchpad will reject the upload" >&2
|
||||
fi
|
||||
if [ -n "$ORIG_SRC" ]; then
|
||||
REUSE_ORIG=1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$REUSE_ORIG" -eq 1 ]; then
|
||||
echo "==> reusing published ${ORIG_NAME} (debian-only bump; do not rewrite orig)"
|
||||
echo " source: ${ORIG_SRC}"
|
||||
sha256sum "$ORIG_SRC"
|
||||
# Local fallback may already be build-area/ORIG_NAME — do not cp onto itself.
|
||||
if [ "$(realpath "$ORIG_SRC")" != "$(realpath "$BUILD_AREA/$ORIG_NAME" 2>/dev/null || echo "")" ]; then
|
||||
cp -f "$ORIG_SRC" "$BUILD_AREA/$ORIG_NAME"
|
||||
fi
|
||||
# Unpack orig (top dir is usually ${VER} or marqdo-${VER})
|
||||
tar -xJf "$BUILD_AREA/$ORIG_NAME" -C "$(dirname "$PKG_ROOT")"
|
||||
if [ ! -d "$PKG_ROOT" ]; then
|
||||
# Some tarballs use marqdo-${VER}/
|
||||
if [ -d "$(dirname "$PKG_ROOT")/marqdo-${VER}" ]; then
|
||||
mv "$(dirname "$PKG_ROOT")/marqdo-${VER}" "$PKG_ROOT"
|
||||
else
|
||||
echo "error: unpack did not create ${PKG_ROOT}" >&2
|
||||
tar -tJf "$BUILD_AREA/$ORIG_NAME" | head -5 >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
rsync -a "$ROOT/debian/" "$PKG_ROOT/debian/"
|
||||
else
|
||||
echo "==> building fresh ${ORIG_NAME} (new upstream or MARQDO_PPA_FORCE_ORIG=1)"
|
||||
# Clean export of sources (no target/, .git)
|
||||
if command -v git >/dev/null && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
git archive --format=tar HEAD | tar -x -C "$PKG_ROOT"
|
||||
else
|
||||
rsync -a --exclude target --exclude .git --exclude build-area "$ROOT"/ "$PKG_ROOT"/
|
||||
fi
|
||||
rsync -a "$ROOT/debian/" "$PKG_ROOT/debian/"
|
||||
|
||||
cd "$PKG_ROOT"
|
||||
echo "==> cargo vendor (Launchpad offline)"
|
||||
mkdir -p .cargo
|
||||
cargo vendor --locked vendor
|
||||
"$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" vendor_config \
|
||||
--require-ok --effects fs.write --fs-root "$PKG_ROOT" --json
|
||||
# dh_clean removes *.orig; drop those paths from vendor checksums so a
|
||||
# stray clean (or older rules) cannot break `cargo --offline` on Launchpad.
|
||||
"$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" sanitize_vendor \
|
||||
--require-ok --effects fs.write --fs-root "$PKG_ROOT" --json
|
||||
|
||||
echo "==> bundle Rust ${RUST_VER} (${RUST_TRIPLE}) for Launchpad"
|
||||
if [ ! -f "$RUST_TARBALL" ]; then
|
||||
echo " downloading ${RUST_URL}"
|
||||
curl -fL --retry 3 --retry-delay 2 -o "${RUST_TARBALL}.partial" "$RUST_URL"
|
||||
mv "${RUST_TARBALL}.partial" "$RUST_TARBALL"
|
||||
else
|
||||
echo " cache hit ${RUST_TARBALL}"
|
||||
fi
|
||||
rm -rf third_party/rust
|
||||
mkdir -p third_party
|
||||
RUST_EXTRACT="$(mktemp -d "${TMPDIR:-/tmp}/marqdo-rust.XXXXXX")"
|
||||
# Always drop the ~1.5G extract dir, even on failure (tmpfs fills up otherwise).
|
||||
trap 'rm -rf "$RUST_EXTRACT"' EXIT
|
||||
tar -xzf "$RUST_TARBALL" -C "$RUST_EXTRACT"
|
||||
INSTALL_SH="$(find "$RUST_EXTRACT" -maxdepth 2 -name install.sh | head -1)"
|
||||
if [ -z "$INSTALL_SH" ]; then
|
||||
echo "error: install.sh not found in ${RUST_TARBALL}" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Launchpad builds need only rustc + cargo + rust-std (debian/rules PATH).
|
||||
# install.sh's --without is a *single* comma-separated valopt; repeating
|
||||
# --without=… keeps only the last flag, so rust-docs still installed and
|
||||
# blew /tmp quota. Prefer explicit --components= instead.
|
||||
bash "$INSTALL_SH" \
|
||||
--prefix="$PKG_ROOT/third_party/rust" \
|
||||
--components="rustc,cargo,rust-std-${RUST_TRIPLE}" \
|
||||
--disable-ldconfig
|
||||
# Belt: docs must never ship in .orig (even if component list drifts).
|
||||
rm -rf "$PKG_ROOT/third_party/rust/share/doc"
|
||||
rm -rf "$RUST_EXTRACT"
|
||||
trap - EXIT
|
||||
"$PKG_ROOT/third_party/rust/bin/rustc" --version
|
||||
"$PKG_ROOT/third_party/rust/bin/cargo" --version
|
||||
du -sh "$PKG_ROOT/third_party/rust"
|
||||
|
||||
cd "$(dirname "$PKG_ROOT")"
|
||||
echo "==> packing ${ORIG_NAME} (vendor + third_party/rust)"
|
||||
rm -f "$BUILD_AREA/$ORIG_NAME"
|
||||
tar -cJf "$BUILD_AREA/$ORIG_NAME" \
|
||||
--exclude=debian \
|
||||
-C "$(dirname "$PKG_ROOT")" "$(basename "$PKG_ROOT")"
|
||||
fi
|
||||
|
||||
cd "$PKG_ROOT"
|
||||
"$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" changelog \
|
||||
"version=\"$DEB_VER\"" "series=\"$SERIES\"" \
|
||||
--require-ok --effects fs.write --fs-root "$PKG_ROOT" --json
|
||||
|
||||
ln -sfn "$BUILD_AREA/$ORIG_NAME" "$(dirname "$PKG_ROOT")/$ORIG_NAME"
|
||||
ls -lh "$BUILD_AREA/$ORIG_NAME"
|
||||
|
||||
cd "$PKG_ROOT"
|
||||
# Local cache reuse does not prove Launchpad already has the orig archive.
|
||||
# Include its unchanged bytes until the published download succeeds.
|
||||
if [ "$ORIG_PUBLISHED" -eq 1 ]; then
|
||||
DEBUILD_ORIG_FLAG="-sd"
|
||||
echo "==> debuild -S ${DEBUILD_ORIG_FLAG} (key ${GPG_KEY}; not re-uploading .orig)"
|
||||
else
|
||||
DEBUILD_ORIG_FLAG="-sa"
|
||||
echo "==> debuild -S ${DEBUILD_ORIG_FLAG} (key ${GPG_KEY}; including new .orig)"
|
||||
fi
|
||||
debuild -S ${DEBUILD_ORIG_FLAG} -k"${GPG_KEY}" -d
|
||||
|
||||
# debuild writes next to package parent (/tmp/marqdo-ppa/); collect into build-area
|
||||
mkdir -p "$BUILD_AREA"
|
||||
shopt -s nullglob
|
||||
for f in ../marqdo_"${DEB_VER}"* ../marqdo_"${VER}".orig.tar.*; do
|
||||
[ -e "$f" ] || continue
|
||||
if [ "$(realpath -m "$f")" = "$(realpath -m "$BUILD_AREA/$(basename "$f")")" ]; then
|
||||
continue
|
||||
fi
|
||||
cp -f "$f" "$BUILD_AREA/"
|
||||
done
|
||||
shopt -u nullglob
|
||||
|
||||
echo "==> artifacts in $BUILD_AREA:"
|
||||
ls -la "$BUILD_AREA"/marqdo_"${DEB_VER}"* "$BUILD_AREA"/marqdo_"${VER}".orig.tar.* 2>/dev/null || true
|
||||
if [ "$REUSE_ORIG" -eq 1 ]; then
|
||||
echo " sha256 of reused orig (must match PPA):"
|
||||
sha256sum "$BUILD_AREA/$ORIG_NAME"
|
||||
fi
|
||||
CHANGES="$BUILD_AREA/marqdo_${DEB_VER}_source.changes"
|
||||
if [ -f "$CHANGES" ]; then
|
||||
echo
|
||||
echo "Upload with:"
|
||||
echo " dput ppa:cflmy/marqdo $CHANGES"
|
||||
echo " # or: ./scripts/ppa-ship.sh ${SERIES}"
|
||||
fi
|
||||
@@ -1,111 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# One-shot: install packaging tools → build signed source package → dput to Launchpad PPA.
|
||||
#
|
||||
# Run in YOUR terminal (needs sudo for apt + GPG passphrase for signing):
|
||||
# ./scripts/ppa-ship.sh # default series: noble
|
||||
# ./scripts/ppa-ship.sh resolute # match host /etc/os-release
|
||||
# ./scripts/ppa-ship.sh noble --no-upload
|
||||
# sudo ./scripts/ppa-ship.sh noble # also OK — build/sign/upload drop back to $SUDO_USER
|
||||
#
|
||||
# PPA: ppa:cflmy/marqdo | key: 505943294D04C803
|
||||
set -euo pipefail
|
||||
|
||||
SERIES="${1:-noble}"
|
||||
NO_UPLOAD=0
|
||||
for arg in "${@:2}"; do
|
||||
case "$arg" in
|
||||
--no-upload|-n) NO_UPLOAD=1 ;;
|
||||
*) echo "unknown arg: $arg" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
# Never cargo/debuild/dput as root — GPG lives in the human user's ~/.gnupg
|
||||
if [ "$(id -u)" -eq 0 ]; then
|
||||
if [ -z "${SUDO_USER:-}" ] || [ "$SUDO_USER" = root ]; then
|
||||
echo "error: run as a normal user, or: sudo -u \$USER ./scripts/ppa-ship.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
REAL_USER="$SUDO_USER"
|
||||
REAL_HOME="$(getent passwd "$REAL_USER" | cut -d: -f6)"
|
||||
echo "==> root detected; apt as root, build/upload as ${REAL_USER}"
|
||||
run_user() {
|
||||
local upath="${REAL_HOME}/.cargo/bin:/usr/local/bin:/usr/bin:/bin"
|
||||
sudo -u "$REAL_USER" -H --preserve-env=MARQDO_PPA_GPG_KEY \
|
||||
env HOME="$REAL_HOME" PATH="$upath" "$@"
|
||||
}
|
||||
APT=(apt-get)
|
||||
else
|
||||
REAL_USER="$(id -un)"
|
||||
REAL_HOME="$HOME"
|
||||
run_user() { "$@"; }
|
||||
APT=(sudo apt-get)
|
||||
fi
|
||||
|
||||
PPA_TARGET="${MARQDO_PPA:-ppa:cflmy/marqdo}"
|
||||
PKGS=(build-essential debhelper devscripts dput lintian
|
||||
dpkg-dev quilt cargo rustc pkg-config libssl-dev ca-certificates
|
||||
xz-utils)
|
||||
|
||||
need_apt=0
|
||||
for bin in debuild dput dpkg-parsechangelog cargo gpg; do
|
||||
if ! command -v "$bin" >/dev/null 2>&1; then
|
||||
need_apt=1
|
||||
break
|
||||
fi
|
||||
done
|
||||
# dh_auto_* comes from debhelper even if debuild exists from a partial install
|
||||
if ! dpkg -s debhelper >/dev/null 2>&1; then
|
||||
need_apt=1
|
||||
fi
|
||||
|
||||
if [ "$need_apt" -eq 1 ]; then
|
||||
echo "==> installing packaging toolchain (sudo)…"
|
||||
"${APT[@]}" update -qq
|
||||
DEBIAN_FRONTEND=noninteractive "${APT[@]}" install -y "${PKGS[@]}"
|
||||
else
|
||||
echo "==> packaging tools already present"
|
||||
fi
|
||||
|
||||
echo "==> building source package for series=${SERIES}"
|
||||
run_user bash "$ROOT/scripts/ppa-build-source.sh" "$SERIES"
|
||||
|
||||
# The native handbook selects the exact current-version artifact.
|
||||
MARQDO_TOOL="${MARQDO_BIN:-$ROOT/target/debug/marqdo}"
|
||||
if [ ! -x "$MARQDO_TOOL" ]; then MARQDO_TOOL="$ROOT/target/release/marqdo"; fi
|
||||
if [ ! -x "$MARQDO_TOOL" ]; then MARQDO_TOOL="$(command -v marqdo || true)"; fi
|
||||
if [ -z "$MARQDO_TOOL" ] || [ ! -x "$MARQDO_TOOL" ]; then
|
||||
echo "error: build Marqdo or set MARQDO_BIN before packaging" >&2
|
||||
exit 1
|
||||
fi
|
||||
DEB_VER="$(run_user "$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" debian_version \
|
||||
"series=\"$SERIES\"" --require-ok --effects fs.read --fs-root "$ROOT")"
|
||||
BUILD_AREA="$(cd "$ROOT/.." && pwd)/build-area"
|
||||
CHANGES="$BUILD_AREA/marqdo_${DEB_VER}_source.changes"
|
||||
if [ ! -f "$CHANGES" ]; then
|
||||
echo "error: expected source artifact is missing: $CHANGES" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "==> artifact: $CHANGES"
|
||||
if command -v lintian >/dev/null 2>&1; then
|
||||
echo "==> lintian (non-fatal)"
|
||||
run_user lintian -i "$CHANGES" || true
|
||||
fi
|
||||
|
||||
if [ "$NO_UPLOAD" -eq 1 ]; then
|
||||
echo
|
||||
echo "Skip upload (--no-upload). When ready:"
|
||||
echo " dput ${PPA_TARGET} ${CHANGES}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "==> dput ${PPA_TARGET}"
|
||||
run_user dput --unchecked "${PPA_TARGET}" "$CHANGES"
|
||||
|
||||
echo
|
||||
echo "Done. Watch builds:"
|
||||
echo " https://launchpad.net/~cflmy/+archive/ubuntu/marqdo/+builds"
|
||||
echo "Enable the Ubuntu series (${SERIES}) in PPA → Change details if Launchpad rejects the upload."
|
||||
@@ -1,170 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Create a GitHub release from Cargo.toml version and upload Windows binaries."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
REPO = "cflmy/marqdo"
|
||||
|
||||
|
||||
def crate_version() -> str:
|
||||
text = Path("Cargo.toml").read_text(encoding="utf-8")
|
||||
m = re.search(r'(?m)^version\s*=\s*"([^"]+)"', text)
|
||||
if not m:
|
||||
raise SystemExit("version not found in Cargo.toml")
|
||||
return m.group(1)
|
||||
|
||||
|
||||
def git_token() -> str:
|
||||
proc = subprocess.run(
|
||||
["git", "credential", "fill"],
|
||||
input="protocol=https\nhost=github.com\n\n",
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
for line in proc.stdout.splitlines():
|
||||
if line.startswith("password="):
|
||||
return line[len("password=") :]
|
||||
raise SystemExit("no github password from git credential fill")
|
||||
|
||||
|
||||
def api(method: str, url: str, token: str, data: bytes | None = None, content_type: str | None = None):
|
||||
req = urllib.request.Request(url, data=data, method=method)
|
||||
req.add_header("Accept", "application/vnd.github+json")
|
||||
req.add_header("Authorization", f"Bearer {token}")
|
||||
req.add_header("X-GitHub-Api-Version", "2022-11-28")
|
||||
req.add_header("User-Agent", "marqdo-release-script")
|
||||
if content_type:
|
||||
req.add_header("Content-Type", content_type)
|
||||
try:
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
body = resp.read()
|
||||
return resp.status, json.loads(body.decode()) if body else {}
|
||||
except urllib.error.HTTPError as e:
|
||||
err = e.read().decode("utf-8", errors="replace")
|
||||
raise SystemExit(f"HTTP {e.code} {url}: {err}") from e
|
||||
|
||||
|
||||
def find_assets(stem: str, ver: str) -> list[Path]:
|
||||
names = [
|
||||
f"{stem}.exe",
|
||||
f"{stem}.zip",
|
||||
f"marqdo-{ver}-stdlib.zip",
|
||||
]
|
||||
assets: list[Path] = []
|
||||
for name in names:
|
||||
found = None
|
||||
for base in (Path("dist"), Path("target/dist")):
|
||||
p = base / name
|
||||
if p.exists():
|
||||
found = p
|
||||
break
|
||||
if not found:
|
||||
raise SystemExit(f"missing asset: {name} under dist/ or target/dist/")
|
||||
assets.append(found)
|
||||
return assets
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ver = crate_version()
|
||||
tag = f"v{ver}"
|
||||
stem = f"marqdo-{ver}-x86_64-pc-windows-msvc"
|
||||
assets = find_assets(stem, ver)
|
||||
|
||||
notes = f"""## Marqdo {tag}
|
||||
|
||||
### Downloads
|
||||
|
||||
| Asset | Contents |
|
||||
|-------|----------|
|
||||
| `{stem}.exe` | **Executable only** — does **not** include the standard library |
|
||||
| `{stem}.zip` | **Recommended**: `marqdo.exe` + `lib/` (keep them together; `lib/` resolves next to the binary) |
|
||||
| `marqdo-{ver}-stdlib.zip` | Standard library only (`lib/*.mq.md`) — unpack next to an existing exe, or set `MARQDO_LIB` |
|
||||
|
||||
> **Important:** the standalone `.exe` does **not** ship `lib/`. Importing `lib/text.mq.md` etc. needs the bundle zip or the stdlib zip.
|
||||
|
||||
### Highlights
|
||||
- **Code as docs as knowledge**: `.mq.md` is narrative + program in one tree
|
||||
- **`marqdo debug`**: dedicated debugger; view stays docs-only
|
||||
- **View**: function outline + search
|
||||
- Roadmap: deeper **OKF**-aligned catalog for human–AI knowledge bases
|
||||
|
||||
```text
|
||||
marqdo --version
|
||||
marqdo run public/00-welcome.mq.md
|
||||
marqdo view public
|
||||
marqdo debug public
|
||||
```
|
||||
"""
|
||||
|
||||
token = git_token()
|
||||
|
||||
existing = None
|
||||
try:
|
||||
_, existing = api(
|
||||
"GET",
|
||||
f"https://api.github.com/repos/{REPO}/releases/tags/{tag}",
|
||||
token,
|
||||
)
|
||||
except SystemExit as e:
|
||||
if "404" not in str(e):
|
||||
raise
|
||||
|
||||
if existing:
|
||||
release_id = existing["id"]
|
||||
upload_url = existing["upload_url"].split("{", 1)[0]
|
||||
print(f"reuse release id={release_id}")
|
||||
else:
|
||||
payload = json.dumps(
|
||||
{
|
||||
"tag_name": tag,
|
||||
"name": tag,
|
||||
"body": notes,
|
||||
"draft": False,
|
||||
"prerelease": False,
|
||||
}
|
||||
).encode("utf-8")
|
||||
_, created = api(
|
||||
"POST",
|
||||
f"https://api.github.com/repos/{REPO}/releases",
|
||||
token,
|
||||
data=payload,
|
||||
content_type="application/json",
|
||||
)
|
||||
release_id = created["id"]
|
||||
upload_url = created["upload_url"].split("{", 1)[0]
|
||||
print(f"created release id={release_id}")
|
||||
|
||||
_, rel = api(
|
||||
"GET",
|
||||
f"https://api.github.com/repos/{REPO}/releases/{release_id}",
|
||||
token,
|
||||
)
|
||||
want = {p.name for p in assets}
|
||||
for asset in rel.get("assets", []):
|
||||
if asset["name"] in want:
|
||||
api(
|
||||
"DELETE",
|
||||
f"https://api.github.com/repos/{REPO}/releases/assets/{asset['id']}",
|
||||
token,
|
||||
)
|
||||
print(f"deleted old asset {asset['name']}")
|
||||
|
||||
for path in assets:
|
||||
data = path.read_bytes()
|
||||
url = f"{upload_url}?name={path.name}"
|
||||
ctype = "application/zip" if path.suffix == ".zip" else "application/octet-stream"
|
||||
_, uploaded = api("POST", url, token, data=data, content_type=ctype)
|
||||
print(f"uploaded {path.name} -> {uploaded.get('browser_download_url')}")
|
||||
|
||||
print(f"OK https://github.com/{REPO}/releases/tag/{tag}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,208 +0,0 @@
|
||||
# Build all Marqdo v0.1.2+ release assets and optionally upload to GitHub Releases.
|
||||
# Usage (repo root):
|
||||
# powershell -File ./scripts/release-full.ps1
|
||||
# powershell -File ./scripts/release-full.ps1 -Tag v0.1.2 -Upload
|
||||
# powershell -File ./scripts/release-full.ps1 -SkipPublic
|
||||
param(
|
||||
[string]$Tag = "",
|
||||
[switch]$Upload,
|
||||
[switch]$DeployPages,
|
||||
[switch]$SkipPublic,
|
||||
[switch]$SkipVsix
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$Root = Split-Path $PSScriptRoot -Parent
|
||||
Set-Location $Root
|
||||
|
||||
function Invoke-Git {
|
||||
param([Parameter(ValueFromRemainingArguments = $true)][string[]]$GitArgs)
|
||||
$prev = $ErrorActionPreference
|
||||
$ErrorActionPreference = "Continue"
|
||||
& git @GitArgs 2>&1 | Out-Null
|
||||
$code = $LASTEXITCODE
|
||||
$ErrorActionPreference = $prev
|
||||
if ($code -ne 0) { throw "git $($GitArgs -join ' ') failed (exit $code)" }
|
||||
}
|
||||
|
||||
if (-not $Tag) {
|
||||
$Tag = (Select-String -Path Cargo.toml -Pattern '^version\s*=\s*"([^"]+)"').Matches.Groups[1].Value
|
||||
$Tag = "v$Tag"
|
||||
}
|
||||
$ver = $Tag.TrimStart("v")
|
||||
$target = "x86_64-pc-windows-msvc"
|
||||
$dist = Join-Path $Root "dist"
|
||||
New-Item -ItemType Directory -Force -Path $dist | Out-Null
|
||||
|
||||
$exeName = "marqdo-$ver-$target.exe"
|
||||
$zipName = "marqdo-$ver-$target.zip"
|
||||
$stdlibName = "marqdo-$ver-stdlib.zip"
|
||||
$sourceName = "marqdo-$ver-source.zip"
|
||||
$vsixName = "marqdo-$ver.vsix"
|
||||
$publicName = "marqdo-$ver-public.zip"
|
||||
|
||||
Write-Host "=== Marqdo release $Tag ==="
|
||||
|
||||
Write-Host "[1/6] cargo build --release"
|
||||
cargo build --release -q
|
||||
|
||||
Write-Host "[2/6] binary + bundle + stdlib zips"
|
||||
$exePath = Join-Path $dist $exeName
|
||||
Copy-Item ".\target\release\marqdo.exe" $exePath -Force
|
||||
|
||||
$stage = Join-Path $dist "stage-bundle"
|
||||
if (Test-Path $stage) { Remove-Item $stage -Recurse -Force }
|
||||
New-Item -ItemType Directory -Force -Path $stage | Out-Null
|
||||
Copy-Item ".\target\release\marqdo.exe" (Join-Path $stage "marqdo.exe") -Force
|
||||
Copy-Item ".\lib" (Join-Path $stage "lib") -Recurse -Force
|
||||
$zipPath = Join-Path $dist $zipName
|
||||
if (Test-Path $zipPath) { Remove-Item $zipPath -Force }
|
||||
Compress-Archive -Path (Join-Path $stage "*") -DestinationPath $zipPath -Force
|
||||
|
||||
$stageLib = Join-Path $dist "stage-stdlib"
|
||||
if (Test-Path $stageLib) { Remove-Item $stageLib -Recurse -Force }
|
||||
New-Item -ItemType Directory -Force -Path $stageLib | Out-Null
|
||||
Copy-Item ".\lib" (Join-Path $stageLib "lib") -Recurse -Force
|
||||
$stdlibPath = Join-Path $dist $stdlibName
|
||||
if (Test-Path $stdlibPath) { Remove-Item $stdlibPath -Force }
|
||||
Compress-Archive -Path (Join-Path $stageLib "*") -DestinationPath $stdlibPath -Force
|
||||
|
||||
Write-Host "[3/6] source archive (main @ HEAD, no .git)"
|
||||
$sourcePath = Join-Path $dist $sourceName
|
||||
if (Test-Path $sourcePath) { Remove-Item $sourcePath -Force }
|
||||
git archive --format=zip -o $sourcePath HEAD
|
||||
if ($LASTEXITCODE -ne 0) { throw "git archive failed" }
|
||||
|
||||
if (-not $SkipVsix) {
|
||||
Write-Host "[4/6] VSIX (branch vscode-extension)"
|
||||
Invoke-Git fetch origin vscode-extension
|
||||
if (Test-Path "vscode-extension") { Remove-Item "vscode-extension" -Recurse -Force }
|
||||
Invoke-Git checkout origin/vscode-extension -- vscode-extension
|
||||
Push-Location vscode-extension
|
||||
npm ci --silent
|
||||
npm run compile
|
||||
$vsixPath = Join-Path $dist $vsixName
|
||||
if (Test-Path $vsixPath) { Remove-Item $vsixPath -Force }
|
||||
npx --yes @vscode/vsce package --no-dependencies -o $vsixPath
|
||||
Pop-Location
|
||||
Remove-Item "vscode-extension" -Recurse -Force -ErrorAction SilentlyContinue
|
||||
} else {
|
||||
Write-Host "[4/6] VSIX skipped"
|
||||
}
|
||||
|
||||
if (-not $SkipPublic) {
|
||||
Write-Host "[5/6] public static site"
|
||||
& .\target\release\marqdo.exe view output public -o public
|
||||
if (-not (Test-Path "public\index.html")) { throw "public/index.html missing after view output" }
|
||||
$publicPath = Join-Path $dist $publicName
|
||||
if (Test-Path $publicPath) { Remove-Item $publicPath -Force }
|
||||
Compress-Archive -Path "public\*" -DestinationPath $publicPath -Force
|
||||
} else {
|
||||
Write-Host "[5/6] public skipped"
|
||||
}
|
||||
|
||||
Write-Host "[6/6] dist summary"
|
||||
Get-ChildItem $dist -File | ForEach-Object { Write-Host (" {0,12:N0} bytes {1}" -f $_.Length, $_.Name) }
|
||||
|
||||
if ($DeployPages) {
|
||||
Write-Host "Deploying gh-pages..."
|
||||
if (-not (Test-Path "public\index.html")) {
|
||||
& .\target\release\marqdo.exe view output public -o public
|
||||
}
|
||||
$pagesDir = Join-Path $dist "gh-pages-staging"
|
||||
if (Test-Path $pagesDir) { Remove-Item $pagesDir -Recurse -Force }
|
||||
New-Item -ItemType Directory -Force -Path $pagesDir | Out-Null
|
||||
Copy-Item -Recurse public\* $pagesDir -Force
|
||||
# peaceiris-style: only site artifacts on gh-pages
|
||||
git worktree add $pagesDir gh-pages 2>$null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
git branch -D gh-pages 2>$null
|
||||
git checkout --orphan gh-pages-temp
|
||||
git reset --hard
|
||||
git checkout main
|
||||
git branch -D gh-pages-temp 2>$null
|
||||
git checkout -b gh-pages
|
||||
Copy-Item -Recurse (Join-Path $Root "public\*") . -Force
|
||||
git add -A
|
||||
git commit -m "Deploy public site for $Tag"
|
||||
git push -f origin gh-pages
|
||||
git checkout main
|
||||
} else {
|
||||
Write-Host "gh-pages worktree exists; copy public/ manually or use CI pages workflow"
|
||||
}
|
||||
}
|
||||
|
||||
if ($Upload) {
|
||||
Write-Host "Uploading to GitHub Release $Tag ..."
|
||||
$assets = @($exeName, $zipName, $stdlibName, $sourceName)
|
||||
if (-not $SkipVsix) { $assets += $vsixName }
|
||||
if (-not $SkipPublic) { $assets += $publicName }
|
||||
|
||||
$raw = ("protocol=https`nhost=github.com`n`n" | git credential fill 2>$null) -join "`n"
|
||||
$user = ([regex]::Match($raw, '(?m)^username=(.+)$')).Groups[1].Value
|
||||
$token = ([regex]::Match($raw, '(?m)^password=(.+)$')).Groups[1].Value
|
||||
if (-not $token) { throw "No GitHub token from git credential; run gh auth login" }
|
||||
$headers = @{
|
||||
Authorization = "Bearer $token"
|
||||
Accept = "application/vnd.github+json"
|
||||
"User-Agent" = "marqdo-release-full"
|
||||
}
|
||||
|
||||
$notes = @"
|
||||
## Marqdo $Tag
|
||||
|
||||
### Downloads
|
||||
|
||||
| Asset | Contents |
|
||||
|-------|----------|
|
||||
| ``$exeName`` | Windows CLI (**embedded** official ``lib/``) |
|
||||
| ``$zipName`` | ``marqdo.exe`` + ``lib/`` (optional disk override) |
|
||||
| ``$stdlibName`` | Standard library ``lib/*.mq.md`` only |
|
||||
| ``$sourceName`` | Source tree snapshot (``git archive`` of ``main``) |
|
||||
| ``$vsixName`` | VS Code / Cursor extension (from branch ``vscode-extension``) |
|
||||
| ``$publicName`` | Static user docs site (also at [gh-pages](https://cflmy.github.io/marqdo/)) |
|
||||
|
||||
### Highlights
|
||||
- Embedded stdlib, **writeback** + **subtask**, v0.2 syntax, ``marqdo version --check``
|
||||
- Extension source: branch ``vscode-extension`` — [vscode-extension-commit.md](https://github.com/cflmy/marqdo/blob/main/doc/design/vscode-extension-commit.md)
|
||||
|
||||
See [CHANGELOG.md](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md).
|
||||
"@
|
||||
|
||||
try {
|
||||
$rel = Invoke-RestMethod -Uri "https://api.github.com/repos/cflmy/marqdo/releases/tags/$Tag" -Headers $headers
|
||||
$releaseId = $rel.id
|
||||
$uploadUrl = $rel.upload_url -replace "\{.*", ""
|
||||
Write-Host "Updating release $($rel.html_url)"
|
||||
$body = @{ tag_name = $Tag; name = "Marqdo $Tag"; body = $notes; draft = $false; prerelease = $false } | ConvertTo-Json -Depth 5
|
||||
Invoke-RestMethod -Method Patch -Uri "https://api.github.com/repos/cflmy/marqdo/releases/$releaseId" -Headers $headers -ContentType "application/json; charset=utf-8" -Body ([Text.Encoding]::UTF8.GetBytes($body)) | Out-Null
|
||||
} catch {
|
||||
Write-Host "Creating release $Tag ..."
|
||||
$body = @{ tag_name = $Tag; name = "Marqdo $Tag"; body = $notes; draft = $false; prerelease = $false } | ConvertTo-Json -Depth 5
|
||||
$rel = Invoke-RestMethod -Method Post -Uri "https://api.github.com/repos/cflmy/marqdo/releases" -Headers $headers -ContentType "application/json; charset=utf-8" -Body ([Text.Encoding]::UTF8.GetBytes($body))
|
||||
$releaseId = $rel.id
|
||||
$uploadUrl = $rel.upload_url -replace "\{.*", ""
|
||||
}
|
||||
|
||||
$rel = Invoke-RestMethod -Uri "https://api.github.com/repos/cflmy/marqdo/releases/$releaseId" -Headers $headers
|
||||
foreach ($file in $assets) {
|
||||
$path = Join-Path $dist $file
|
||||
if (-not (Test-Path $path)) { Write-Warning "skip missing $file"; continue }
|
||||
$existing = $rel.assets | Where-Object { $_.name -eq $file }
|
||||
if ($existing) {
|
||||
Invoke-RestMethod -Method Delete -Uri "https://api.github.com/repos/cflmy/marqdo/releases/assets/$($existing.id)" -Headers $headers | Out-Null
|
||||
}
|
||||
$uri = "$uploadUrl`?name=$([uri]::EscapeDataString($file))"
|
||||
$bytes = [System.IO.File]::ReadAllBytes($path)
|
||||
$ctype = switch -Regex ($file) {
|
||||
'\.zip$' { "application/zip" }
|
||||
'\.vsix$' { "application/vsix" }
|
||||
default { "application/octet-stream" }
|
||||
}
|
||||
$asset = Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -ContentType $ctype -Body $bytes
|
||||
Write-Host " uploaded $($asset.browser_download_url)"
|
||||
}
|
||||
Write-Host "OK https://github.com/cflmy/marqdo/releases/tag/$Tag"
|
||||
}
|
||||
|
||||
Write-Host "Done."
|
||||
@@ -1,137 +0,0 @@
|
||||
# Build Windows release assets (exe, bundle zip, stdlib zip, VSIX) and upload
|
||||
# to an existing GitHub Release tag.
|
||||
# Usage (from repo root):
|
||||
# powershell -File ./scripts/release-windows.ps1
|
||||
# powershell -File ./scripts/release-windows.ps1 -Tag v0.1.2
|
||||
param(
|
||||
[string]$Tag = ""
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
Set-Location (Split-Path $PSScriptRoot -Parent)
|
||||
|
||||
if (-not $Tag) {
|
||||
$Tag = (Select-String -Path Cargo.toml -Pattern '^version\s*=\s*"([^"]+)"').Matches.Groups[1].Value
|
||||
$Tag = "v$Tag"
|
||||
}
|
||||
$ver = $Tag.TrimStart("v")
|
||||
$target = "x86_64-pc-windows-msvc"
|
||||
$dist = Join-Path (Get-Location) "dist"
|
||||
$stage = Join-Path $dist "stage-bundle"
|
||||
$stageLib = Join-Path $dist "stage-stdlib"
|
||||
New-Item -ItemType Directory -Force -Path $dist | Out-Null
|
||||
|
||||
Write-Host "Building release binary for $Tag ..."
|
||||
cargo build --release -q
|
||||
|
||||
$exeName = "marqdo-$ver-$target.exe"
|
||||
$zipName = "marqdo-$ver-$target.zip"
|
||||
$stdlibName = "marqdo-$ver-stdlib.zip"
|
||||
$vsixName = "marqdo-$ver.vsix"
|
||||
$exePath = Join-Path $dist $exeName
|
||||
$zipPath = Join-Path $dist $zipName
|
||||
$stdlibPath = Join-Path $dist $stdlibName
|
||||
$vsixPath = Join-Path $dist $vsixName
|
||||
|
||||
Copy-Item ".\target\release\marqdo.exe" $exePath -Force
|
||||
|
||||
Write-Host "Building VS Code extension $vsixName (from branch vscode-extension) ..."
|
||||
git fetch origin vscode-extension 2>$null
|
||||
git checkout origin/vscode-extension -- vscode-extension
|
||||
Push-Location vscode-extension
|
||||
npm ci --silent
|
||||
npm run compile
|
||||
npx @vscode/vsce package --no-dependencies -o $vsixPath
|
||||
Pop-Location
|
||||
|
||||
# Bundle: marqdo.exe + lib/ (optional disk override)
|
||||
if (Test-Path $stage) { Remove-Item $stage -Recurse -Force }
|
||||
New-Item -ItemType Directory -Force -Path $stage | Out-Null
|
||||
Copy-Item ".\target\release\marqdo.exe" (Join-Path $stage "marqdo.exe") -Force
|
||||
Copy-Item ".\lib" (Join-Path $stage "lib") -Recurse -Force
|
||||
if (Test-Path $zipPath) { Remove-Item $zipPath -Force }
|
||||
Compress-Archive -Path (Join-Path $stage "*") -DestinationPath $zipPath -Force
|
||||
|
||||
# Stdlib-only zip (override / mirror)
|
||||
if (Test-Path $stageLib) { Remove-Item $stageLib -Recurse -Force }
|
||||
New-Item -ItemType Directory -Force -Path $stageLib | Out-Null
|
||||
Copy-Item ".\lib" (Join-Path $stageLib "lib") -Recurse -Force
|
||||
if (Test-Path $stdlibPath) { Remove-Item $stdlibPath -Force }
|
||||
Compress-Archive -Path (Join-Path $stageLib "*") -DestinationPath $stdlibPath -Force
|
||||
|
||||
Write-Host "Packaged:"
|
||||
Write-Host " $exePath (CLI with embedded stdlib)"
|
||||
Write-Host " $zipPath (marqdo.exe + lib/)"
|
||||
Write-Host " $stdlibPath (lib/ only)"
|
||||
Write-Host " $vsixPath (VS Code extension)"
|
||||
|
||||
$raw = ("protocol=https`nhost=github.com`n`n" | git credential fill 2>$null) -join "`n"
|
||||
$user = ([regex]::Match($raw, '(?m)^username=(.+)$')).Groups[1].Value
|
||||
$token = ([regex]::Match($raw, '(?m)^password=(.+)$')).Groups[1].Value
|
||||
if (-not $token) { throw "No GitHub credentials from git credential fill; run gh auth login or configure git credentials." }
|
||||
$pair = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${user}:${token}"))
|
||||
$headers = @{
|
||||
Authorization = "Basic $pair"
|
||||
Accept = "application/vnd.github+json"
|
||||
"User-Agent" = "marqdo-release-windows"
|
||||
}
|
||||
|
||||
$rel = Invoke-RestMethod -Uri "https://api.github.com/repos/cflmy/marqdo/releases/tags/$Tag" -Headers $headers
|
||||
Write-Host "Uploading to release $($rel.html_url)"
|
||||
|
||||
$notes = @"
|
||||
## Marqdo $Tag
|
||||
|
||||
### Downloads
|
||||
|
||||
| Asset | Contents |
|
||||
|-------|----------|
|
||||
| ``$exeName`` | CLI with **embedded** official stdlib (``lib/*.mq.md``) |
|
||||
| ``$zipName`` | ``marqdo.exe`` + ``lib/`` (optional disk override) |
|
||||
| ``$stdlibName`` | Standard library only — unpack to override embedded lib |
|
||||
| ``$vsixName`` | **VS Code / Cursor extension** — built from branch ``vscode-extension`` only (see doc/design/vscode-extension-commit.md) |
|
||||
|
||||
### Highlights
|
||||
- **Embedded stdlib**: standalone ``.exe`` imports ``lib/…`` without a separate zip
|
||||
- **writeback** + **subtask** (file / function / foreign concurrency)
|
||||
- **v0.2 syntax**: ``+`param` ``, ``1.`` branches, backtick identifiers, quoted strings
|
||||
- ``marqdo version --check`` compares with GitHub latest release
|
||||
|
||||
### Quick start
|
||||
|
||||
``````text
|
||||
marqdo --version
|
||||
marqdo version --check
|
||||
marqdo run public/00-welcome.mq.md
|
||||
marqdo view public
|
||||
``````
|
||||
|
||||
See [CHANGELOG.md](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md).
|
||||
"@
|
||||
|
||||
$body = @{
|
||||
tag_name = $Tag
|
||||
name = "Marqdo $Tag"
|
||||
body = $notes
|
||||
draft = $false
|
||||
prerelease = $false
|
||||
} | ConvertTo-Json -Depth 5
|
||||
Invoke-RestMethod -Method Patch -Uri "https://api.github.com/repos/cflmy/marqdo/releases/$($rel.id)" -Headers $headers -ContentType "application/json; charset=utf-8" -Body ([Text.Encoding]::UTF8.GetBytes($body)) | Out-Null
|
||||
|
||||
$rel = Invoke-RestMethod -Uri "https://api.github.com/repos/cflmy/marqdo/releases/$($rel.id)" -Headers $headers
|
||||
|
||||
foreach ($file in @($exeName, $zipName, $stdlibName, $vsixName)) {
|
||||
$path = Join-Path $dist $file
|
||||
$existing = $rel.assets | Where-Object { $_.name -eq $file }
|
||||
if ($existing) {
|
||||
Invoke-RestMethod -Method Delete -Uri $existing.url -Headers $headers | Out-Null
|
||||
Write-Host " deleted old $file"
|
||||
}
|
||||
$uri = "https://uploads.github.com/repos/cflmy/marqdo/releases/$($rel.id)/assets?name=$([uri]::EscapeDataString($file))"
|
||||
$bytes = [System.IO.File]::ReadAllBytes($path)
|
||||
$ctype = if ($file.EndsWith(".zip")) { "application/zip" } elseif ($file.EndsWith(".vsix")) { "application/vsix" } else { "application/octet-stream" }
|
||||
$asset = Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -ContentType $ctype -Body $bytes
|
||||
Write-Host " $($asset.browser_download_url)"
|
||||
}
|
||||
|
||||
Write-Host "OK"
|
||||
@@ -1,251 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rebuild the Marqdo Markdown → View → execution promotional film.
|
||||
|
||||
Source imagery:
|
||||
- assets/marketing/user-procurement-view.png: original user-provided View capture
|
||||
- assets/marketing/source-markdown-view-concept.png: original generated concept art
|
||||
Other images are generated from the repository's actual procurement source.
|
||||
The purchasing demo is simulated, not an ERP transaction.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import math, subprocess, wave, tempfile
|
||||
import numpy as np
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageOps
|
||||
from markdown_it import MarkdownIt
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
A=ROOT/"assets"/"marketing"
|
||||
OUT=A/"marqdo-2.7.1-markdown-to-execution.mp4"
|
||||
POSTER=A/"marqdo-2.7.1-markdown-to-execution-cover.jpg"
|
||||
SRT=A/"marqdo-2.7.1-markdown-to-execution.srt"
|
||||
W,H=1600,900
|
||||
D=[4.8,6.8,6.4,7.0,7.5,9.5,8.8,5.2]
|
||||
IVORY=(249,247,242);INK=(37,35,34);GOLD=(191,146,81);PEARL=(242,232,214);DIM=(122,114,105);NIGHT=(18,23,32)
|
||||
REG="/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"
|
||||
BOLD="/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc"
|
||||
SERIF="/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc"
|
||||
SERIFB="/usr/share/fonts/opentype/noto/NotoSerifCJK-Bold.ttc"
|
||||
def f(size,mode="regular"):
|
||||
return ImageFont.truetype({"regular":REG,"bold":BOLD,"serif":SERIF,"serifbold":SERIFB}[mode],size)
|
||||
def txt(d,xy,s,size=26,color=INK,style="regular"):
|
||||
d.text(xy,str(s),font=f(size,style),fill=color)
|
||||
def card(d,box,fill=IVORY,stroke=(220,210,195),r=24):
|
||||
d.rounded_rectangle(box,radius=r,fill=fill,outline=stroke,width=2)
|
||||
def base(dark=False):
|
||||
im=Image.new("RGB",(W,H),NIGHT if dark else IVORY)
|
||||
d=ImageDraw.Draw(im)
|
||||
if dark:
|
||||
for j in range(8):
|
||||
d.arc((880+j*32,-200+j*26,1760+j*28,1030+j*25),158,268,fill=(68+j*7,60+j*6,51+j*4),width=2)
|
||||
else:
|
||||
for j in range(7):
|
||||
d.arc((-430+j*14,-500+j*14,500+j*25,520+j*25),35,150,fill=(238,224+j*2,207+j*2),width=2)
|
||||
return im
|
||||
def rounded_image(im,src,box,focus=(.5,.5)):
|
||||
x1,y1,x2,y2=box
|
||||
crop=ImageOps.fit(src,(x2-x1,y2-y1),method=Image.Resampling.LANCZOS,centering=focus)
|
||||
mask=Image.new("L",crop.size,0)
|
||||
ImageDraw.Draw(mask).rounded_rectangle((0,0,crop.width-1,crop.height-1),radius=18,fill=255)
|
||||
im.paste(crop,(x1,y1),mask)
|
||||
ImageDraw.Draw(im).rounded_rectangle(box,radius=18,outline=(200,177,145),width=2)
|
||||
def footer(d,text,dark=False):
|
||||
txt(d,(80,855),text,18,(148,158,171) if dark else DIM)
|
||||
def make_intro():
|
||||
im=base(True);d=ImageDraw.Draw(im)
|
||||
txt(d,(94,113),"MARQDO / v2.7.1",21,(233,197,146))
|
||||
txt(d,(90,221),"Your SKILL",83,IVORY,"serifbold")
|
||||
txt(d,(90,327),"is now a",83,IVORY,"serifbold")
|
||||
txt(d,(90,435),"TOOL.",91,(244,201,148),"serifbold")
|
||||
d.line((100,562,1040,562),fill=GOLD,width=3)
|
||||
txt(d,(102,613),"不只是让 AI 阅读文档。",35,(232,230,224),"serif")
|
||||
txt(d,(102,681),"让同一份 Markdown 承载可控执行流。",35,(232,230,224),"serif")
|
||||
footer(d,"WRITE ONCE · RENDER AS MARKDOWN · INSPECT AS RUNTIME",True)
|
||||
return im
|
||||
|
||||
source=(ROOT/"examples/procurement/index.mq.md").read_text(encoding="utf8")
|
||||
assert "## 查询采购商价格" in source
|
||||
section=source.split("## 查询采购商价格",1)[1].split("\n## ",1)[0]
|
||||
excerpt="## 查询采购商价格\n"+section
|
||||
lines=excerpt.splitlines()
|
||||
content=[]
|
||||
for line in lines:
|
||||
if len(content)>=18:break
|
||||
content.append(line)
|
||||
assert len(content)>10
|
||||
md=MarkdownIt("commonmark").enable("table")
|
||||
html=md.render("\n".join(content))
|
||||
document=f"""<!DOCTYPE html><html lang='zh'><head><meta charset='utf-8'>
|
||||
<style>html,body{{margin:0;background:#fcfbf6;color:#34302d}}
|
||||
body{{font-family:'Noto Serif CJK SC',serif;padding:64px 96px;font-size:26px;line-height:1.75}}
|
||||
h2{{font-size:43px;font-weight:700;margin:0 0 33px}}
|
||||
p{{margin:17px 0}}table{{font:20px/1.7 'Noto Sans CJK SC',sans-serif;width:100%;border-collapse:collapse;margin:26px 0}}
|
||||
td,th{{padding:12px 18px;border:1px solid #e1d7c8;text-align:left}}
|
||||
th{{background:#efe7d9}}tr:nth-child(even){{background:#f7f2e9}}em{{color:#8c704f}}
|
||||
</style></head><body>{html}</body></html>"""
|
||||
opts=Options()
|
||||
for arg in ["--headless=new","--no-sandbox","--disable-dev-shm-usage","--disable-gpu","--window-size=1450,1600"]:
|
||||
opts.add_argument(arg)
|
||||
browser=webdriver.Chrome(options=opts)
|
||||
try:
|
||||
browser.set_window_size(1450,1600)
|
||||
browser.get("data:text/html;charset=utf-8,"+__import__("urllib.parse",fromlist=["quote"]).quote(document))
|
||||
htmlscreen=A/"marqdo-procurement-standard-markdown.png"
|
||||
browser.save_screenshot(str(htmlscreen))
|
||||
assert htmlscreen.stat().st_size>20000
|
||||
finally:
|
||||
browser.quit()
|
||||
RENDER=Image.open(htmlscreen).convert("RGB")
|
||||
USER=Image.open(A/"user-procurement-view.png").convert("RGB")
|
||||
CONCEPT=Image.open(A/"source-markdown-view-concept.png").convert("RGB")
|
||||
|
||||
def make_source():
|
||||
im=base(True);d=ImageDraw.Draw(im)
|
||||
txt(d,(78,69),"01 / SOURCE",21,(226,192,141))
|
||||
txt(d,(77,123),"源码态:它本来就是 Markdown",54,IVORY,"serifbold")
|
||||
txt(d,(80,209),"普通段落保持可读,标题、参数表和返回契约仍是 Markdown。",28,(187,198,213))
|
||||
card(d,(75,265,1520,797),(28,38,51),(78,89,105),23)
|
||||
card(d,(76,265,1519,332),(43,53,70),(43,53,70),23)
|
||||
for j,col in enumerate([(190,97,91),(224,173,97),(109,173,130)]):
|
||||
d.ellipse((105+j*33,293,122+j*33,310),fill=col)
|
||||
txt(d,(256,282),"index.mq.md · 查询采购商价格",24,(227,227,222))
|
||||
for i,line in enumerate(content[:16]):
|
||||
value=line[:77].replace("\t"," ")
|
||||
clr=(232,193,133) if value.startswith("#") or "返回" in value else ((164,214,201) if "正常" in value else (221,226,230))
|
||||
txt(d,(106,358+i*25),f"{i+1:02d} {value}",20,clr)
|
||||
footer(d,"ACTUAL .mq.md EXCERPT · source: examples/procurement/index.mq.md",True)
|
||||
return im
|
||||
|
||||
def make_render():
|
||||
im=base();d=ImageDraw.Draw(im)
|
||||
txt(d,(81,69),"02 / STANDARD MARKDOWN",21,(170,126,67))
|
||||
txt(d,(77,128),"渲染态:它首先是一篇文档",56,INK,"serifbold")
|
||||
txt(d,(80,205),"同一段源码,无需定制语法高亮,也可以按 Markdown 阅读。",29,DIM)
|
||||
card(d,(80,265,1516,839),(255,254,251))
|
||||
rounded_image(im,RENDER,(120,290,1469,814),(.5,.19))
|
||||
txt(ImageDraw.Draw(im),(1145,280),"STANDARD MARKDOWN",18,(167,115,55))
|
||||
footer(ImageDraw.Draw(im),"A MARKDOWN-IT RENDER · FROM THE SAME SOURCE")
|
||||
return im
|
||||
|
||||
def make_triple():
|
||||
im=base();d=ImageDraw.Draw(im)
|
||||
txt(d,(75,60),"03 / THREE VIEWS, ONE FILE",21,(170,126,67))
|
||||
txt(d,(76,130),"同一份 .mq.md,三种视图",55,INK,"serifbold")
|
||||
txt(d,(81,211),"源码能编写,Markdown 能阅读,View 能看到函数、值和执行依赖。",27,DIM)
|
||||
screens=[("SOURCE / 源码",make_source()),("MARKDOWN / 渲染",RENDER),("VIEW / 执行",USER)]
|
||||
xlist=[75,578,1081]
|
||||
for i,(label,src) in enumerate(screens):
|
||||
x=xlist[i];tw=442
|
||||
card(d,(x,280,x+tw,777),(255,254,250))
|
||||
txt(d,(x+21,301),label,23,(130,95,56))
|
||||
rounded_image(im,src,(x+15,349,x+tw-15,749),(.50,.38))
|
||||
d=ImageDraw.Draw(im)
|
||||
for x in [523,1026]:
|
||||
d.line((x,530,x+49,530),fill=GOLD,width=4)
|
||||
d.polygon([(x+49,530),(x+32,519),(x+32,541)],fill=GOLD)
|
||||
footer(d,"NOT THREE FILES · ONE DOCUMENT + EXECUTION SEMANTICS")
|
||||
return im
|
||||
|
||||
def make_concept():
|
||||
im=base();d=ImageDraw.Draw(im)
|
||||
txt(d,(72,58),"04 / DESIGN LANGUAGE",21,(170,126,67))
|
||||
rounded_image(im,CONCEPT,(55,112,1545,850),(.5,.5))
|
||||
txt(ImageDraw.Draw(im),(92,855),"CONCEPT ART · Source → Rendered Markdown → Marqdo View",18,DIM)
|
||||
return im
|
||||
|
||||
def make_view():
|
||||
im=base();d=ImageDraw.Draw(im)
|
||||
txt(d,(78,62),"05 / REAL MARQDO VIEW",21,(170,126,67))
|
||||
txt(d,(78,127),"在文档上,看见它的执行流",58,INK,"serifbold")
|
||||
txt(d,(80,216),"自然语言依然是主体,执行信息沿优雅的曲线引出。",28,DIM)
|
||||
card(d,(70,278,1530,841),(255,254,250))
|
||||
rounded_image(im,USER,(88,295,1513,817),(.50,.50))
|
||||
footer(ImageDraw.Draw(im),"ACTUAL VIEW SCREENSHOT · PROVIDED BY THE PROJECT AUTHOR")
|
||||
return im
|
||||
|
||||
def make_execution():
|
||||
im=base(True);d=ImageDraw.Draw(im)
|
||||
txt(d,(80,66),"06 / EXECUTABLE FUNCTIONS",21,(230,192,137))
|
||||
txt(d,(80,132),"在哪里执行?就在同一份文档的函数里。",53,IVORY,"serifbold")
|
||||
txt(d,(84,216),"说明是可读的,规则却会通过函数调用实际检查。",28,(183,198,211))
|
||||
card(d,(76,275,1519,367),(30,42,57),(78,88,100))
|
||||
txt(d,(99,303),"marqdo call examples/procurement/index.mq.md 查询余额 已花费=120",25,(233,218,188))
|
||||
card(d,(76,418,760,775),(25,55,48),(70,124,96))
|
||||
card(d,(790,418,1520,775),(58,34,43),(154,85,96))
|
||||
txt(d,(110,455),"PASS / LOCAL SIMULATION",24,(150,227,185))
|
||||
txt(d,(822,455),"DENIED / BUDGET CHECK",24,(249,164,170))
|
||||
txt(d,(112,533),"¥120 + ¥288",43,IVORY)
|
||||
txt(d,(823,533),"¥360 + ¥288",43,IVORY)
|
||||
txt(d,(113,606),"¥408",86,(146,229,185),"bold")
|
||||
txt(d,(823,606),"¥648",86,(250,162,166),"bold")
|
||||
txt(d,(115,720),"ok: true · 本地模拟,未发送",23,(217,237,224))
|
||||
txt(d,(824,720),"ok: false · 超预算拒绝",23,(248,216,217))
|
||||
footer(d,"OUTCOMES VERIFIED WITH MARQDO 2.7.1 CLI · NO REAL ORDER WAS SENT",True)
|
||||
return im
|
||||
|
||||
def make_outro():
|
||||
im=base(True);d=ImageDraw.Draw(im)
|
||||
txt(d,(97,157),"Marqdo",90,IVORY,"serifbold")
|
||||
txt(d,(98,313),"Write it. Read it. Run it.",61,(238,195,136),"serifbold")
|
||||
d.line((99,431,1480,431),fill=GOLD,width=3)
|
||||
txt(d,(101,500),"A document-native runtime for executable AI skills.",31,(217,221,225))
|
||||
txt(d,(101,649),"github.com/cflmy/marqdo",43,IVORY)
|
||||
footer(d,"Marqdo v2.7.1 · Apache 2.0 · simulated procurement demo",True)
|
||||
return im
|
||||
|
||||
slides=[make_intro(),make_source(),make_render(),make_triple(),make_concept(),make_view(),make_execution(),make_outro()]
|
||||
A.mkdir(parents=True,exist_ok=True)
|
||||
slides[0].save(POSTER,quality=95)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp=Path(tmp);clips=[]
|
||||
for i,(still,dur) in enumerate(zip(slides,D)):
|
||||
imagefile=tmp/f"slide_{i:02d}.png"
|
||||
still.save(imagefile)
|
||||
clip=tmp/f"clip_{i:02d}.mp4"
|
||||
filt=f"scale=1280:720,zoompan=z='min(zoom+0.00016,1.02)':x='iw/2-iw/zoom/2':y='ih/2-ih/zoom/2':d=1:s=1280x720:fps=24,fade=t=in:st=0:d=0.4,fade=t=out:st={dur-.5}:d=0.5,format=yuv420p"
|
||||
cmd=["ffmpeg","-y","-hide_banner","-loglevel","error","-loop","1","-framerate","24","-t",str(dur),"-i",str(imagefile),"-vf",filt,"-an","-c:v","libx264","-preset","veryfast","-crf","19","-pix_fmt","yuv420p",str(clip)]
|
||||
subprocess.run(cmd,check=True,timeout=200)
|
||||
clips.append(clip)
|
||||
print("RENDERED_SLIDE",i,flush=True)
|
||||
playlist=tmp/"concat.txt"
|
||||
playlist.write_text("\n".join(f"file '{c}'" for c in clips)+"\n")
|
||||
silent=tmp/"silent.mp4"
|
||||
subprocess.run(["ffmpeg","-y","-hide_banner","-loglevel","error","-f","concat","-safe","0","-i",str(playlist),"-c","copy",str(silent)],check=True,timeout=90)
|
||||
sr=24000
|
||||
total=sum(D);ts=np.arange(int(total*sr))/sr
|
||||
sound=np.zeros(len(ts))
|
||||
at=0.
|
||||
for i,dur in enumerate(D):
|
||||
mask=(ts>=at)&(ts<at+dur);tt=ts[mask]-at
|
||||
a=np.minimum(np.minimum(tt/.8,(dur-tt)/.8),1).clip(0,1)
|
||||
note=[110.,123.47,130.81,146.83,110.,123.47,130.81,110.][i]
|
||||
sound[mask]+=a*.12*(.55*np.sin(2*np.pi*note*tt)+.2*np.sin(2*np.pi*note*1.5*tt)+.12*np.sin(2*np.pi*note*2*tt))
|
||||
at+=dur
|
||||
sound*=np.minimum(np.minimum(ts/1.2,(total-ts)/1.2),1).clip(0,1)
|
||||
wav=tmp/"ambience.wav"
|
||||
with wave.open(str(wav),"wb") as w:
|
||||
w.setnchannels(1);w.setsampwidth(2);w.setframerate(sr)
|
||||
w.writeframes((sound*32767).astype(np.int16).tobytes())
|
||||
subprocess.run(["ffmpeg","-y","-hide_banner","-loglevel","error","-i",str(silent),"-i",str(wav),"-c:v","copy","-c:a","aac","-b:a","160k","-shortest","-movflags","+faststart",str(OUT)],check=True,timeout=90)
|
||||
|
||||
times=[0,4.8,11.6,18,25,32.5,42,50.8,56]
|
||||
messages=[
|
||||
"Your SKILL is now a TOOL.\n让 Markdown 直接承载可执行语义。",
|
||||
"源码态:标题、段落、表格都沿用 Markdown。\n执行逻辑就在文档之中。",
|
||||
"渲染态:同一份代码也能成为普通 Markdown 文档。",
|
||||
"源码态、标准 Markdown 渲染态、Marqdo View 态。\n三种视图,同一份源文件。",
|
||||
"一份 .mq.md,既可以阅读,也可以编译执行。",
|
||||
"真实 View 截图:函数调用和值沿着优雅曲线呈现。",
|
||||
"预算校验不是文字承诺,而是函数执行。\n模拟订单通过或拒绝,均由运行时返回结果。",
|
||||
"Marqdo 2.7.1 · github.com/cflmy/marqdo"
|
||||
]
|
||||
def stamp(s):
|
||||
ms=int(round(s*1000))
|
||||
h=ms//3600000;ms%=3600000;m=ms//60000;ms%=60000
|
||||
return f"{h:02d}:{m:02d}:{ms//1000:02d},{ms%1000:03d}"
|
||||
SRT.write_text("\n\n".join(f"{i+1}\n{stamp(times[i])} --> {stamp(times[i+1])}\n{msg}" for i,msg in enumerate(messages))+"\n",encoding="utf-8")
|
||||
print("VIDEO",OUT,OUT.stat().st_size)
|
||||
print("COVER",POSTER,POSTER.stat().st_size)
|
||||
print("SRT",SRT,SRT.stat().st_size)
|
||||
assert OUT.stat().st_size>800000 and sum(D)==56
|
||||
@@ -1,20 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run every public/*.mq.md that defines `# main`, then export the site.
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
# CLI + native plugins used by public demos (ext/quantum, ext/linalg).
|
||||
cargo build --release -p marqdo -p marqdo_plugin_quantum -p marqdo_plugin_linalg
|
||||
|
||||
BIN=./target/release/marqdo
|
||||
while IFS= read -r -d '' f; do
|
||||
if grep -q '^# main' "$f"; then
|
||||
echo "+ marqdo run $f"
|
||||
"$BIN" run "$f"
|
||||
else
|
||||
echo "- skip (no # main): $f"
|
||||
fi
|
||||
done < <(find public -name '*.mq.md' -print0)
|
||||
|
||||
"$BIN" view output public -o public
|
||||
@@ -1,222 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Upload Marqdo extension packs to Cloudflare R2 (CDN: https://ext.marqdo.com).
|
||||
|
||||
No third-party deps (stdlib only) — AWS Signature V4 PutObject.
|
||||
|
||||
Credentials: ~/.marqdo/r2.env (chmod 600; never commit). Required:
|
||||
R2_ENDPOINT, R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY
|
||||
Optional: R2_PUBLIC_BASE, R2_REGION (default auto)
|
||||
|
||||
Usage:
|
||||
python3 scripts/upload-ext-r2.py --version 1.0.2 dist/marqdo-1.0.2-ext.zip \\
|
||||
dist/marqdo-1.0.2-native-x86_64-unknown-linux-gnu.zip
|
||||
python3 scripts/upload-ext-r2.py --version 1.0.2 --from-dir dist/
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote, urlparse
|
||||
|
||||
|
||||
def load_env_file(path: Path) -> None:
|
||||
if not path.is_file():
|
||||
return
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
k, _, v = line.partition("=")
|
||||
os.environ.setdefault(k.strip(), v.strip().strip("'").strip('"'))
|
||||
|
||||
|
||||
def sha256_hex(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def hmac_sha256(key: bytes, msg: str) -> bytes:
|
||||
return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
|
||||
|
||||
|
||||
def signing_key(secret: str, datestamp: str, region: str, service: str) -> bytes:
|
||||
k_date = hmac_sha256(("AWS4" + secret).encode("utf-8"), datestamp)
|
||||
k_region = hmac.new(k_date, region.encode("utf-8"), hashlib.sha256).digest()
|
||||
k_service = hmac.new(k_region, service.encode("utf-8"), hashlib.sha256).digest()
|
||||
return hmac.new(k_service, b"aws4_request", hashlib.sha256).digest()
|
||||
|
||||
|
||||
def put_object(
|
||||
*,
|
||||
endpoint: str,
|
||||
bucket: str,
|
||||
key: str,
|
||||
body: bytes,
|
||||
content_type: str,
|
||||
access_key: str,
|
||||
secret_key: str,
|
||||
region: str,
|
||||
) -> None:
|
||||
endpoint = endpoint.rstrip("/")
|
||||
host = urlparse(endpoint).netloc
|
||||
# Path-style: https://endpoint/bucket/key
|
||||
canonical_uri = "/" + bucket + "/" + quote(key, safe="/~")
|
||||
amz_date = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
datestamp = amz_date[:8]
|
||||
payload_hash = sha256_hex(body)
|
||||
canonical_headers = (
|
||||
f"content-type:{content_type}\n"
|
||||
f"host:{host}\n"
|
||||
f"x-amz-content-sha256:{payload_hash}\n"
|
||||
f"x-amz-date:{amz_date}\n"
|
||||
)
|
||||
signed_headers = "content-type;host;x-amz-content-sha256;x-amz-date"
|
||||
canonical_request = "\n".join(
|
||||
[
|
||||
"PUT",
|
||||
canonical_uri,
|
||||
"",
|
||||
canonical_headers,
|
||||
signed_headers,
|
||||
payload_hash,
|
||||
]
|
||||
)
|
||||
credential_scope = f"{datestamp}/{region}/s3/aws4_request"
|
||||
string_to_sign = "\n".join(
|
||||
[
|
||||
"AWS4-HMAC-SHA256",
|
||||
amz_date,
|
||||
credential_scope,
|
||||
sha256_hex(canonical_request.encode("utf-8")),
|
||||
]
|
||||
)
|
||||
sig = hmac.new(
|
||||
signing_key(secret_key, datestamp, region, "s3"),
|
||||
string_to_sign.encode("utf-8"),
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
auth = (
|
||||
f"AWS4-HMAC-SHA256 Credential={access_key}/{credential_scope}, "
|
||||
f"SignedHeaders={signed_headers}, Signature={sig}"
|
||||
)
|
||||
url = endpoint + canonical_uri
|
||||
req = urllib.request.Request(url, data=body, method="PUT")
|
||||
req.add_header("Content-Type", content_type)
|
||||
req.add_header("x-amz-content-sha256", payload_hash)
|
||||
req.add_header("x-amz-date", amz_date)
|
||||
req.add_header("Authorization", auth)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=300) as resp:
|
||||
if resp.status not in (200, 201):
|
||||
raise RuntimeError(f"PUT {key} HTTP {resp.status}")
|
||||
except urllib.error.HTTPError as e:
|
||||
detail = e.read().decode("utf-8", errors="replace")
|
||||
raise RuntimeError(f"PUT {key} HTTP {e.code}: {detail}") from e
|
||||
|
||||
|
||||
def content_type_for(path: Path) -> str:
|
||||
if path.name == "VERSION" or path.suffix.lower() == ".txt":
|
||||
return "text/plain; charset=utf-8"
|
||||
if path.suffix.lower() == ".json":
|
||||
return "application/json"
|
||||
return "application/zip"
|
||||
|
||||
|
||||
def upload_file(
|
||||
path: Path,
|
||||
key: str,
|
||||
*,
|
||||
endpoint: str,
|
||||
bucket: str,
|
||||
access_key: str,
|
||||
secret_key: str,
|
||||
region: str,
|
||||
public_base: str,
|
||||
) -> None:
|
||||
body = path.read_bytes()
|
||||
print(f"upload {path.name} → s3://{bucket}/{key} ({len(body)} bytes)")
|
||||
put_object(
|
||||
endpoint=endpoint,
|
||||
bucket=bucket,
|
||||
key=key,
|
||||
body=body,
|
||||
content_type=content_type_for(path),
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
region=region,
|
||||
)
|
||||
print(f" public: {public_base.rstrip('/')}/{key}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
load_env_file(Path.home() / ".marqdo" / "r2.env")
|
||||
load_env_file(Path(".env"))
|
||||
load_env_file(Path(".env.r2"))
|
||||
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument("--version", required=True, help="Extension pack SemVer (no v prefix)")
|
||||
ap.add_argument("--from-dir", type=Path, help="Upload all marqdo-{VER}-*.zip from dir")
|
||||
ap.add_argument("files", nargs="*", type=Path, help="Files to upload")
|
||||
ap.add_argument("--no-latest", action="store_true", help="Do not update latest/ pointers")
|
||||
args = ap.parse_args()
|
||||
|
||||
ver = args.version.lstrip("v")
|
||||
for key in ("R2_ENDPOINT", "R2_BUCKET", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY"):
|
||||
if not os.environ.get(key):
|
||||
print(
|
||||
f"missing {key}; write ~/.marqdo/r2.env (see .env.r2.example)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
|
||||
endpoint = os.environ["R2_ENDPOINT"]
|
||||
bucket = os.environ["R2_BUCKET"]
|
||||
access_key = os.environ["R2_ACCESS_KEY_ID"]
|
||||
secret_key = os.environ["R2_SECRET_ACCESS_KEY"]
|
||||
region = os.environ.get("R2_REGION", "auto")
|
||||
public_base = os.environ.get("R2_PUBLIC_BASE", "https://ext.marqdo.com")
|
||||
|
||||
files: list[Path] = [p for p in args.files if p.is_file()]
|
||||
if args.from_dir:
|
||||
files.extend(sorted(args.from_dir.glob(f"marqdo-{ver}-*.zip")))
|
||||
if not files:
|
||||
print("no files to upload", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
kw = dict(
|
||||
endpoint=endpoint,
|
||||
bucket=bucket,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
region=region,
|
||||
public_base=public_base,
|
||||
)
|
||||
for path in files:
|
||||
upload_file(path, f"v{ver}/{path.name}", **kw)
|
||||
if not args.no_latest:
|
||||
upload_file(path, f"latest/{path.name}", **kw)
|
||||
|
||||
if not args.no_latest:
|
||||
with tempfile.NamedTemporaryFile("w", encoding="utf-8", delete=False) as tf:
|
||||
tf.write(ver + "\n")
|
||||
tmp = Path(tf.name)
|
||||
try:
|
||||
upload_file(tmp, "latest/VERSION", **kw)
|
||||
upload_file(tmp, f"v{ver}/VERSION", **kw)
|
||||
finally:
|
||||
tmp.unlink(missing_ok=True)
|
||||
|
||||
print("done.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user