An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Prepare an isolated Go toolchain for HarmonyOS builds
Daniel1ed072702598
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex 04c5a3d9a3..c9b35401a6 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -97,13 +97,15 @@ Only support compilation under Linux, need to install Harmony SDK, and need to m* `./build.sh` (`./build-win.sh` for Windows Emulator)* https://github.com/siyuan-note/siyuan-harmony-For ARM64 devices, run `node scripts/harmony-dev-run.mjs` from the SiYuan repository root to build the mobile frontend, package resources, build the kernel and signed debug HAP, then install and launch the separate debug app through HDC. First configure the Harmony project's `debug` signing profile for your device in DevEco Studio and prepare the native OCR runtime and models (see the Harmony repository README). On Windows, WSL runs `kernel/harmony/build.sh` against the current checkout; the Harmony SDK and patched Go toolchain described below must be available inside WSL. The script requires ZIP-capable bsdtar (the bundled Windows `tar`) and never automatically uninstalls the app.+For ARM64 devices, run `node scripts/harmony-dev-run.mjs` from the SiYuan repository root to build the mobile frontend, package resources, build the kernel and signed debug HAP, then install and launch the separate debug app through HDC. First configure the Harmony project's `debug` signing profile for your device in DevEco Studio and prepare the native OCR runtime and models (see the Harmony repository README). On Windows, WSL builds the kernel against the current checkout; the Harmony SDK, Go, and Python 3.10+ must be available inside WSL. The script requires ZIP-capable bsdtar (the bundled Windows `tar`) and never automatically uninstalls the app.Use `--deveco=<path>`, `--harmony-dir=<path>`, and `--device=<connect-key>` to select tools, project, and device. `--skip-ui` reuses existing frontend output (mobile, desktop, and export are required), `--skip-kernel` copies existing `kernel/harmony/libkernel.so` and `libkernel.h`, and `--skip-hvigor` only reinstalls and launches the existing debug HAP, skipping all builds and resource copies. See `node scripts/harmony-dev-run.mjs --help` for more options. Run script tests with `node --test app/scripts/harmony-dev-run.test.js`.On Windows, the deployment script translates active `go.work` module paths and local replacements into WSL paths in a temporary workspace. Local dependency overrides remain active; the original workspace files are not changed. If workspace mode is disabled, the WSL build also uses `GOWORK=off`.-Modify Go source code:+The deployment script uses `scripts/prepare-harmony-go.py` to copy the selected Go toolchain into the Linux user cache (default: `~/.cache/siyuan-harmony/go`), applies the three Harmony adaptations below to that copy, and pins it with `GOTOOLCHAIN=local`. The system installation and shared downloaded toolchains remain unchanged. Toolchain version or patch input changes produce another cache entry; unsupported sources and corrupted caches cause an error. Run preparation tests with `python3 -m unittest scripts/test_prepare_harmony_go.py`; on Linux, these also check toolchain selection in the build wrapper without compiling the kernel.++When running `kernel/harmony/build.sh` directly, modify the Go sources actually used by the build:1. go/src/runtime/vim tls_arm64.sdiff --git a/.github/CONTRIBUTING.zh-CN.md b/.github/CONTRIBUTING.zh-CN.mdindex dd8ccfc50c..5180063b95 100644--- a/.github/CONTRIBUTING.zh-CN.md+++ b/.github/CONTRIBUTING.zh-CN.md@@ -97,13 +97,15 @@ Android 工程默认位于思源仓库同级,可用 `--android-dir=<路径>`* `./build.sh` (Windows 模拟器使用 `./build-win.sh`)* https://github.com/siyuan-note/siyuan-harmony-ARM64 真机可在思源仓库根目录执行 `node scripts/harmony-dev-run.mjs`,构建移动端前端、打包资源、构建内核和已签名的调试 HAP,然后通过 HDC 安装并启动独立调试包。先在 DevEco Studio 为设备配置鸿蒙工程的 `debug` 签名,并准备原生 OCR 运行库和模型(参考鸿蒙仓库 README)。Windows 通过 WSL 在当前检出目录中执行 `kernel/harmony/build.sh`,WSL 内仍需具备下述鸿蒙 SDK 和修改后的 Go 工具链。脚本使用支持 ZIP 的 bsdtar(Windows 自带的 `tar`),不会自动卸载应用。+ARM64 真机可在思源仓库根目录执行 `node scripts/harmony-dev-run.mjs`,构建移动端前端、打包资源、构建内核和已签名的调试 HAP,然后通过 HDC 安装并启动独立调试包。先在 DevEco Studio 为设备配置鸿蒙工程的 `debug` 签名,并准备原生 OCR 运行库和模型(参考鸿蒙仓库 README)。Windows 通过 WSL 在当前检出目录中执行内核构建,WSL 内需具备鸿蒙 SDK、Go 和 Python 3.10+。脚本使用支持 ZIP 的 bsdtar(Windows 自带的 `tar`),不会自动卸载应用。通过 `--deveco=<路径>`、`--harmony-dir=<路径>`、`--device=<连接标识>` 指定工具、工程和设备。`--skip-ui` 复用现有前端产物(需包含 mobile、desktop、export),`--skip-kernel` 复制现有 `kernel/harmony/libkernel.so` 和 `libkernel.h`,`--skip-hvigor` 则仅重新安装并启动已有的调试 HAP,跳过所有构建及资源复制。更多参数见 `node scripts/harmony-dev-run.mjs --help`。运行脚本测试:`node --test app/scripts/harmony-dev-run.test.js`。Windows 下,部署脚本会在临时工作区中将当前 `go.work` 的模块路径和本地替换路径转换为 WSL 路径,保留本地依赖覆盖,不修改原始工作区文件。如果已禁用工作区模式,WSL 构建同样使用 `GOWORK=off`。-修改 Go 源码:+部署脚本通过 `scripts/prepare-harmony-go.py` 将实际选中的 Go 工具链复制到 Linux 用户缓存(默认 `~/.cache/siyuan-harmony/go`),在副本中应用下面三处鸿蒙适配,再通过 `GOTOOLCHAIN=local` 固定使用该副本。系统 Go 和自动下载的共享工具链均保持不变;版本或适配输入变化时创建另一份缓存,不识别的源码或损坏的缓存会报错。工具链准备测试:`python3 -m unittest scripts/test_prepare_harmony_go.py`;Linux 下还会验证构建包装脚本的工具链选择流程,测试不编译内核。++直接运行 `kernel/harmony/build.sh` 时,需自行修改实际使用的 Go 源码:1. go/src/runtime/tls_arm64.sdiff --git a/app/scripts/harmony-dev-run.test.js b/app/scripts/harmony-dev-run.test.jsindex 8e243c43f8..2f2e15e247 100644--- a/app/scripts/harmony-dev-run.test.js+++ b/app/scripts/harmony-dev-run.test.js@@ -148,6 +148,7 @@ test(`Harmony build handles resources and workspace (reuse=${reuse}, workspace=$if (command === "wsl.exe" && argv.includes("--cd")) {assert.equal(argv[argv.indexOf("--cd") + 1], "/linux/harmony");assert.ok(argv.includes("pipefail"));+ assert.match(argv.at(-1), /harmony-kernel-build.sh/);const gowork = argv.find(value => value.startsWith("GOWORK="));if (workspace) {temporaryWork = translated.get(gowork.slice("GOWORK=".length));diff --git a/scripts/harmony-dev-run.mjs b/scripts/harmony-dev-run.mjsindex 8287625621..f075329c29 100644--- a/scripts/harmony-dev-run.mjs+++ b/scripts/harmony-dev-run.mjs@@ -101,9 +101,10 @@ export function main(args = process.argv.slice(2), execute = spawnSync, root = rBuilds product=debug, buildMode=debug for ARM64 devices. Configure the debugsigning profile in DevEco Studio for your device first. Uses build.sh and its-Linux SDK / patched Go toolchain (see .github/CONTRIBUTING.md); Windows uses WSL+Linux SDK / Python 3.10+ (see .github/CONTRIBUTING.md); Windows uses WSLagainst this checkout. Existing OCR native libraries and models are required.Windows go.work paths are translated in a temporary workspace, preserving local modules.+The selected Go toolchain is copied and patched in the Linux user cache for Harmony.No uninstall is attempted if installation fails.`);return;}@@ -182,12 +183,12 @@ No uninstall is attempted if installation fails.`);}// 去掉检出脚本的 CRLF,使用临时工作区保留本地依赖,不更改原始工作区文件。run("wsl.exe", [...wsl, "--cd", linuxPath, "--exec", "env", `GOWORK=${gowork}`,- "bash", "-e", "-o", "pipefail", "-c", "sed 's/\\r$//' build.sh | bash -e"], {stdio: "inherit"});+ "bash", "-e", "-o", "pipefail", "-c", "sed 's/\\r$//' ../../scripts/harmony-kernel-build.sh | bash -e -s -- ../../scripts/harmony-kernel-build.sh"], {stdio: "inherit"});} finally {removeTemp(workTemp);}} else {- run("bash", ["-e", "build.sh"], {cwd: kernel, stdio: "inherit"});+ run("bash", ["-e", path.join(root, "scripts/harmony-kernel-build.sh")], {cwd: kernel, stdio: "inherit"});}}checkKernel(path.join(kernel, "libkernel.so"));diff --git a/scripts/harmony-kernel-build.sh b/scripts/harmony-kernel-build.shnew file mode 100644index 0000000000..ae8e40ba16--- /dev/null+++ b/scripts/harmony-kernel-build.sh@@ -0,0 +1,13 @@+#!/bin/bash+# 按模块要求选择 Go 版本,再为鸿蒙构建准备隔离的工具链。+set -euo pipefail++source_root=$(go env GOROOT)+script_dir=$(cd -- "$(dirname -- "${1:-$0}")" && pwd)+harmony_root=$(python3 "$script_dir/prepare-harmony-go.py" --source "$source_root")+export GOROOT="$harmony_root"+export GOTOOLCHAIN=local+export PATH="$GOROOT/bin:$PATH"+echo "Harmony Go: $GOROOT"+# 清除 Windows 检出文件的 CRLF,不修改原始构建脚本。+sed 's/\r$//' build.sh | bash -ediff --git a/scripts/prepare-harmony-go.py b/scripts/prepare-harmony-go.pynew file mode 100644index 0000000000..9570de6c65--- /dev/null+++ b/scripts/prepare-harmony-go.py@@ -0,0 +1,103 @@+#!/usr/bin/env python3+"""为鸿蒙构建准备独立的 Go 工具链副本,不修改系统安装和模块缓存。"""++import argparse+import hashlib+import json+import os+from pathlib import Path+import re+import shutil+import stat+import sys+import tempfile+++PATCH_VERSION = 1+PATCH_FILES = ("src/net/cgo_resold.go", "src/runtime/tls_arm64.s", "src/runtime/cgo/gcc_android.c")+++def replace_once(text, before, after, name):+ if text.count(before) == 1 and after not in text:+ return text.replace(before, after)+ if text.count(after) == 1 and before not in text:+ return text+ raise ValueError(f"Unsupported Go source in {name}; refusing to apply the Harmony patch")+++def patched_sources(source):+ texts = {name: (source / name).read_text(encoding="utf-8") for name in PATCH_FILES}+ texts[PATCH_FILES[0]] = replace_once(texts[PATCH_FILES[0]], "C.size_t(len(b))", "C.socklen_t(len(b))", PATCH_FILES[0])+ texts[PATCH_FILES[1]] = replace_once(texts[PATCH_FILES[1]],+ "DATA runtime·tls_g+0(SB)/8, $16", "DATA runtime·tls_g+0(SB)/8, $-144", PATCH_FILES[1])+ pattern = r"(static void\s+inittls\(void \*\*tlsg, void \*\*tlsbase\)\s*\{)(.*?)(\n\}\s*\nvoid \(\*x_cgo_inittls\))"+ matches = list(re.finditer(pattern, texts[PATCH_FILES[2]], re.S))+ if len(matches) != 1:+ raise ValueError("Unsupported Go inittls function; refusing to apply the Harmony patch")+ body = matches[0].group(2)+ if body.strip() != "return;" and ("pthread_key_create" not in body or "TLS_SLOT_APP" not in body):+ raise ValueError("Unsupported Go inittls body; refusing to apply the Harmony patch")+ texts[PATCH_FILES[2]] = re.sub(pattern, lambda match: match[1] + "\n\treturn;" + match[3], texts[PATCH_FILES[2]], flags=re.S)+ return texts+++def prepare(source, cache):+ source = source.resolve()+ if not (source / "bin/go").is_file():+ raise ValueError(f"Missing Go executable: {source / 'bin/go'}")+ texts = patched_sources(source)+ identity = {"revision": PATCH_VERSION, "source": str(source), "version": (source / "VERSION").read_text(encoding="utf-8"),+ "files": {name: hashlib.sha256((source / name).read_bytes()).hexdigest() for name in PATCH_FILES}}+ key = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()[:24]+ cache = cache.resolve()+ cache.mkdir(parents=True, exist_ok=True)+ target = cache / key++ def valid():+ try:+ return ((target / ".siyuan-harmony.json").read_text(encoding="utf-8") == json.dumps(identity, sort_keys=True)+ and (target / "bin/go").is_file()+ and all((target / name).read_text(encoding="utf-8") == text for name, text in texts.items()))+ except OSError:+ return False++ if target.exists():+ if valid():+ return target+ raise ValueError(f"Invalid Harmony Go cache; choose another --cache-dir: {target}")+ # 先在独立临时目录完成复制及适配,再发布可复用的缓存目录。+ with tempfile.TemporaryDirectory(prefix="prepare-", dir=cache) as temporary:+ staged = Path(temporary) / "go"+ shutil.copytree(source, staged, symlinks=True)+ for directory, _, _ in os.walk(staged):+ folder = Path(directory)+ folder.chmod(folder.stat().st_mode | stat.S_IWUSR)+ for name, text in texts.items():+ destination = staged / name+ if not destination.resolve().is_relative_to(staged.resolve()):+ raise ValueError(f"Go source links outside the copied toolchain: {name}")+ destination.chmod(destination.stat().st_mode | stat.S_IWUSR)+ destination.write_text(text, encoding="utf-8", newline="\n")+ (staged / ".siyuan-harmony.json").write_text(json.dumps(identity, sort_keys=True), encoding="utf-8")+ try:+ staged.rename(target)+ except OSError:+ if not valid():+ raise+ return target+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--source", type=Path, required=True)+ parser.add_argument("--cache-dir", type=Path, default=Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "siyuan-harmony/go")+ args = parser.parse_args()+ print(prepare(args.source, args.cache_dir))+++if __name__ == "__main__":+ try:+ main()+ except (OSError, ValueError) as error:+ print(f"Error: {error}", file=sys.stderr)+ sys.exit(1)diff --git a/scripts/test_prepare_harmony_go.py b/scripts/test_prepare_harmony_go.pynew file mode 100644index 0000000000..e331484867--- /dev/null+++ b/scripts/test_prepare_harmony_go.py@@ -0,0 +1,96 @@+import importlib.util+import os+from pathlib import Path+import subprocess+import tempfile+import unittest+from unittest.mock import patch+++SPEC = importlib.util.spec_from_file_location("harmony_go", Path(__file__).with_name("prepare-harmony-go.py"))+harmony = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(harmony)+++class HarmonyGoTests(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.root = Path(self.temporary.name)+ self.source = self.root / "original-go"+ self.cache = self.root / "cache"+ self.write("bin/go", "executable")+ self.write("VERSION", "go1.26.10\ntime 2026-10-01T00:00:00Z\n")+ self.write(harmony.PATCH_FILES[0], "gerrno, err := C.getnameinfo(sa, salen, b, C.size_t(len(b)), nil, 0, flags)\n")+ self.write(harmony.PATCH_FILES[1], "DATA runtime·tls_g+0(SB)/8, $16\n")+ self.write(harmony.PATCH_FILES[2], "static void\ninittls(void **tlsg, void **tlsbase)\n{\n"+ "\tif (TLS_SLOT_APP) { pthread_key_create(&k, nil); }\n}\n\n"+ "void (*x_cgo_inittls)(void **tlsg, void **tlsbase) = inittls;\n")++ def write(self, name, text):+ file = self.source / name+ file.parent.mkdir(parents=True, exist_ok=True)+ file.write_text(text, encoding="utf-8")++ def test_patches_separate_copy_and_preserves_original_toolchain(self):+ original = {name: (self.source / name).read_bytes() for name in harmony.PATCH_FILES}+ target = harmony.prepare(self.source, self.cache)+ self.assertIn("C.socklen_t(len(b))", (target / harmony.PATCH_FILES[0]).read_text(encoding="utf-8"))+ self.assertIn("$-144", (target / harmony.PATCH_FILES[1]).read_text(encoding="utf-8"))+ self.assertIn("\n\treturn;\n}", (target / harmony.PATCH_FILES[2]).read_text(encoding="utf-8"))+ self.assertNotIn("pthread_key_create", (target / harmony.PATCH_FILES[2]).read_text(encoding="utf-8"))+ self.assertEqual(original, {name: (self.source / name).read_bytes() for name in harmony.PATCH_FILES})++ def test_reuses_completed_cache(self):+ target = harmony.prepare(self.source, self.cache)+ with patch.object(harmony.shutil, "copytree", side_effect=AssertionError("must reuse cache")):+ self.assertEqual(target, harmony.prepare(self.source, self.cache))++ def test_toolchain_version_change_uses_another_cache(self):+ target = harmony.prepare(self.source, self.cache)+ self.write("VERSION", "go1.26.11\n")+ self.assertNotEqual(target, harmony.prepare(self.source, self.cache))++ def test_unknown_source_fails_without_publishing_cache(self):+ self.write(harmony.PATCH_FILES[0], "unknown resolver")+ with self.assertRaisesRegex(ValueError, "Unsupported Go source"):+ harmony.prepare(self.source, self.cache)+ self.assertFalse(self.cache.exists())++ def test_interrupted_copy_leaves_no_reusable_or_temporary_cache(self):+ with patch.object(harmony.shutil, "copytree", side_effect=OSError("copy failed")):+ with self.assertRaisesRegex(OSError, "copy failed"):+ harmony.prepare(self.source, self.cache)+ self.assertEqual(list(self.cache.iterdir()), [])++ def test_corrupted_cache_is_rejected_without_repairing_source(self):+ target = harmony.prepare(self.source, self.cache)+ (target / harmony.PATCH_FILES[0]).write_text("corrupt", encoding="utf-8")+ with self.assertRaisesRegex(ValueError, "Invalid Harmony Go cache"):+ harmony.prepare(self.source, self.cache)++ def test_already_patched_source_remains_supported(self):+ for name, text in harmony.patched_sources(self.source).items():+ self.write(name, text)+ target = harmony.prepare(self.source, self.cache)+ self.assertEqual(harmony.patched_sources(target), harmony.patched_sources(self.source))++ @unittest.skipUnless(os.name == "posix", "Linux shell integration")+ def test_build_wrapper_selects_isolated_toolchain_without_auto_switching(self):+ executable = self.source / "bin/go"+ executable.write_text("#!/bin/sh\nif [ \"$1\" = env ]; then printf '%s\\n' \"$FIXTURE_GOROOT\"; "+ "else test \"$GOTOOLCHAIN\" = local && printf 'isolated:%s\\n' \"$GOROOT\"; fi\n")+ executable.chmod(0o755)+ working = self.root / "harmony"+ working.mkdir()+ (working / "build.sh").write_bytes(b"set -e\r\ngo version\r\n")+ env = dict(os.environ, PATH=str(self.source / "bin") + os.pathsep + os.environ["PATH"],+ FIXTURE_GOROOT=str(self.source), XDG_CACHE_HOME=str(self.root / "linux-cache"))+ result = subprocess.run(["bash", str(Path(__file__).with_name("harmony-kernel-build.sh").resolve())],+ cwd=working, env=env, text=True, capture_output=True)+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("isolated:" + str(self.root / "linux-cache/siyuan-harmony/go"), result.stdout)+++if __name__ == "__main__":+ unittest.main()