From 70d7ed416944bfa8481eecdd532b6aa346293846 Mon Sep 17 00:00:00 2001 From: chumanic Date: Mon, 16 Nov 2026 17:46:28 +0800 Subject: [PATCH] feat(workbench): restore retained repairs to verified private copies --- .github/workflows/release.yml | 75 +++++++++- .gitignore | 2 + CHANGELOG.md | 10 +- README.en.md | 12 +- README.md | 4 +- desktop/README.md | 2 + desktop/application_manifest.py | 44 ++++++ desktop/build_app.py | 21 ++- desktop/prepare_runtime.py | 25 +++- desktop/tests/test_application_manifest.py | 28 ++++ desktop/tests/test_portable_boundaries.py | 39 ++++++ docs/build.md | 2 + docs/repair-recovery.md | 12 ++ package-lock.json | 4 +- package.json | 2 +- src/capabilities.ts | 2 +- src/domain/patch-application.ts | 3 +- src/domain/repair-backups.ts | 16 ++- src/workbench/history.ts | 9 +- src/workbench/page.ts | 30 ++-- src/workbench/repair-recovery.ts | 129 ++++++++++++++++++ src/workbench/server.ts | 33 ++++- tests/cli/fix.test.ts | 16 ++- tests/cli/help.test.ts | 2 +- tests/cli/report.test.ts | 4 +- tests/docs/release-installation.test.ts | 6 +- .../live-runtime-preparation.test.ts | 19 ++- tests/integration/product-trust-loop.test.ts | 15 +- tests/reporters/sarif.test.ts | 2 +- tests/workbench/page.test.ts | 28 +++- tests/workbench/repair-recovery.test.ts | 45 ++++++ tests/workbench/server.test.ts | 57 ++++++++ 32 files changed, 640 insertions(+), 58 deletions(-) create mode 100644 desktop/application_manifest.py create mode 100644 desktop/tests/test_application_manifest.py create mode 100644 desktop/tests/test_portable_boundaries.py create mode 100644 src/workbench/repair-recovery.ts create mode 100644 tests/workbench/repair-recovery.test.ts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 96769a8..8684c0f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,7 +12,7 @@ jobs: release: runs-on: ubuntu-latest permissions: - contents: write + contents: read actions: read id-token: write attestations: write @@ -75,10 +75,81 @@ jobs: uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4 with: subject-path: release/*.tgz - - name: Publish immutable GitHub release + - name: Retain verified CLI distribution + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: skillsync-cli + path: release/* + if-no-files-found: error + + mac-app: + needs: release + runs-on: macos-15 + permissions: + contents: read + id-token: write + attestations: write + artifact-metadata: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: "24" + package-manager-cache: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 + with: + python-version: '3.x' + - run: npm ci --ignore-scripts + - run: npm run build + - name: Build and inspect owned portable application + run: | + set -euo pipefail + test "$(uname -m)" = arm64 + python3 -m unittest discover -s desktop/tests -p 'test_*.py' + python3 desktop/prepare_runtime.py --output "$GITHUB_WORKSPACE/.release-workspace/runtime" + python3 desktop/build_app.py --runtime "$GITHUB_WORKSPACE/.release-workspace/runtime" --output "$GITHUB_WORKSPACE/.release-workspace/apps" + app="$GITHUB_WORKSPACE/.release-workspace/apps/SkillSync.app" + codesign --verify --deep --strict "$app" + "$app/Contents/MacOS/Workspace" --smoke-check "$RUNNER_TEMP/native-smoke.json" --snapshot "$RUNNER_TEMP/native-smoke.png" --width 390 + python3 -c 'import json,sys; assert json.load(open(sys.argv[1]))["success"] is True' "$RUNNER_TEMP/native-smoke.json" + mkdir release + version="${GITHUB_REF_NAME#v}" + archive="release/skillsync-app-v$version-aarch64-apple-darwin.zip" + ditto -c -k --sequesterRsrc --keepParent "$app" "$archive" + python3 desktop/application_manifest.py --application "$app" --archive "$archive" --output "release/skillsync-app-v$version-aarch64-apple-darwin.source.json" + - name: Attest owned portable application + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4 + with: + subject-path: release/*.zip + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: skillsync-mac-app + path: release/* + if-no-files-found: error + + publish: + needs: [release, mac-app] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + pattern: skillsync-* + path: release + merge-multiple: true + - name: Verify immutable tag and publish complete distribution env: GH_TOKEN: ${{ github.token }} run: | set -euo pipefail + ref=$(gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$GITHUB_REF_NAME" --jq '.object.type+" "+.object.sha') + read -r kind source <<< "$ref" + if [[ "$kind" == tag ]]; then source=$(gh api "repos/$GITHUB_REPOSITORY/git/tags/$source" --jq '.object.sha'); fi + test "$source" = "$GITHUB_SHA" + if gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then echo 'An existing release must not be overwritten' >&2; exit 1; fi + (cd release && sha256sum *.tgz *.zip *.json > checksums.txt) gh release create "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --verify-tag \ --title "SkillSync $GITHUB_REF_NAME" --generate-notes release/* diff --git a/.gitignore b/.gitignore index df0c7d0..f5f7a8c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ node_modules dist/ +/release/ +/.release-workspace/ coverage/ .DS_Store .env diff --git a/CHANGELOG.md b/CHANGELOG.md index c6a5541..6b5405e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,12 @@ # Changelog -## Unreleased source - 2026-11-02 +## 0.4.0 - 2026-11-16 + +- Check retained repair originals, create a new bounded recovery copy, reopen the same operation after interruption and verify/download the copy without changing the selected directory. +- Bind new backups to the local selected directory, preserve v1 legacy manifests with original-plan verification, and invalidate confirmation on content, permissions or identity changes. +- Retain four private recovery slots, cancellation material and immutable completion evidence; keep queries read-only and copy reports path-redacted. + +### Included source follow-ups (2026-11-02) - Report Git URL/commit declarations as unknown remote identity rather than authenticated provenance. Explicit unknown-provenance policies also block @@ -14,7 +20,7 @@ - Record synthetic small, byte-limit and near-file-limit scan baselines while retaining the required before/after mutation checks and no cross-request cache. -## Unreleased source - 2026-10-21 +### Included workbench follow-ups (2026-10-21) - Add a loopback graphical workbench for real Skill and contract directories, with native macOS selection, read-only cancellation and offline report review. diff --git a/README.en.md b/README.en.md index a8184a3..d3e36f3 100644 --- a/README.en.md +++ b/README.en.md @@ -8,10 +8,10 @@ Load the sample, check its frontmatter, and use the reported line and column to Inspect local Skill folders and declared artifact deliveries. Review provenance, compatibility and changes without executing the Skill. -> **Alpha · GitHub release v0.3.0 · Node.js 20+** +> **Alpha · GitHub release v0.4.0 · Node.js 20+** > SkillSync performs offline checks of local Skill content. It does not execute Skill scripts, does not read credentials, and does not enable live provider, remote-worker, or runtime capabilities. -GitHub v0.3.0 adds a declared cross-file checklist to HTML, text and JSON reports, including paths, field mappings and capacity limits. Declarations remain separate from actual results, and expected values are omitted. [Review the declaration list](docs/declared-checks.md). It also locates citation metadata failures by file, data record and compared columns. It checks exact digests and revisions without copying record values into reports. The offline review, correction workflow and bounded composite-key reconciliation remain available. The npm registry stays at 0.1.0; use the verified GitHub archive for current features. +GitHub v0.4.0 adds a declared cross-file checklist to HTML, text and JSON reports, including paths, field mappings and capacity limits. Declarations remain separate from actual results, and expected values are omitted. [Review the declaration list](docs/declared-checks.md). It also locates citation metadata failures by file, data record and compared columns. It checks exact digests and revisions without copying record values into reports. The offline review, correction workflow and bounded composite-key reconciliation remain available. The npm registry stays at 0.1.0; use the verified GitHub archive for current features. [![Terminal demo](https://raw.githubusercontent.com/Chumaniac/skillsync/main/docs/assets/verify-demo.svg)](https://github.com/Chumaniac/skillsync/blob/main/docs/assets/verify-demo.svg) @@ -49,7 +49,7 @@ Current source also supports [multi-delivery acceptance plans and portable revie Tagged builds now publish a CLI tarball, checksums, a validated CycloneDX SBOM and a source manifest on [GitHub Releases](https://github.com/Chumaniac/skillsync/releases). -[GitHub v0.3.0](https://github.com/Chumaniac/skillsync/releases/tag/v0.3.0) +[GitHub v0.4.0](https://github.com/Chumaniac/skillsync/releases/tag/v0.4.0) is distributed as a versioned CLI tarball with checksums, SBOM, source manifest and GitHub provenance. Its release workflow requires the exact immutable tag and an already successful main check before packaging. Earlier v0.1.7 assets @@ -58,12 +58,12 @@ Installation uses Node.js 20+ and fetches the package's public dependencies; it needs no npm login. ```bash -release_base="https://github.com/Chumaniac/skillsync/releases/download/v0.3.0" -for asset in chumanic-skillsync-0.3.0.tgz checksums.txt sbom.cyclonedx.json release-manifest.json; do +release_base="https://github.com/Chumaniac/skillsync/releases/download/v0.4.0" +for asset in chumanic-skillsync-0.4.0.tgz checksums.txt sbom.cyclonedx.json release-manifest.json; do curl --fail --location --output "$asset" "$release_base/$asset" done shasum -a 256 -c checksums.txt -npm install --prefix ./skillsync-tools ./chumanic-skillsync-0.3.0.tgz +npm install --prefix ./skillsync-tools ./chumanic-skillsync-0.4.0.tgz ./skillsync-tools/node_modules/.bin/skillsync --version ``` diff --git a/README.md b/README.md index 3a0214e..ba79684 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ 在运行 Skill 之前,检查它来自哪里、需要哪些权限,以及交付物是否满足声明的规则。 -**[打开 SKILL.md 检查器 →](https://chumaniac.github.io/skillsync/)** · [English / CLI reference](README.en.md) · [桌面下载](https://github.com/Chumaniac/skillsync/releases/tag/user-2026.11.11-zh) +**[打开 SKILL.md 检查器 →](https://chumaniac.github.io/skillsync/)** · [English / CLI reference](README.en.md) · [桌面下载](https://github.com/Chumaniac/skillsync/releases/tag/v0.4.0) 进入后,点击「载入示例」再检查文档;出现行列提示时,用「定位错误」回到原文。网页只解析粘贴的文档,本机目录、权限和交付物由 CLI 核验。 @@ -48,3 +48,5 @@ node dist/cli/index.js verify --path fixtures/product/trust-loop/review --target [使用指南](docs/user-guide.md) · [构建桌面应用](docs/build.md) · [隐私与备份](docs/privacy.md) · [贡献指南](CONTRIBUTING.md) 修复前的持久备份、并发编辑保全和中断后的核对步骤见[修复与恢复](docs/repair-recovery.md)。工作台会区分完成历史和保留的未完成材料。 + +修复前文件可在本机核验台检查、恢复到独立副本并只读核验。原目录不被覆盖,旧版备份需关联原计划,结果待查时查询原恢复编号。详见[恢复说明](docs/repair-recovery.md)。GitHub 0.4.0 包与 npm 0.1.0 是不同发行渠道;npm 观察值保持实际记录,不冒充新版已发布。 diff --git a/desktop/README.md b/desktop/README.md index fa5c14c..64e1ebc 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -16,3 +16,5 @@ The three task sections share a quiet sidebar. File and directory selection, scr Native smoke checks use port 19012, a dedicated canonical cache directory and nonpersistent WebKit storage. They never use the normal history directory. The project tests use synthetic files and explicit cleanup. Build output is not a user-data backup. Local builds use ad-hoc signing and are not notarized redistribution releases. 完整可移动程序的构建步骤、运行时闭包和许可要求见[构建说明](../docs/build.md)。 + +The 0.4.0 workbench can check retained repair originals, restore to a new private copy and verify it without changing the selected directory. Source build identity must match the package version and exact Git tree before runtime assembly. The release pipeline includes the portable Apple Silicon app and reports ad-hoc signing explicitly. diff --git a/desktop/application_manifest.py b/desktop/application_manifest.py new file mode 100644 index 0000000..faef704 --- /dev/null +++ b/desktop/application_manifest.py @@ -0,0 +1,44 @@ +"""Inventory an owned SkillSync application without executing its contents.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re + +def scoped(value): + root=os.path.realpath(os.getcwd()); value=os.path.realpath(os.path.abspath(os.path.expanduser(value))) + if value!=root and not value.startswith(root.rstrip(os.sep)+os.sep):raise ValueError('PATH_OUTSIDE_INVOCATION_ROOT') + return Path(value) +def metadata(path,limit): + if not path.is_file() or path.is_symlink() or path.stat().st_size>limit:raise ValueError('METADATA_INVALID') + return json.loads(path.read_text()) +def digest(path): + with path.open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest() +def create(application,archive): + application=scoped(application);archive=scoped(archive) + if not application.is_dir() or application.is_symlink() or not archive.is_file() or archive.is_symlink() or archive.stat().st_size>1024**3:raise ValueError('ARTIFACT_INVALID') + resources=application/'Contents/Resources';config=metadata(resources/'app.json',16384) + runtime=metadata(resources/'runtime/runtime-manifest.json',8*1024**2);build=metadata(resources/'runtime/app/dist/build-info.json',16384) + package=metadata(resources/'runtime/app/package.json',16384);revision=config.get('sourceCommit') + if runtime.get('architecture') not in {'arm64','x86_64'}:raise ValueError('RUNTIME_ARCHITECTURE_INVALID') + if not isinstance(revision,str) or not re.fullmatch('[a-f0-9]{40}',revision) or config.get('includesWorkingTreeChanges') is not False or runtime.get('sourceCommit')!=revision or runtime.get('includesWorkingTreeChanges') is not False or build.get('sourceRevision')!=revision or build.get('dirty') is not False or build.get('version')!=package.get('version'):raise ValueError('SOURCE_IDENTITY_MISMATCH') + files={};total=0 + for file in application.rglob('*'): + if file.is_symlink(): + if not file.resolve().is_relative_to(application.resolve()):raise ValueError('EXTERNAL_LINK') + continue + if not (file.is_file() or file.is_dir()):raise ValueError('SPECIAL_FILE') + if file.is_file(): + name=str(file.relative_to(application));total+=file.stat().st_size + if len(files)>=30000 or total>512*1024**2 or len(name.encode())>1024:raise ValueError('ARTIFACT_CAPACITY') + files[name]=digest(file) + prefix='Contents/Resources/runtime/' + actual={name[len(prefix):]:value for name,value in files.items() if name.startswith(prefix) and name!=prefix+'runtime-manifest.json'} + if actual!=runtime.get('files'):raise ValueError('RUNTIME_BYTES_CHANGED') + return {'schema':'skillsync.application-release/v1','version':package['version'],'architecture':runtime['architecture'],'sourceCommit':revision,'minimumSystemVersion':runtime['minimumSystemVersion'],'archive':archive.name,'sha256':digest(archive),'signing':'ad-hoc','notarized':False,'validation':'file hashes; verify published workflow provenance separately','bytes':total,'files':files} +def main(): + p=argparse.ArgumentParser();p.add_argument('--application',type=Path,required=True);p.add_argument('--archive',type=Path,required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args() + value=create(a.application,a.archive) + with scoped(a.output).open('x') as stream:stream.write(json.dumps(value,sort_keys=True,indent=2)+'\n') +if __name__=='__main__':main() diff --git a/desktop/build_app.py b/desktop/build_app.py index 0a1e28f..e7e506d 100644 --- a/desktop/build_app.py +++ b/desktop/build_app.py @@ -12,6 +12,18 @@ ROOT = Path(__file__).resolve().parents[1] +def validate_portable_profile(config): + expected = { + 'executable': '{{RESOURCES}}/runtime/bin/node', + 'workingDirectory': '{{RESOURCES}}/runtime/app', + 'arguments': ['{{RESOURCES}}/runtime/app/dist/cli/index.js', 'gui', '--state-dir', + '{{HOME}}/Library/Application Support/SkillSync/workspace', '--port', str(config['port'])], + 'smokeArguments': ['{{RESOURCES}}/runtime/app/dist/cli/index.js', 'gui', '--state-dir', + '{{SMOKE_DIR}}/state', '--port', str(config['smokePort'])], + } + if config.get('product') != 'skillsync' or any(config.get('launch', {}).get(key) != value for key, value in expected.items()): + raise ValueError('PORTABLE_LAUNCH_PROFILE_INVALID') + def main(): parser = argparse.ArgumentParser() parser.add_argument('--output', type=Path, default=ROOT / 'desktop/build') @@ -21,6 +33,8 @@ def main(): if sys.platform != 'darwin': raise SystemExit('MACOS_BUILD_REQUIRED') config = json.loads((ROOT / ('desktop/portable.json' if args.runtime else 'desktop/app.json')).read_text()) + if args.runtime: + validate_portable_profile(config) dirty = bool(subprocess.check_output(['git','status','--porcelain'],cwd=ROOT,text=True).strip()) if dirty and not args.preview: raise SystemExit('CLEAN_SOURCE_REQUIRED; use --preview only for local review') @@ -72,10 +86,11 @@ def main(): binary = app / 'Contents/MacOS/Workspace' resources = app / 'Contents/Resources' binary.parent.mkdir(parents=True); resources.mkdir() + product_version = json.loads((ROOT / 'package.json').read_text())['version'] info = {'CFBundleIdentifier': config['identifier'], 'CFBundleName': config['name'], 'CFBundleDisplayName': config['name'], 'CFBundleExecutable': 'Workspace', - 'CFBundlePackageType': 'APPL', 'CFBundleIconFile': 'AppIcon', 'CFBundleShortVersionString': '1.0.0', - 'CFBundleVersion': '1', 'LSMinimumSystemVersion': '13.0', + 'CFBundlePackageType': 'APPL', 'CFBundleIconFile': 'AppIcon', 'CFBundleShortVersionString': product_version, + 'CFBundleVersion': product_version, 'LSMinimumSystemVersion': '13.0', 'NSHighResolutionCapable': True, 'NSAppTransportSecurity': {'NSAllowsLocalNetworking': True}} (app / 'Contents/Info.plist').write_bytes(plistlib.dumps(info)) @@ -95,6 +110,8 @@ def resolve(value): raise SystemExit('RUNTIME_MANIFEST_REQUIRED') import hashlib manifest = json.loads((runtime / 'runtime-manifest.json').read_text()) + if manifest.get('architecture') != platform.machine(): + raise SystemExit('RUNTIME_ARCHITECTURE_MISMATCH') if manifest.get('sourceCommit') != installed['sourceCommit'] or manifest.get('includesWorkingTreeChanges') != dirty: raise SystemExit('RUNTIME_SOURCE_IDENTITY_MISMATCH') paths = list(runtime.rglob('*')) diff --git a/desktop/prepare_runtime.py b/desktop/prepare_runtime.py index 99ab624..776b401 100644 --- a/desktop/prepare_runtime.py +++ b/desktop/prepare_runtime.py @@ -12,6 +12,12 @@ ROOT = Path(__file__).resolve().parents[1] +def validate_node_license(path, prefix=None): + if (path.is_symlink() or not path.is_file() or not 1 <= path.stat().st_size <= 4 * 1024 * 1024 + or (prefix is not None and not path.resolve().is_relative_to(prefix.resolve()))): + raise ValueError('NODE_LICENSE_INVALID') + return path + def declared_minimum(text): # vtool also prints linker/tool versions. They are not OS deployment targets. @@ -41,6 +47,12 @@ def main(): parser.add_argument('--output', type=Path, required=True) parser.add_argument('--node-license', type=Path, help='Full upstream license for the installed Node runtime') args = parser.parse_args() + revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip() + dirty = bool(subprocess.check_output(['git', 'status', '--porcelain'], cwd=ROOT, text=True).strip()) + info = json.loads((ROOT / 'dist/build-info.json').read_text()) + version = json.loads((ROOT / 'package.json').read_text())['version'] + if info.get('schema') != 'skillsync.build-info/v1' or info.get('version') != version or info.get('sourceRevision') != revision or info.get('dirty') != dirty: + raise SystemExit('RUNTIME_BUILD_IDENTITY_MISMATCH') profile = json.loads((ROOT / 'desktop/portable.json').read_text()) product = profile['product'] output = args.output.expanduser().absolute() @@ -66,6 +78,10 @@ def copy(relative, destination=None): node = shutil.which('node') if not node: raise SystemExit('NODE_REQUIRED') + node_version = subprocess.check_output([node, '--version'], text=True, timeout=10).strip() + node_architecture = subprocess.check_output([node, '-p', 'process.arch'], text=True, timeout=10).strip() + if {'arm64': 'arm64', 'x86_64': 'x64'}.get(platform.machine()) != node_architecture: + raise SystemExit('NODE_ARCHITECTURE_MISMATCH') (output / 'bin').mkdir() shutil.copy2(node, output / 'bin/node') for relative in ['package.json', 'package-lock.json']: @@ -77,9 +93,10 @@ def copy(relative, destination=None): subprocess.run(['npm', 'ci', '--omit=dev', '--ignore-scripts', '--no-audit', '--no-fund'], cwd=app, check=True) node_prefix = Path(node).resolve().parent.parent candidates = [args.node_license] if args.node_license else [node_prefix / 'LICENSE', node_prefix / 'share/doc/node/LICENSE', node_prefix / 'share/doc/nodejs/LICENSE'] - license_root = next((path for path in candidates if path and path.is_file()), Path('/nonexistent-node-license')) - if not license_root.is_file(): + license_root = next((path for path in candidates if path and path.is_file()), None) + if license_root is None: raise SystemExit('NODE_LICENSE_REQUIRED') + validate_node_license(license_root, None if args.node_license else node_prefix) shutil.copy2(license_root, output / 'bin/NODE-LICENSE.txt') if (ROOT / 'desktop/runtime-licenses').is_dir(): @@ -94,9 +111,7 @@ def copy(relative, destination=None): manifest = {str(p.relative_to(output)): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(output.rglob('*')) if p.is_file() and not p.is_symlink()} minimum, deployments = minimum_macos(output) - revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip() - dirty = bool(subprocess.check_output(['git', 'status', '--porcelain'], cwd=ROOT, text=True).strip()) - (output / 'runtime-manifest.json').write_text(json.dumps({'schema': 'runtime-files/v1', 'product': product, 'sourceCommit': revision, 'includesWorkingTreeChanges': dirty, 'minimumSystemVersion': minimum, 'binaryDeploymentTargets': deployments, 'files': manifest}, indent=2) + '\n') + (output / 'runtime-manifest.json').write_text(json.dumps({'schema': 'runtime-files/v1', 'product': product, 'architecture': platform.machine(), 'nodeVersion': node_version, 'nodeLicenseSha256': manifest['bin/NODE-LICENSE.txt'], 'sourceCommit': revision, 'includesWorkingTreeChanges': dirty, 'minimumSystemVersion': minimum, 'binaryDeploymentTargets': deployments, 'files': manifest}, indent=2) + '\n') print(json.dumps({'product': product, 'files': len(manifest), 'runtime': str(output)})) diff --git a/desktop/tests/test_application_manifest.py b/desktop/tests/test_application_manifest.py new file mode 100644 index 0000000..392a450 --- /dev/null +++ b/desktop/tests/test_application_manifest.py @@ -0,0 +1,28 @@ +import hashlib,importlib.util,json,tempfile,unittest +from contextlib import chdir +from pathlib import Path +from unittest import mock +spec=importlib.util.spec_from_file_location('sync_application_manifest',Path(__file__).resolve().parents[1]/'application_manifest.py');module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) +class ManifestTests(unittest.TestCase): + def fixture(self,root): + app=root/'SkillSync.app';resources=app/'Contents/Resources';runtime=resources/'runtime';dist=runtime/'app/dist';dist.mkdir(parents=True) + (resources/'app.json').write_text(json.dumps({'sourceCommit':'a'*40,'includesWorkingTreeChanges':False})) + (runtime/'app/package.json').write_text(json.dumps({'version':'0.4.0'})) + (dist/'build-info.json').write_text(json.dumps({'version':'0.4.0','sourceRevision':'a'*40,'dirty':False})) + files={str(p.relative_to(runtime)):hashlib.sha256(p.read_bytes()).hexdigest() for p in runtime.rglob('*') if p.is_file()} + (runtime/'runtime-manifest.json').write_text(json.dumps({'sourceCommit':'a'*40,'includesWorkingTreeChanges':False,'minimumSystemVersion':'13.5','architecture':'arm64','files':files})) + archive=root/'application.zip';archive.write_bytes(b'owned zip fixture');return app,archive,dist + def test_nonexecuting_same_source_inventory_and_changed_bytes(self): + with tempfile.TemporaryDirectory() as temporary,chdir(temporary): + app,archive,dist=self.fixture(Path(temporary)) + with mock.patch('subprocess.Popen',side_effect=AssertionError('must not execute app code')):data=module.create(app,archive) + self.assertEqual(data['version'],'0.4.0');self.assertFalse(data['notarized']) + (dist/'changed.txt').write_text('unrecognized file') + with self.assertRaisesRegex(ValueError,'BYTES_CHANGED'):module.create(app,archive) + def test_outside_context_and_external_links_fail(self): + with tempfile.TemporaryDirectory() as temporary,tempfile.TemporaryDirectory() as outside,chdir(temporary): + app,archive,dist=self.fixture(Path(outside)) + with self.assertRaisesRegex(ValueError,'OUTSIDE_INVOCATION_ROOT'):module.create(app,archive) + app,archive,dist=self.fixture(Path(temporary));(dist/'link').symlink_to(outside,target_is_directory=True) + with self.assertRaisesRegex(ValueError,'EXTERNAL_LINK'):module.create(app,archive) +if __name__=='__main__':unittest.main() diff --git a/desktop/tests/test_portable_boundaries.py b/desktop/tests/test_portable_boundaries.py new file mode 100644 index 0000000..ca57166 --- /dev/null +++ b/desktop/tests/test_portable_boundaries.py @@ -0,0 +1,39 @@ +import importlib.util +from pathlib import Path +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +def load(name): + spec = importlib.util.spec_from_file_location(name, ROOT / (name + '.py')) + module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module) + return module + +class PortableBoundaries(unittest.TestCase): + def test_portable_profile_cannot_launch_source_or_external_program(self): + import copy, json + builder = load('build_app') + profile = json.loads((ROOT / 'portable.json').read_text()) + builder.validate_portable_profile(profile) + for key, value in [('executable', '/tmp/foreign-node'), ('workingDirectory', '/tmp/foreign'), ('arguments', ['/tmp/foreign.js']), ('smokeArguments', ['/tmp/foreign.js'])]: + changed = copy.deepcopy(profile); changed['launch'][key] = value + with self.assertRaisesRegex(ValueError, 'PORTABLE_LAUNCH_PROFILE_INVALID'): + builder.validate_portable_profile(changed) + def test_node_license_is_bounded_regular_file_and_inside_detected_prefix(self): + runtime = load('prepare_runtime') + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary); prefix = root / 'node'; prefix.mkdir() + license = prefix / 'LICENSE'; license.write_text('upstream Node license') + self.assertEqual(runtime.validate_node_license(license, prefix), license) + link = prefix / 'linked'; link.symlink_to(license) + with self.assertRaisesRegex(ValueError, 'NODE_LICENSE_INVALID'): + runtime.validate_node_license(link, prefix) + outside = root / 'external'; outside.write_text('outside') + with self.assertRaisesRegex(ValueError, 'NODE_LICENSE_INVALID'): + runtime.validate_node_license(outside, prefix) + for contents in ['', 'x' * (4 * 1024 * 1024 + 1)]: + license.write_text(contents) + with self.assertRaisesRegex(ValueError, 'NODE_LICENSE_INVALID'): + runtime.validate_node_license(license, prefix) + +if __name__ == '__main__': unittest.main() diff --git a/docs/build.md b/docs/build.md index 0a87820..d1e5204 100644 --- a/docs/build.md +++ b/docs/build.md @@ -44,3 +44,5 @@ npm test 如果 Node 安装方式没有在标准位置保存完整许可,可给 prepare_runtime.py 传入 --node-license /path/to/official/NODE-LICENSE.txt,文件必须对应实际运行时版本。 运行包从实际 Mach-O 部署目标计算最低系统版本,当前 Apple Silicon 包最低 macOS 13.5。嵌入的 Node 运行时最低13.5;源码 package.json 的 >=20 是库兼容下限,此桌面构建固定使用 Node 24。具体下载以 source-manifest.json 与应用信息为准。本机验收不等于其他系统版本已实机验收。 + +正式GitHub发行从准确main成功检查和不可变版本标签构建CLI及Apple Silicon可移动程序。原生包用临时签名,不宣称Apple公证;实际最低系统版本以运行时Mach-O清单为准。检查程序清单只读文件哈希,不执行待检查App。 diff --git a/docs/repair-recovery.md b/docs/repair-recovery.md index 9e81249..58122bb 100644 --- a/docs/repair-recovery.md +++ b/docs/repair-recovery.md @@ -32,3 +32,15 @@ CLI默认使用 `~/.skillsync/repair-backups`。工作台使用其私有状态 报告数据和索引分别以完整文件发布;索引只有在写入并同步后才发布。中断、存储不足或索引失败的材料保留在状态目录,历史栏显示“未完成或无法读取”,不计入完成记录,也不会自动变成可应用计划。它们仍占用容量,这是保护恢复材料的设计;请先归档核对,再使用新的状态目录。 文件同步改善突然退出时的恢复条件,但不是对断电、介质损坏或所有文件系统的零丢失保证;Windows的Node接口不提供相同的目录同步能力。唯一资料仍应有独立、加密并验证过的备份。 + +## 核验台:检查、恢复、查回与核验 + +1. 选择并核验原 Skill 目录,展开“检查备份与恢复副本”。列表只读取元数据,尚未验证文件正文。 +2. 选择备份并检查。新备份带本机目录绑定;旧 v1 清单保持兼容,须选择当前目录的原修复计划以核对 planDigest。其它目录的备份不能用于当前恢复。 +3. 核对文件数量与范围后选择“确认恢复到新副本”。备份中的文件恢复为修复前版本,其它文件使用当前目录内容;这不是整个目录的历史时间点快照。原目录不被覆盖。源内容、权限或目录身份变化会使十分钟内的一次确认失效。 +4. 副本完成后只读核验,再下载 JSON。该结果只属于副本,可能重新出现修复前的警告;原计划不会重新激活,当前选择不自动切换。报告中的本机路径继续脱敏,另由副本 ID 和摘要绑定。 +5. 刷新、断网或响应未确认时先读取当前目录的已有恢复操作、查询原编号;查询不会新建副本或覆盖“上次恢复”状态。 + +私有状态目录的 `recovery-copies` 最多保留4份完整或不完整材料,每份工作区最多64 MiB/10,000文件。取消保留 `INCOMPLETE`,它不算成功。不会自动淘汰旧副本;达到上限先人工核对并归档再移走对应恢复文件夹。完成后的私有副本按冻结恢复结果检查,内容或权限变化不再当作原恢复结果。若要继续编辑,先复制到自己的项目目录,再作为普通目录选择;保留原恢复证据。 + +本机目录绑定与摘要不认证作者,也不隔离同一 OS 用户的恶意进程。旧历史、原清单、原目录、捕获/回滚材料及未知状态均保留。 diff --git a/package-lock.json b/package-lock.json index 64444d9..ad47ba7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@chumanic/skillsync", - "version": "0.3.0", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@chumanic/skillsync", - "version": "0.3.0", + "version": "0.4.0", "license": "MIT", "dependencies": { "commander": "^13.1.0", diff --git a/package.json b/package.json index 2ee9488..85265d2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@chumanic/skillsync", - "version": "0.3.0", + "version": "0.4.0", "private": false, "publishConfig": { "access": "public" diff --git a/src/capabilities.ts b/src/capabilities.ts index 6071ca2..1cf7db6 100644 --- a/src/capabilities.ts +++ b/src/capabilities.ts @@ -2,7 +2,7 @@ export const CURRENT_CAPABILITIES = [ "static-verification/v1", "sarif-report/v1", "junit-report/v1", "acceptance-batches/v1", "workbench-operation-tracking/v1", - "scoped-operation-cancel/v1", "pinned-ci-source/v1", + "retained-repair-recovery/v1", "scoped-operation-cancel/v1", "pinned-ci-source/v1", ] as const; export const DEFAULT_NPM_VERSION = "0.1.0"; export const CHANNEL_OBSERVATION = { diff --git a/src/domain/patch-application.ts b/src/domain/patch-application.ts index e9669b1..840d69f 100644 --- a/src/domain/patch-application.ts +++ b/src/domain/patch-application.ts @@ -315,7 +315,8 @@ export async function applyActionPlan( } if (options.backupDirectory && isWithinRoot(rootPath, resolve(options.backupDirectory))) throw new Error("Repair backups must be outside the Skill directory."); - const retained = await createRepairBackup(prepared, plan.planDigest, options.backupDirectory); + const scopeInfo = await stat(rootPath); + const retained = await createRepairBackup(prepared, plan.planDigest, options.backupDirectory, {rootPath,rootIdentity:`${scopeInfo.dev}:${scopeInfo.ino}`}); const temporaryBackupPath = retained.directory; const backups: Backup[] = prepared.map(item => ({ ...item, backupFilePath: join(retained.directory, 'files', item.normalizedPath) })); diff --git a/src/domain/repair-backups.ts b/src/domain/repair-backups.ts index 304d479..ffc03bb 100644 --- a/src/domain/repair-backups.ts +++ b/src/domain/repair-backups.ts @@ -16,6 +16,7 @@ const manifestSchema = z.object({ schema: z.literal('skillsync.repair-backup/v1' sha256: z.string().regex(/^[a-f0-9]{64}$/), mode: z.number().int().min(0).max(0o777) }).strict()).max(WORKSPACE_TREE_LIMITS.maxFiles), }).strict(); export type RepairBackupFile = { normalizedPath: string; content: string; mode: number }; +export const repairScopeSchema = z.object({ schema:z.literal('skillsync.repair-scope/v1'), rootPath:z.string().min(1).max(4096), rootIdentity:z.string().regex(/^\d+:\d+$/), planDigest:z.string().min(1).max(128) }).strict(); export async function syncDirectory(path: string): Promise { // Windows does not expose a portable directory-fsync operation through Node. if (process.platform === 'win32') return; @@ -31,7 +32,7 @@ export async function validateRepairBackupRoot(path: string): Promise { ((info.mode & 0o077) !== 0 || typeof process.getuid === 'function' && info.uid !== process.getuid())) throw new Error('Repair backups require an owned private directory.'); return realpath(path); } -export async function createRepairBackup(files: RepairBackupFile[], planDigest: string, selectedRoot?: string) { +export async function createRepairBackup(files: RepairBackupFile[], planDigest: string, selectedRoot?: string, scope?: { rootPath:string; rootIdentity:string }) { const raw = resolve(selectedRoot ?? join(homedir(), '.skillsync', REPAIR_BACKUP_FOLDER)); await mkdir(raw, { recursive: true, mode: 0o700 }); const root = await validateRepairBackupRoot(raw); @@ -60,6 +61,7 @@ export async function createRepairBackup(files: RepairBackupFile[], planDigest: const directory = join(slot, randomUUID()); try { await mkdir(directory, { mode: 0o700 }); + if (scope) await writeSyncedFile(join(directory, 'scope.json'), JSON.stringify(repairScopeSchema.parse({schema:'skillsync.repair-scope/v1',...scope,planDigest}))); for (const file of files) { const path = join(directory, 'files', file.normalizedPath); await mkdir(dirname(path), { recursive: true, mode: 0o700 }); @@ -73,7 +75,7 @@ export async function createRepairBackup(files: RepairBackupFile[], planDigest: await rm(slot, { recursive: true, force: true }); throw error; } } -export async function inspectRepairBackup(input: string) { +export async function readRepairBackupHeader(input: string) { const directory = await validateRepairBackupRoot(resolve(input)); const manifest = manifestSchema.parse(parseStrictJson(await readWorkspaceText(join(directory, 'manifest.json'), MAX_MANIFEST_BYTES))); const paths = new Set(); let bytes = 0; @@ -81,10 +83,20 @@ export async function inspectRepairBackup(input: string) { if (normalizeRelativePath(file.path) !== file.path || paths.has(file.path)) throw new Error('Invalid repair backup manifest.'); paths.add(file.path); bytes += file.bytes; if (bytes > WORKSPACE_TREE_LIMITS.maxTotalBytes) throw new Error('Repair backup exceeds the workspace limit.'); + } + return { directory, manifest, bytes }; +} +export async function readRepairBackup(input: string) { + const {directory,manifest,bytes}=await readRepairBackupHeader(input); + for (const file of manifest.files) { const path = join(directory, 'files', file.path); if (await realpath(path) !== path) throw new Error('Linked repair backup material is not accepted.'); const content = await readWorkspaceFile(path, WORKSPACE_TREE_LIMITS.maxFileBytes); if (content.length !== file.bytes || sha(content) !== file.sha256) throw new Error('Repair backup checksum or size mismatch.'); } + return { directory, manifest, bytes }; +} +export async function inspectRepairBackup(input: string) { + const {manifest,bytes}=await readRepairBackup(input); return { schema: 'skillsync.repair-backup-check/v1', status: 'verified', planDigest: manifest.planDigest, files: manifest.files.length, bytes, sourceAuthentication: 'not-authenticated' }; } diff --git a/src/workbench/history.ts b/src/workbench/history.ts index 3faaa01..fbb7491 100644 --- a/src/workbench/history.ts +++ b/src/workbench/history.ts @@ -45,10 +45,10 @@ export class WorkbenchHistory { private async entries() { const root = await lstat(this.root); if (!root.isDirectory() || root.isSymbolicLink() || identity(root)!==this.rootIdentity || await realpath(this.root)!==this.root) throw new WorkbenchStateError("状态目录已变化,请停止操作并检查原目录。"); - const entries = await readDirectoryEntries(this.root, MAX_FILES + 1); + const entries = await readDirectoryEntries(this.root, MAX_FILES + 2); let bytes = 0; const reports = []; for (const entry of entries) { - if (entry.name === REPAIR_BACKUP_FOLDER) { await validateRepairBackupRoot(join(this.root, entry.name)); continue; } + if (entry.name === REPAIR_BACKUP_FOLDER || entry.name === "recovery-copies") { await validateRepairBackupRoot(join(this.root, entry.name)); continue; } reports.push(entry); const info = await lstat(join(this.root,entry.name)); if (!info.isFile() || info.isSymbolicLink()) throw new WorkbenchStateError("状态目录包含非普通文件,请检查;原结果未删除。"); @@ -122,6 +122,11 @@ export class WorkbenchHistory { const record=await this.metadata(id); return {record,output:await this.output(record)}; } + async repairPlans(selection:Selection) { + const {entries}=await this.entries(),result:Array<{id:string;createdAt:string}>=[]; + for(const entry of entries){if(!/^[a-f0-9-]{36}-history\.json$/.test(entry.name))continue;try{const record=await this.metadata(entry.name.slice(0,-13));if(record.kind==='plan'&&record.selection.path===selection.path&&record.selection.identity===selection.identity&&record.selection.kind===selection.kind)result.push({id:record.id,createdAt:record.createdAt});}catch{/* Incomplete records remain visible separately. */}} + return result.sort((a,b)=>b.createdAt.localeCompare(a.createdAt)).slice(0,16); + } private async output(record:HistoryRecord) { const output=record.dataFile?await readWorkspaceText(join(this.root,record.dataFile),MAX_OUTPUT):undefined; if(output!==undefined && sha(output)!==record.dataSha256)throw new Error("历史材料摘要不匹配。"); diff --git a/src/workbench/page.ts b/src/workbench/page.ts index 2b12c26..ea8a7ff 100644 --- a/src/workbench/page.ts +++ b/src/workbench/page.ts @@ -5,10 +5,13 @@ export function workbenchPage(nonce: string): string {

核验一个目录

只读检查
  1. 01选择范围
  2. 02查看结论
  3. 03保存证据
选择要完成的任务

后台操作

正在核对后台状态…

尚未核验

+

检查备份与恢复副本

需要恢复修复前文件时展开

检查已保留的修复原件,在新副本中恢复并重新核验。当前目录不被覆盖;副本可能重新出现修复前的问题。

只检查本机文件,不运行 Skill。

报告保存位置

报告、计划和回执保存在本机私有目录;历史功能启用前的文件仍保留。

`; } export const workbenchStyle = ` +#repair-recovery{min-width:0}#repair-recovery select{width:100%;min-height:44px}#repair-report{width:100%;min-height:420px;border:1px solid var(--line);border-radius:8px}#repair-recovery p{overflow-wrap:anywhere}@media(min-width:1100px){#repair-recovery{grid-column:1/-1}} + :root{color-scheme:light;font:14px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC",sans-serif;color:#242424;background:#fff;--line:#e8e8e4;--muted:#686862;--sidebar:#f6f6f4;--panel:#fafaf9}*{box-sizing:border-box}body{margin:0}a{color:inherit;text-decoration:none}[hidden]{display:none!important}button,input,select,textarea{font:inherit;touch-action:manipulation;max-width:100%}button{min-height:38px;padding:8px 14px;border:1px solid #d4d4ce;border-radius:8px;color:#292929;background:#fff;cursor:pointer;transition:background-color .18s,border-color .18s}button:hover{background:#efefea}button:disabled{opacity:.5;cursor:default}button.primary{background:#292929;border-color:#292929;color:#fff}button.primary:hover{background:#444}.workspace-shell{display:grid;grid-template-columns:244px minmax(0,1fr);min-height:100dvh}.app-sidebar{position:sticky;top:0;display:flex;flex-direction:column;height:100dvh;padding:24px 14px 16px;background:var(--sidebar);border-right:1px solid var(--line)}.app-brand{display:flex;align-items:center;gap:10px;padding:0 9px 18px;font-size:15px;letter-spacing:-.02em}.sidebar-label{padding:0 10px;margin:16px 0 10px;font-size:12px;color:var(--muted)}.task-nav{display:grid;gap:5px}.task-nav button{width:100%;text-align:left;justify-content:flex-start;border-color:transparent;background:transparent;font-size:13px}.task-nav button:hover{background:#edede8}.task-nav button[aria-pressed=true]{background:#e7e7e2;color:#242424;font-weight:500}.sidebar-bottom{display:grid;gap:3px;margin-top:auto;padding:14px 10px 0;border-top:1px solid var(--line);font-size:12px}.sidebar-bottom small{font-size:11px;color:var(--muted)}.workspace-main{min-width:0}.workspace-bar{height:59px;display:flex;align-items:center;justify-content:space-between;gap:16px;padding:0 32px;border-bottom:1px solid var(--line);font-size:13px}.workspace-status{font-size:12px;color:var(--muted)}main{padding:38px 40px;max-width:1120px;margin:auto;min-width:0}.page-heading{margin-bottom:30px}.page-heading h1{margin:0 0 12px;font-size:26px;line-height:1.35;font-weight:600;letter-spacing:-.04em}.page-heading p{margin:0;max-width:650px;color:var(--muted)}section{min-width:0;padding:24px;margin-bottom:22px;border:1px solid var(--line);border-radius:10px;background:#fff}h2{margin:0 0 14px;font-size:18px;font-weight:600;letter-spacing:-.02em}h3{font-size:15px;font-weight:600}.task-steps{font-size:12px;color:var(--muted)}label{display:block;margin:18px 0 8px;font-size:13px}input,select{width:100%;min-width:0;min-height:42px;padding:9px 12px;border:1px solid #d4d4ce;border-radius:8px;background:#fff;color:#242424}input::placeholder{color:var(--muted)}input[type=checkbox],input[type=radio]{width:18px;min-height:18px;accent-color:#292929;vertical-align:middle}input[type=checkbox]{margin-right:8px}.row{display:flex;gap:10px;align-items:center}.row input{flex:1;min-width:0}.row button{white-space:nowrap}.actions{flex-wrap:wrap;margin-top:18px}:focus-visible{outline:2px solid #777772;outline-offset:3px}iframe{width:100%;height:min(70vh,580px);border:1px solid var(--line);border-radius:8px;margin:18px 0}pre{white-space:pre-wrap;overflow-wrap:anywhere;font:12px/1.75 ui-monospace,SFMono-Regular,monospace;max-height:440px;overflow:auto;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:16px}#history-list p,#batch-receipt,#batch-info,p,li,code{overflow-wrap:anywhere}footer{font-size:12px;color:var(--muted);padding:4px 0 16px}footer p{margin:8px 0}summary{cursor:pointer;min-height:36px;padding:6px 0}.operation-status{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:24px}.operation-status button{flex-shrink:0}#status{padding:12px 0;color:var(--muted)}.selection-options{border:0;padding:0;display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:22px}.selection-options label{display:flex;align-items:flex-start;gap:10px;border:1px solid var(--line);border-radius:8px;padding:15px;margin:0;background:var(--panel)}.selection-options label:has(input:checked){border-color:#999991;background:#f0f0eb}.selection-options input[type=radio]{flex:0 0 18px;margin-top:4px}.selection-options small{display:block;color:var(--muted);font-size:12px}.field-error{color:#a33f3b;font-size:13px}.mode-help{background:var(--panel);padding:12px 14px;border-radius:8px;color:var(--muted)}.result-summary{padding:0;margin:16px 0}.result-summary ul{display:flex;gap:18px;flex-wrap:wrap;padding-left:20px}.result-summary .actions{margin-bottom:16px}.history-comparison{margin-top:24px;padding-top:20px;border-top:1px solid var(--line)}.history-comparison-counts{display:flex;gap:20px;flex-wrap:wrap}.history-comparison-counts div{min-width:100px}.history-comparison-counts dt{font-size:12px;color:var(--muted)}.history-comparison-counts dd{font-size:24px;margin:4px 0}.history-comparison ul{padding-left:20px}#history-list button{margin:4px}#structured-report{max-height:400px}.history-filters{display:grid;grid-template-columns:1fr 1fr;column-gap:16px}.history-filters .actions{grid-column:1/-1}.skip-link{position:fixed;left:10px;top:-80px;z-index:10;padding:10px 14px;background:#fff;border:1px solid var(--line);border-radius:8px}.skip-link:focus{top:10px} @media(max-width:980px){.workspace-shell{grid-template-columns:218px minmax(0,1fr)}main{padding:30px 26px}.row{flex-wrap:wrap}.row input{flex-basis:100%}} @media(max-width:720px){.workspace-shell{display:block}.app-sidebar{position:static;height:auto;padding:18px 16px}.app-brand{padding-bottom:0}.sidebar-label,.sidebar-bottom{display:none}.task-nav{grid-template-columns:repeat(3,minmax(0,1fr));margin-top:16px}.task-nav button{text-align:center;padding:8px;min-width:0;line-height:1.4}.workspace-bar{padding:0 20px;height:52px}main{padding:28px 20px}.page-heading h1{font-size:23px}section{padding:18px}.selection-options,.history-filters{grid-template-columns:1fr}.row{flex-wrap:wrap}.row input{flex-basis:100%}.operation-status{align-items:flex-start;flex-direction:column}button,input,select{min-height:44px}input,select{font-size:16px}.actions button{flex:1 1 120px}} @@ -50,17 +53,18 @@ const $ = id => document.getElementById(id); const nonce = document.querySelector('meta[name="client"]').content; let busy = false, planId = null, selected = null, baselineId = null, historyId = null, historyOffset = 0, historyTotal = 0, historyLoading = false, historyRefreshQueued = false, renderedHistory = null, batchReady=false, summaryCanPlan=false, recoveryPath=null; let localBusy=false,localApplying=false,checkingOperation=true,observedOperation=null,ownedOperationId=null,ownedOperationKind=null,operationTimer=null,operationController=null,operationReads=0,operationDisposed=false; -const trackedActions=new Set(['select','choose','verify','plan','apply','batch/preview','batch/run','batch/open','history/open','history/export']); -const operationLabels={select:'选择目录',choose:'选择文件',verify:'核验',plan:'准备处理计划',apply:'应用已确认修复',batch_preview:'预检多批次计划',batch_run:'逐批核验',batch_open:'只读复核包',history_open:'读取历史',history_export:'导出历史摘要'}; +const trackedActions=new Set(['repair/list','repair/check','repair/restore','repair/verify','select','choose','verify','plan','apply','batch/preview','batch/run','batch/open','history/open','history/export']); +const operationLabels={repair_status:'查询恢复材料',repair_list:'读取修复备份',repair_check:'检查备份',repair_restore:'恢复新副本',repair_verify:'核验恢复副本',select:'选择目录',choose:'选择文件',verify:'核验',plan:'准备处理计划',apply:'应用已确认修复',batch_preview:'预检多批次计划',batch_run:'逐批核验',batch_open:'只读复核包',history_open:'读取历史',history_export:'导出历史摘要'}; const operationUUID=value=>typeof value==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value); // Switching tasks hides existing controls; it never replaces form nodes or submits them. let historyFilters={query:''}; let historyCompareController=null,historyCompareSerial=0,historyCompareLoading=false; +let repairToken=null,repairCopyId=null,repairReport=null,repairPendingId=null,repairCopySnapshot=null; let activeTask='single', resultOwner='single', resultAvailable=false, fixAvailable=false; function syncWorkspace(){ for(const task of ['single','batch','history']){ $('task-'+task).hidden=task!==activeTask; $('nav-'+task).setAttribute('aria-pressed',String(task===activeTask)); } $('result').hidden=!resultAvailable||resultOwner!==activeTask; - $('fix').hidden=!fixAvailable||activeTask!=='single'; + $('fix').hidden=!fixAvailable||activeTask!=='single';$('repair-recovery').hidden=activeTask!=='single'; } function setTask(task){if(activeTask==='history'&&task!=='history')clearHistoryComparison();activeTask=task;syncWorkspace();if(!$('result').hidden&&reportHtml)mountReport();$(task==='single'?'selection':task==='batch'?'batch-title':'history-title').focus();} function revealResult(owner){resultOwner=owner;resultAvailable=true;syncWorkspace();if(activeTask===owner)$('result-title').focus();} @@ -91,10 +95,11 @@ function mountReport(){ function showReport(html){reportHtml=html.replaceAll('href="#','href="about:srcdoc#');if(!$('result').hidden)mountReport();} function clearReport(){ $('structured-report').textContent='打开一份已保存的核验记录后查看。';$('structured-details').open=false;summaryCanPlan=false;if(!reportHtml)return;reportHtml='';$('report').srcdoc='';} function status(text){ $('status').textContent = text; } -function renderLocks(){const value=localBusy||checkingOperation||Boolean(observedOperation)||Boolean(ownedOperationId),applying=localApplying; busy=value; ['guide-single','guide-batch','guide-history','verify','plan','result-recheck','result-details','mode-skill','mode-artifacts','reverify','choose','choose-contract','root','contract','kind','delivery','history-refresh','batch-plan','batch-preview','batch-recover','batch-output','batch-previous','batch-retry','batch-package','batch-digest','batch-open','choose-batch-plan','choose-batch-package'].forEach(id => $(id).disabled=value); $('batch-run').disabled=value||!batchReady; document.querySelectorAll('.history-open').forEach(button=>button.disabled=value||historyLoading); ['history-query','history-kind','history-exit','history-filter','history-clear','history-refresh'].forEach(id=>$(id).disabled=value||historyLoading); $('history-prev').disabled=value||historyLoading||historyOffset===0; $('history-next').disabled=value||historyLoading||historyOffset+12>=historyTotal; $('export-summary').disabled=value||!historyId;$('export-json').disabled=value||!historyId;$('load-example').disabled=value; $('cancel').disabled=checkingOperation||!(observedOperation?.cancellable||ownedOperationId&&['verify','plan','batch/run'].includes(ownedOperationKind)&&!applying); $('confirm').disabled=value||!planId; $('apply').disabled=value || !$('confirm').checked || !planId; $('plan').disabled=value||!selected||!summaryCanPlan; syncHistoryCompareControls(); document.querySelectorAll('.history-compare-pick').forEach(button=>button.disabled=value||historyLoading); } -function lock(value,applying=false){localBusy=value;localApplying=value&&applying;renderLocks();} +function renderLocks(){const value=localBusy||checkingOperation||Boolean(observedOperation)||Boolean(ownedOperationId),applying=localApplying; busy=value;syncRepairLocks(); ['guide-single','guide-batch','guide-history','verify','plan','result-recheck','result-details','mode-skill','mode-artifacts','reverify','choose','choose-contract','root','contract','kind','delivery','history-refresh','batch-plan','batch-preview','batch-recover','batch-output','batch-previous','batch-retry','batch-package','batch-digest','batch-open','choose-batch-plan','choose-batch-package'].forEach(id => $(id).disabled=value); $('batch-run').disabled=value||!batchReady; document.querySelectorAll('.history-open').forEach(button=>button.disabled=value||historyLoading); ['history-query','history-kind','history-exit','history-filter','history-clear','history-refresh'].forEach(id=>$(id).disabled=value||historyLoading); $('history-prev').disabled=value||historyLoading||historyOffset===0; $('history-next').disabled=value||historyLoading||historyOffset+12>=historyTotal; $('export-summary').disabled=value||!historyId;$('export-json').disabled=value||!historyId;$('load-example').disabled=value; $('cancel').disabled=checkingOperation||!(observedOperation?.cancellable||ownedOperationId&&['verify','plan','batch/run','repair/restore','repair/verify'].includes(ownedOperationKind)&&!applying); $('confirm').disabled=value||!planId; $('apply').disabled=value || !$('confirm').checked || !planId; $('plan').disabled=value||!selected||!summaryCanPlan; syncHistoryCompareControls(); document.querySelectorAll('.history-compare-pick').forEach(button=>button.disabled=value||historyLoading); } +function syncRepairLocks(){for(const id of ['repair-list','repair-choice','repair-legacy-plan','repair-return','repair-existing'])$(id).disabled=busy;$('repair-check').disabled=busy||!$('repair-choice').value;$('repair-restore').disabled=busy||!repairToken;$('repair-verify').disabled=busy||!repairCopyId;$('repair-download').disabled=busy||!repairReport;} +function lock(value,applying=false){localBusy=value;localApplying=value&&applying;renderLocks();syncRepairLocks();} function clearPlan(){$('fix-title').textContent='审阅修复计划';planId=null;$('confirm').checked=false;setFix(false);$('changes').textContent='';$('apply').disabled=true;} -function invalidate(){ $('structured-report').textContent='尚未核验';$('export-json').disabled=true; $('plan').disabled=true;$('plan').hidden=true;fieldError('root','');fieldError('contract','');selected=null; planId=null; baselineId=null; historyId=null; $('comparison').textContent=''; $('export-summary').disabled=true; hideResult(); setFix(false); $('confirm').checked=false; clearReport(); status('目录或模式已更改,请重新核验'); } +function invalidate(){clearRepair(); $('structured-report').textContent='尚未核验';$('export-json').disabled=true; $('plan').disabled=true;$('plan').hidden=true;fieldError('root','');fieldError('contract','');selected=null; planId=null; baselineId=null; historyId=null; $('comparison').textContent=''; $('export-summary').disabled=true; hideResult(); setFix(false); $('confirm').checked=false; clearReport(); status('目录或模式已更改,请重新核验'); } ['root','contract'].forEach(id=>$(id).addEventListener('input',()=>{invalidate();syncMode();})); ['kind','delivery'].forEach(id=>$(id).addEventListener('change',()=>{invalidate();syncMode();})); function syncMode(){const artifacts=$('kind').value==='artifacts';$('mode-skill').checked=!artifacts;$('mode-artifacts').checked=artifacts;$('contract-fields').hidden=!artifacts;$('root-label').textContent=artifacts?'交付目录':'Skill 根目录或包含 Skills 的目录';$('root').placeholder=artifacts?'/project/artifacts…':'/project/my-skill…';$('mode-help').textContent=artifacts?'需要交付目录和验收清单(YAML / JSON)。如使用 SkillTape 交付,请勾选 delivery.json 模式。':'首次使用建议选择直接包含 SKILL.md 的目录。这里只检查文件,不运行 Skill。';} @@ -124,6 +129,15 @@ $('apply').onclick=async()=>{ finally{lock(false);} }; +function clearRepair(){repairCopySnapshot=null;repairToken=null;repairCopyId=null;repairReport=null;$('repair-restore').disabled=true;$('repair-verify').disabled=true;$('repair-download').disabled=true;$('repair-report').hidden=true;$('repair-report').srcdoc='';$('repair-copy-path').textContent='';$('repair-scope').textContent='';} +$('repair-choice').onchange=()=>{clearRepair();$('repair-check').disabled=busy||!$('repair-choice').value;}; +$('repair-legacy-plan').onchange=()=>{clearRepair();syncRepairLocks();}; +$('repair-list').onclick=async()=>{if(busy)return;clearRepair();lock(true);try{if(!selected)throw new Error('请先选择并核验当前 Skill 目录。');const data=await api('repair/list');$('repair-choice').replaceChildren(new Option('选择一份备份',''));for(const item of data.items){const option=new Option((item.createdAt||'不完整材料')+' · '+item.state+(item.legacy?' · 旧版需原计划':''),item.id);option.disabled=item.state==='incomplete';$('repair-choice').add(option);}$('repair-legacy-plan').replaceChildren(new Option('旧版备份请选择原计划',''));for(const item of data.plans)$('repair-legacy-plan').add(new Option(item.createdAt,item.id));$('repair-existing').replaceChildren(new Option('选择已有恢复操作',''));for(const item of data.copies||[])$('repair-existing').add(new Option(item.createdAt+' · '+item.state,item.id));$('repair-scope').textContent=data.items.length?'请选择备份并检查;列表尚未验证文件正文。':'当前目录尚无保留的修复备份。';}catch(e){$('repair-scope').textContent=e.message;}finally{lock(false);}}; +$('repair-check').onclick=async()=>{if(busy||!$('repair-choice').value)return;clearRepair();lock(true);try{const data=await api('repair/check',{id:$('repair-choice').value,planHistoryId:$('repair-legacy-plan').value||undefined});repairToken=data.token;$('repair-scope').textContent='完整性已核对:'+data.files+' 文件 / '+data.bytes+' 字节。'+data.message;}catch(e){$('repair-scope').textContent=e.message;}finally{lock(false);$('repair-restore').disabled=!repairToken;}}; +$('repair-restore').onclick=async()=>{if(busy||!repairToken)return;const token=repairToken;repairToken=null;lock(true);$('repair-scope').textContent='正在创建新副本;原目录保留。';try{const pending=api('repair/restore',{token,confirm:true});repairPendingId=ownedOperationId;const data=await pending;repairCopyId=data.id;repairCopySnapshot=data.snapshot;$('repair-copy-path').textContent=data.path;$('repair-scope').textContent='副本已生成,尚未重新核验。备份文件为修复前版本,其他文件来自当前目录;原目录保持。';}catch(e){$('repair-scope').textContent=e.message+' 原操作可能保留不完整副本,请先核对后台状态和私有恢复目录,不要重复创建。';}finally{lock(false);$('repair-restore').disabled=true;$('repair-verify').disabled=!repairCopyId;}}; +$('repair-return').onclick=async()=>{if(busy)return;const id=$('repair-existing').value||repairPendingId||(observedOperation&&observedOperation.kind==='repair_restore'?observedOperation.id:null);if(!id){$('repair-scope').textContent='尚无待查恢复编号。刷新后可先读取后台操作。';return;}lock(true);try{const data=await api('repair/status',{id});if(data.status==='ready'){repairCopyId=data.id;repairCopySnapshot=data.snapshot;$('repair-copy-path').textContent=data.path;$('repair-scope').textContent='已查回原恢复副本,没有再创建;请只读核验。';}else{$('repair-scope').textContent=data.status==='modified'?'副本已变化,不能再作为原恢复结果。请保留材料并另行核对。':data.status==='incomplete'?'原恢复尚不完整,请保留私有恢复目录并核对,未创建另一副本。':'原编号未找到完成副本,请先核对后台状态。';}}catch(e){$('repair-scope').textContent=e.message;}finally{lock(false);$('repair-verify').disabled=!repairCopyId;}}; +$('repair-verify').onclick=async()=>{if(busy||!repairCopyId)return;const id=repairCopyId,path=$('repair-copy-path').textContent,snapshot=repairCopySnapshot;repairReport=null;$('repair-report').hidden=true;$('repair-report').srcdoc='';lock(true);try{const data=await api('repair/verify',{id});if(operationDisposed||repairCopyId!==id||data.id!==id||data.readOnly!==true||data.path!==path||typeof snapshot!=='string'||data.snapshot!==snapshot||!data.report||data.report.schema_version!==1||!Array.isArray(data.report.issues)||!Array.isArray(data.report.targets)||data.report.targets.length!==1||!(data.report.targets[0].path===path||data.report.targets[0].path==='')||typeof data.html!=='string'||data.html.length>8*1024*1024)throw new Error('副本核验回应未能绑定当前目录,已保留副本,未启用下载。');repairReport=data.report;$('repair-report').srcdoc=data.html;$('repair-report').hidden=false;$('repair-scope').textContent='副本核验报告已保存。结果仅属于此副本,当前选择未切换;副本中的问题仍需逐项处理。';await loadHistory(true);}catch(e){$('repair-scope').textContent=e.message;}finally{lock(false);$('repair-verify').disabled=!repairCopyId;$('repair-download').disabled=!repairReport;}}; +$('repair-download').onclick=()=>{if(!repairReport)return;const url=URL.createObjectURL(new Blob([JSON.stringify(repairReport,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='skillsync-recovery-verification.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}; function syncHistoryCompareControls(){ $('history-compare').disabled=busy||historyCompareLoading; $('history-compare-before').disabled=busy;$('history-compare-after').disabled=busy; @@ -223,7 +237,7 @@ async function checkOperation(reset=true){ if(operationDisposed||ownedOperationId)return;if(reset)operationReads=0;stopOperationPolling();operationController?.abort(); const controller=new AbortController();operationController=controller;operationReads++;checkingOperation=true;$('operation-check').disabled=true;renderLocks(); try{ - const value=await api('operation',{},controller.signal); + const value=await api('operation',{},controller.signal);if(value.last&&value.last.kind==='repair_restore')repairPendingId=value.last.id; if(operationController!==controller||controller.signal.aborted||operationDisposed||ownedOperationId)return; if(!validOperationStatus(value))throw new Error('后台状态回应无法核对,请重新打开核验台。'); checkingOperation=false;const previous=observedOperation; @@ -243,7 +257,7 @@ async function checkOperation(reset=true){ }finally{if(operationController===controller){operationController=null;$('operation-check').disabled=false;renderLocks();scheduleOperationPolling();}} } $('operation-check').onclick=()=>checkOperation(); -window.addEventListener('pagehide',()=>{operationDisposed=true;stopOperationPolling();operationController?.abort();operationController=null;ownedOperationId=null;ownedOperationKind=null;clearHistoryComparison();clearPlan();clearReport();hideResult();selected=null;baselineId=null;historyId=null;batchReady=false;}); +window.addEventListener('pagehide',()=>{operationDisposed=true;stopOperationPolling();operationController?.abort();operationController=null;ownedOperationId=null;ownedOperationKind=null;clearRepair();clearHistoryComparison();clearPlan();clearReport();hideResult();selected=null;baselineId=null;historyId=null;batchReady=false;}); window.addEventListener('pageshow',event=>{if(event.persisted){operationDisposed=false;localBusy=false;localApplying=false;ownedOperationId=null;ownedOperationKind=null;checkingOperation=true;void checkOperation();}}); document.addEventListener('visibilitychange',()=>{if(document.hidden){stopOperationPolling();operationController?.abort();operationController=null;}else if(!ownedOperationId)void checkOperation();}); syncWorkspace(); diff --git a/src/workbench/repair-recovery.ts b/src/workbench/repair-recovery.ts new file mode 100644 index 0000000..97a7d4c --- /dev/null +++ b/src/workbench/repair-recovery.ts @@ -0,0 +1,129 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { constants } from 'node:fs'; +import { chmod, lstat, mkdir, open, realpath, unlink } from 'node:fs/promises'; +import { join } from 'node:path'; +import { z } from 'zod'; +import { readRepairBackup, readRepairBackupHeader, repairScopeSchema, syncDirectory, validateRepairBackupRoot, writeSyncedFile } from '../domain/repair-backups.js'; +import { assertActionPlanIntegrity, type ActionPlan } from '../domain/action-plan.js'; +import { parseStrictJson } from '../domain/strict-json.js'; +import { readDirectoryEntries, readWorkspaceFile, readWorkspaceText, scanStagedWorkspace, WORKSPACE_TREE_LIMITS } from '../sandbox/workspace-tree.js'; +import { WorkbenchHistory, WorkbenchStateError, type Selection } from './history.js'; + +export const RECOVERY_COPIES_FOLDER='recovery-copies'; +const sha=(value:Buffer|string)=>createHash('sha256').update(value).digest('hex'); +const same=(a:Selection,b:Selection)=>a.path===b.path&&a.identity===b.identity&&a.kind===b.kind&&a.contract===b.contract&&a.delivery===b.delivery; +const selectionSchema=z.object({path:z.string().max(4096),identity:z.string().regex(/^\d+:\d+$/),kind:z.literal('skill'),contract:z.string().optional(),delivery:z.boolean()}).strict(); +const copySchema=z.object({schema:z.literal('skillsync.recovery-copy/v1'),id:z.string().uuid(),selection:selectionSchema,backupId:z.string().max(80),planDigest:z.string().max(128),sourceSnapshot:z.string().max(128),createdAt:z.string().datetime(),outputSnapshot:z.string().max(128).optional()}).strict(); +type Ready={token:string;selection:Selection;backupId:string;planDigest:string;manifestHash:string;snapshot:string;expiresAt:number;legacyPlan?:string}; +const idPattern=/^slot-(?:0\d|1[0-5])\/[a-f0-9-]{36}$/; +async function sourceSnapshot(root:string){ + const stamps:Array<[string,number,number,number,number,number]>=[]; + const tree=await scanStagedWorkspace(root,{inspectFile:async name=>{const info=await lstat(join(root,name));stamps.push([name,info.mode&0o777,info.dev,info.ino,info.mtimeMs,info.ctimeMs]);}}); + return {tree,digest:'sha256:'+sha(JSON.stringify([tree.digest,stamps.sort((a,b)=>a[0].localeCompare(b[0]))]))}; +} + +/** Metadata stays private. A repair restores originals into a new bounded copy, never the selected directory. */ +export class RepairRecovery { + private ready?:Ready; + constructor(private stateDir:string,private stateIdentity:string,private history:WorkbenchHistory){} + private async state(){const info=await lstat(this.stateDir);if(`${info.dev}:${info.ino}`!==this.stateIdentity||await validateRepairBackupRoot(this.stateDir)!==this.stateDir)throw new WorkbenchStateError('私有状态目录已变化,请保留原材料后重新打开。');} + private async selected(selection:Selection){const value=await lstat(selection.path);if(value.isSymbolicLink()||!value.isDirectory()||await realpath(selection.path)!==selection.path||`${value.dev}:${value.ino}`!==selection.identity)throw new WorkbenchStateError('所选目录已变化,请重新选择。');} + private async backup(id:unknown){ + await this.state();if(typeof id!=='string'||!idPattern.test(id))throw new WorkbenchStateError('备份编号无效。'); + const root=join(this.stateDir,'repair-backups');await validateRepairBackupRoot(root); + const [slot,name]=id.split('/');if(!z.string().uuid().safeParse(name).success)throw new WorkbenchStateError('备份编号无效。');await validateRepairBackupRoot(join(root,slot)); + return validateRepairBackupRoot(join(root,slot,name)); + } + private async scoped(directory:string,selection:Selection,planDigest:string,legacyPlan?:unknown){ + const exists=await lstat(join(directory,'scope.json')).then(()=>true).catch(error=>{if((error as NodeJS.ErrnoException).code==='ENOENT')return false;throw error;}); + if(exists){const scope=repairScopeSchema.parse(parseStrictJson(await readWorkspaceText(join(directory,'scope.json'),16384)));if(scope.rootPath!==selection.path||scope.rootIdentity!==selection.identity||scope.planDigest!==planDigest)throw new WorkbenchStateError('这份备份不属于当前目录。');return;} + if(typeof legacyPlan!=='string')throw new WorkbenchStateError('旧版备份需要选择当前目录的原修复计划后再核对。'); + const {record,output}=await this.history.read(legacyPlan); + if(record.kind!=='plan'||!same(record.selection,selection)||!output)throw new WorkbenchStateError('原计划与当前目录不匹配。'); + const plan=parseStrictJson(output) as ActionPlan;assertActionPlanIntegrity(plan); + if(plan.planDigest!==planDigest||plan.rootPath!==selection.path||plan.rootIdentity&&plan.rootIdentity!==selection.identity)throw new WorkbenchStateError('备份与原修复计划不匹配。'); + } + async list(selection:Selection){ + await this.state();const items:Array<{id:string;createdAt?:string;files?:number;bytes?:number;legacy:boolean;state:string}>=[]; + const root=join(this.stateDir,'repair-backups'); + try{await validateRepairBackupRoot(root);}catch(error){if((error as NodeJS.ErrnoException).code==='ENOENT')return {items,plans:await this.history.repairPlans(selection),copies:await this.references(selection)};throw error;} + for(const slot of await readDirectoryEntries(root,16)){ + if(!/^slot-(?:0\d|1[0-5])$/.test(slot.name)||!slot.isDirectory()||slot.isSymbolicLink())throw new WorkbenchStateError('备份目录包含未识别材料,原件已保留。'); + const folder=await validateRepairBackupRoot(join(root,slot.name)); + const children=await readDirectoryEntries(folder,1); + for(const child of children){ + const id=slot.name+'/'+child.name;if(!idPattern.test(id))throw new WorkbenchStateError('备份目录包含未识别材料,原件已保留。'); + const directory=await this.backup(id);let legacy=false; + try{const scope=repairScopeSchema.parse(parseStrictJson(await readWorkspaceText(join(directory,'scope.json'),16384)));if(scope.rootPath!==selection.path||scope.rootIdentity!==selection.identity)continue;} + catch(error){const missing=await lstat(join(directory,'scope.json')).then(()=>false).catch(e=>{if((e as NodeJS.ErrnoException).code==='ENOENT')return true;throw e;});if(missing)legacy=true;else throw error;} + try{const {manifest,bytes}=await readRepairBackupHeader(directory);items.push({id,createdAt:manifest.createdAt,files:manifest.files.length,bytes,legacy,state:'unchecked'});} + catch{items.push({id,legacy,state:'incomplete'});} + } + } + return {items,plans:await this.history.repairPlans(selection),copies:await this.references(selection)}; + } + async check(id:unknown,selection:Selection,legacyPlan?:unknown){ + if(selection.kind!=='skill')throw new WorkbenchStateError('恢复副本只用于当前选择的 Skill 目录。'); + await this.selected(selection); + const directory=await this.backup(id),data=await readRepairBackup(directory);await this.scoped(directory,selection,data.manifest.planDigest,legacyPlan); + const tree=await sourceSnapshot(selection.path); + this.ready={token:randomUUID(),selection:{...selection},backupId:id as string,planDigest:data.manifest.planDigest,manifestHash:sha(JSON.stringify(data.manifest)),snapshot:tree.digest,expiresAt:Date.now()+10*60_000,...(typeof legacyPlan==='string'?{legacyPlan}:{})}; + return {token:this.ready.token,files:data.manifest.files.length,bytes:data.bytes,snapshot:tree.digest,expiresAt:this.ready.expiresAt,sourceAuthentication:'not-authenticated',message:'副本中的备份文件恢复为修复前版本,其他文件使用当前目录内容;原目录保持。副本仍需重新核验。'}; + } + async restore(token:unknown,selection:Selection,operationId:string,cancelled:()=>boolean,finalizing:()=>void=()=>{}){ + const ready=this.ready;this.ready=undefined; + if(!ready||token!==ready.token||!same(ready.selection,selection)||ready.expiresAt<=Date.now())throw new WorkbenchStateError('恢复确认已过期或目录已切换,请重新检查备份。'); + const directory=await this.backup(ready.backupId),data=await readRepairBackup(directory); + await this.scoped(directory,selection,data.manifest.planDigest,ready.legacyPlan); + if(data.manifest.planDigest!==ready.planDigest||sha(JSON.stringify(data.manifest))!==ready.manifestHash)throw new WorkbenchStateError('备份已变化,请重新检查。'); + await this.selected(selection);const initial=await sourceSnapshot(selection.path); + if(initial.digest!==ready.snapshot)throw new WorkbenchStateError('当前目录已变化,请重新检查备份与范围。'); + const finalFiles=new Map(initial.tree.files.map(file=>[file.path,file.bytes]));for(const file of data.manifest.files)finalFiles.set('workspace/'+file.path,file.bytes); + if(finalFiles.size>WORKSPACE_TREE_LIMITS.maxFiles||[...finalFiles.values()].reduce((sum,value)=>sum+value,0)>WORKSPACE_TREE_LIMITS.maxTotalBytes)throw new WorkbenchStateError('恢复后的副本超过64MiB或文件数上限,请保留原材料并缩小范围。'); + const copies=join(this.stateDir,RECOVERY_COPIES_FOLDER);await mkdir(copies,{recursive:true,mode:0o700}); + await validateRepairBackupRoot(copies); + const entries=await readDirectoryEntries(copies,4);if(entries.some(e=>!/^slot-0[0-3]$/.test(e.name)))throw new WorkbenchStateError('恢复目录包含未识别材料,未删除任何文件。'); + let slot:string|undefined; + for(let i=0;i<4;i++){const value=join(copies,`slot-0${i}`);try{await mkdir(value,{mode:0o700});slot=value;break;}catch(error){if((error as NodeJS.ErrnoException).code!=='EEXIST')throw error;}} + if(!slot)throw new WorkbenchStateError('已保留4份恢复材料。请先核对并归档私有 recovery-copies 中的目录,原件不会自动淘汰。'); + const copy=join(slot,'workspace');await mkdir(copy,{mode:0o700}); + const metadata=copySchema.parse({schema:'skillsync.recovery-copy/v1',id:operationId,selection,backupId:ready.backupId,planDigest:ready.planDigest,sourceSnapshot:ready.snapshot,createdAt:new Date().toISOString()}); + await writeSyncedFile(join(slot,'META.json'),JSON.stringify(metadata));await writeSyncedFile(join(slot,'INCOMPLETE'),'retained recovery material');await syncDirectory(slot); + const stop=()=>{if(cancelled())throw new WorkbenchStateError('恢复已停止,原目录未改动;新目录中的不完整材料保留。');}; + try{await scanStagedWorkspace(selection.path,{inspectFile:async(name,content)=>{stop();const dest=join(copy,name);await mkdir(join(dest,'..'),{recursive:true,mode:0o700});const mode=(await lstat(join(selection.path,name))).mode&0o777;const file=await open(dest,'wx',0o600);try{await file.writeFile(content);await file.sync();}finally{await file.close();}await chmod(dest,mode);}});}catch(error){stop();throw error;} + for(const file of data.manifest.files){stop();const content=await readWorkspaceFile(join(directory,'files',file.path),WORKSPACE_TREE_LIMITS.maxFileBytes);if(content.length!==file.bytes||sha(content)!==file.sha256)throw new WorkbenchStateError('备份读取期间变化,恢复副本尚未完成。');const dest=join(copy,file.path);await mkdir(join(dest,'..'),{recursive:true,mode:0o700});const handle=await open(dest,constants.O_WRONLY|constants.O_TRUNC|constants.O_CREAT|(constants.O_NOFOLLOW??0),0o600);try{await handle.writeFile(content);await handle.sync();}finally{await handle.close();}await chmod(dest,file.mode);} + stop();if((await sourceSnapshot(selection.path)).digest!==ready.snapshot)throw new WorkbenchStateError('源目录在恢复期间变化,副本材料保留但不能当作完成。'); + await this.selected(selection);const restored=await sourceSnapshot(copy);stop(); + finalizing();await syncDirectory(copy);await writeSyncedFile(join(slot,'RESTORE.json'),JSON.stringify({...metadata,outputSnapshot:restored.digest}));await syncDirectory(slot);await unlink(join(slot,'INCOMPLETE'));await syncDirectory(slot); + return {id:operationId,path:copy,files:restored.tree.files.length,snapshot:restored.digest,originalUnchanged:true,requiresVerification:true}; + } + async references(selection:Selection){ + await this.state();const root=join(this.stateDir,RECOVERY_COPIES_FOLDER),items:Array<{id:string;createdAt:string;state:string}>=[]; + try{await validateRepairBackupRoot(root);}catch(error){if((error as NodeJS.ErrnoException).code==='ENOENT')return items;throw error;} + for(const entry of await readDirectoryEntries(root,4)){if(!/^slot-0[0-3]$/.test(entry.name))throw new WorkbenchStateError('恢复材料布局待核对。');const slot=await validateRepairBackupRoot(join(root,entry.name));try{const info=copySchema.parse(parseStrictJson(await readWorkspaceText(join(slot,'META.json'),32768)));if(same(info.selection,selection))items.push({id:info.id,createdAt:info.createdAt,state:await lstat(join(slot,'INCOMPLETE')).then(()=>'incomplete').catch(()=>'recorded')});}catch{/* Unknown partial material stays on disk and consumes its slot. */}} + return items; + } + async status(id:unknown,selection:Selection){ + await this.state();if(typeof id!=='string'||!z.string().uuid().safeParse(id).success)throw new WorkbenchStateError('恢复编号无效。'); + const root=join(this.stateDir,RECOVERY_COPIES_FOLDER); + try{await validateRepairBackupRoot(root);}catch(error){if((error as NodeJS.ErrnoException).code==='ENOENT')return {id,status:'not-found' as const};throw error;} + for(const entry of await readDirectoryEntries(root,4)){ + if(!/^slot-0[0-3]$/.test(entry.name))throw new WorkbenchStateError('恢复材料布局待核对。'); + const slot=await validateRepairBackupRoot(join(root,entry.name)); + const pending=copySchema.parse(parseStrictJson(await readWorkspaceText(join(slot,'META.json'),32768)));if(pending.id!==id)continue;if(!same(pending.selection,selection))throw new WorkbenchStateError('此恢复材料不属于当前选择。'); + const incomplete=await lstat(join(slot,'INCOMPLETE')).then(()=>true).catch(error=>{if((error as NodeJS.ErrnoException).code==='ENOENT')return false;throw error;}); + if(incomplete)return {id,status:'incomplete' as const,path:slot}; + const info=copySchema.parse(parseStrictJson(await readWorkspaceText(join(slot,'RESTORE.json'),32768))); + if(info.id!==id)throw new WorkbenchStateError('恢复结果编号不匹配。');if(!same(info.selection,selection))throw new WorkbenchStateError('此副本不属于当前选择。'); + const path=join(slot,'workspace');if(await realpath(path)!==path||(await lstat(path)).isSymbolicLink())throw new WorkbenchStateError('副本目录已变化。'); + const current=await sourceSnapshot(path);if(current.digest!==info.outputSnapshot)return {id,status:'modified' as const,path}; + return {id,status:'ready' as const,path,snapshot:info.outputSnapshot,metadata:info}; + } + return {id,status:'not-found' as const}; + } + async copy(id:unknown,selection:Selection){ + const value=await this.status(id,selection); + if(value.status!=='ready')throw new WorkbenchStateError('尚未找到可核验的完整副本,请保留原材料并先查询恢复状态。'); + return value; + } +} diff --git a/src/workbench/server.ts b/src/workbench/server.ts index f6f5d56..98eea17 100644 --- a/src/workbench/server.ts +++ b/src/workbench/server.ts @@ -22,13 +22,14 @@ import { compareArtifactReports, parseArtifactReport } from "../domain/artifact- import {previewAcceptancePlan,inspectAcceptancePackage,batchSummary} from "../cli/commands/batch.js"; import {renderBatchHtml} from "../reporters/batch-html.js"; import {BatchAcceptanceError} from "../domain/batch-report.js"; +import {RepairRecovery} from "./repair-recovery.js"; const identity = (s: {dev: number; ino: number}) => `${s.dev}:${s.ino}`; const inside = (root: string, target: string) => { const r = relative(root, target); return !r || (!r.startsWith("..") && !isAbsolute(r)); }; const describePlan = (value:ActionPlan) => [...value.changes.map(c => `${c.path} · ${c.safety} · ${c.modeBefore?.toString(8) ?? "内容"} → ${c.modeAfter?.toString(8) ?? "内容"}`), ...value.manualSteps.map(s => `人工处理:${s.title}\n${s.steps.join("\n")}`)].join("\n\n") || "没有可自动应用的变更。"; const preview = (text:string) => `
${text.replace(/[&<>"]/g,c=>({"&":"&","<":"<",">":">",'"':"""}[c]!))}
`; -const operationKinds = {"/api/choose":"choose","/api/select":"select","/api/verify":"verify","/api/plan":"plan","/api/apply":"apply","/api/batch/preview":"batch_preview","/api/batch/run":"batch_run","/api/batch/open":"batch_open","/api/history/open":"history_open","/api/history/export":"history_export"} as const; +const operationKinds = {"/api/repair/list":"repair_list","/api/repair/check":"repair_check","/api/repair/restore":"repair_restore","/api/repair/verify":"repair_verify","/api/choose":"choose","/api/select":"select","/api/verify":"verify","/api/plan":"plan","/api/apply":"apply","/api/batch/preview":"batch_preview","/api/batch/run":"batch_run","/api/batch/open":"batch_open","/api/history/open":"history_open","/api/history/export":"history_export"} as const; type OperationKind = typeof operationKinds[keyof typeof operationKinds]; type OperationOutcome = "completed"|"failed"|"cancelled"|"unconfirmed"; type ActiveOperation = {id:string;kind:OperationKind;phase:"preparing"|"running"|"finalizing";startedAt:number;submitted:boolean;historyId?:string;outcome?:OperationOutcome}; @@ -42,16 +43,17 @@ export async function startWorkbench(options: { port?: number; stateDir: string; if ((await lstat(stateDir)).isSymbolicLink() || await realpath(stateDir) !== stateDir) throw new Error("State directory must be a real directory."); await chmod(stateDir, 0o700); const history = new WorkbenchHistory(stateDir, identity(await lstat(stateDir))); + const recovery=new RepairRecovery(stateDir,identity(await lstat(stateDir)),history); const nonce = randomBytes(32).toString("hex"); const cliPath = options.cliPath ?? fileURLToPath(new URL("../cli/index.js", import.meta.url)); let active: ChildProcess | undefined, busy = false, applying = false, cancelled = false; let currentOperation:ActiveOperation|undefined, lastOperation:LastOperation|undefined; let cancelKiller:ReturnType|undefined, closing=false; - const cancellable = () => Boolean(currentOperation && !applying && !cancelled && currentOperation.phase!=="finalizing" && ["verify","plan","batch_run"].includes(currentOperation.kind)); + const cancellable = () => Boolean(currentOperation && !applying && !cancelled && currentOperation.phase!=="finalizing" && ["verify","plan","batch_run","repair_restore","repair_verify"].includes(currentOperation.kind)); const operationStatus = () => ({schema:"skillsync.workbench-operation/v1",readOnly:true, active:currentOperation?{id:currentOperation.id,kind:currentOperation.kind,phase:applying?"applying":currentOperation.phase,startedAt:currentOperation.startedAt,cancellable:cancellable(),cancelRequested:cancelled}:null, last:lastOperation??null}); - let comparingHistory=false; + let comparingHistory=false,readingRecovery=false; let selection: Selection | undefined; let actionable: string[] = []; let plan: { id: string; path: string; value: ActionPlan; snapshot: string; historyId:string } | undefined; @@ -154,6 +156,11 @@ export async function startWorkbench(options: { port?: number; stateDir: string; catch(error){return send(res,400,{error:error instanceof WorkbenchStateError?error.message:"历史材料无法稳定读取,请检查两份原记录;没有重新执行核验。"});} finally{comparingHistory=false;} } + if(req.url==='/api/repair/status'){ + if(readingRecovery)return send(res,409,{error:'已有恢复状态查询中,请稍后再试。'}); + readingRecovery=true; + try{const scope=await checkSelection();const value=await recovery.status(input.id,scope);if(selection!==scope)throw new WorkbenchStateError('当前选择已变化,请重新核对恢复材料。');return send(res,200,value);}finally{readingRecovery=false;} + } if (busy) return send(res, 409, {error: "已有操作进行中,请查看后台状态。",code:"operation_busy"}); const kind=operationKinds[req.url as keyof typeof operationKinds]; if(!kind)return send(res,404,{error:"未知操作。"}); @@ -233,6 +240,24 @@ export async function startWorkbench(options: { port?: number; stateDir: string; return respond( 200, {selected: true}); } const selected = await checkSelection(); + if(req.url?.startsWith('/api/repair/')){ + if(selected.kind!=='skill')throw new WorkbenchStateError('恢复副本只用于 Skill 目录。'); + if(req.url==='/api/repair/list')return respond(200,await recovery.list(selected)); + if(req.url==='/api/repair/check')return respond(200,await recovery.check(input.id,selected,input.planHistoryId)); + if(req.url==='/api/repair/restore'){ + if(input.confirm!==true)throw new WorkbenchStateError('请确认只创建新副本,保留当前目录。'); + plan=undefined;actionable=[];owned.submitted=true;owned.phase='running'; + const value=await recovery.restore(input.token,selected,owned.id,()=>cancelled||closing,()=>{owned.phase='finalizing';});owned.phase='finalizing';return respond(200,value); + } + if(req.url==='/api/repair/verify'){ + const copy=await recovery.copy(input.id,selected),before=await scanStagedWorkspace(copy.path); + const args=['verify','--path',copy.path,'--format','json'];if(selected.delivery)args.push('--delivery'); + const output=await command(args),value=parseStrictJson(output) as VerificationReport; + if((await scanStagedWorkspace(copy.path)).digest!==before.digest)throw new WorkbenchStateError('副本在核验期间变化,请保留原结果后重新检查。'); + const info=await lstat(copy.path);const record=await history.append({kind:'verify',selection:{...selected,path:copy.path,identity:identity(info)},snapshot:before.digest,exitCode:value.exitCode},output); + return respond(200,{id:input.id,snapshot:copy.snapshot,readOnly:true,report:value,html:renderVerificationHtml(value),historyId:record.id,path:copy.path}); + } + } if (req.url === "/api/verify") { plan=undefined;actionable=[]; const snapshot=selected.kind==="skill"?(await scanStagedWorkspace(selected.path)).digest:undefined; @@ -311,7 +336,7 @@ export async function startWorkbench(options: { port?: number; stateDir: string; } return respond( 404, {error: "未知操作。"}); } catch(error) { - owned.outcome=owned.submitted&&["apply","batch_run"].includes(owned.kind)?"unconfirmed":cancelled?"cancelled":"failed"; + owned.outcome=owned.submitted&&["apply","batch_run","repair_restore"].includes(owned.kind)?"unconfirmed":cancelled?"cancelled":"failed"; throw error; } finally { if(cancelKiller){clearTimeout(cancelKiller);cancelKiller=undefined;} diff --git a/tests/cli/fix.test.ts b/tests/cli/fix.test.ts index 58dc356..82dec1e 100644 --- a/tests/cli/fix.test.ts +++ b/tests/cli/fix.test.ts @@ -1,11 +1,20 @@ -import { chmod, mkdir, mkdtemp, readFile, stat, writeFile } from "node:fs/promises"; +import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; import { planDigest } from "../../src/domain/action-plan"; -import { runCli } from "../../src/cli/index"; +import { runCli as actualRunCli } from "../../src/cli/index"; + +// Every repair test owns its vault; repeated suites never consume the user vault. +const backupFixtures: string[] = []; +afterEach(async () => { for (const path of backupFixtures.splice(0)) await rm(path, {recursive: true, force: true}); }); +async function runCli(args: string[]) { + if (args[0] !== "fix" || !args.includes("--apply") || args.includes("--backup-dir")) return actualRunCli(args); + const parent = await mkdtemp(join(tmpdir(), "skillsync-test-backups-")); backupFixtures.push(parent); + return actualRunCli([...args, "--backup-dir", join(parent, "vault")]); +} async function createSkillRoot(): Promise<{ root: string; scriptPath: string }> { const parent = await mkdtemp(join(tmpdir(), "skillsync-fix-")); @@ -246,6 +255,7 @@ describe("skillsync fix", () => { "--yes", "--approve-review-required", ]); + expect(approved.stderr).toBe(""); expect(approved.exitCode).toBe(0); expect(approved.stdout).toContain("Applied is not verified. Next command: skillsync verify"); await expect(readFile(skillPath, "utf8")).resolves.toBe("after\n"); diff --git a/tests/cli/help.test.ts b/tests/cli/help.test.ts index aad007b..2020d4b 100644 --- a/tests/cli/help.test.ts +++ b/tests/cli/help.test.ts @@ -12,7 +12,7 @@ describe("skillsync CLI", () => { it("reports the installed source version and lists the verification commands", async () => { const version = await runCli(["--version"]); expect(version.exitCode).toBe(0); - expect(version.stdout).toBe("0.3.0\n"); + expect(version.stdout).toBe("0.4.0\n"); const result = await runCli(["--help"]); diff --git a/tests/cli/report.test.ts b/tests/cli/report.test.ts index 19ee3a6..454286d 100644 --- a/tests/cli/report.test.ts +++ b/tests/cli/report.test.ts @@ -248,7 +248,7 @@ describe("skillsync report", () => { const json = await runCli(["report", "--before", beforePath, "--after", afterPath, "--format", "json"]); expect(JSON.parse(json.stdout).conclusion).toBe("verified"); - expect(JSON.parse(json.stdout).toolVersion).toBe("0.3.0"); + expect(JSON.parse(json.stdout).toolVersion).toBe("0.4.0"); const sarif = await runCli(["report", "--before", beforePath, "--after", afterPath, "--format", "sarif"]); const parsedSarif = JSON.parse(sarif.stdout) as { @@ -259,7 +259,7 @@ describe("skillsync report", () => { }>; }; expect(parsedSarif.version).toBe("2.1.0"); - expect(parsedSarif.runs[0]?.tool.driver.version).toBe("0.3.0"); + expect(parsedSarif.runs[0]?.tool.driver.version).toBe("0.4.0"); expect(parsedSarif.runs[0]?.results[0]?.properties.issueId).toMatch(/^iss_/); }); diff --git a/tests/docs/release-installation.test.ts b/tests/docs/release-installation.test.ts index 87fbdbf..6f4f5b5 100644 --- a/tests/docs/release-installation.test.ts +++ b/tests/docs/release-installation.test.ts @@ -39,10 +39,10 @@ describe("release documentation", () => { }; expect(readme).toContain("Inspect local Skill folders and declared artifact deliveries."); - expect(readme).toContain("Alpha · GitHub release v0.3.0 · Node.js 20+"); + expect(readme).toContain("Alpha · GitHub release v0.4.0 · Node.js 20+"); expect(readme).toContain("GitHub Releases"); - expect(readme).toContain("download/v0.3.0"); - expect(readme).toContain("chumanic-skillsync-0.3.0.tgz"); + expect(readme).toContain("download/v0.4.0"); + expect(readme).toContain("chumanic-skillsync-0.4.0.tgz"); expect(readme).toContain("## Install"); expect(readme).toContain("npx --yes @chumanic/skillsync@0.1.0 verify"); expect(readme).toContain([ diff --git a/tests/integration/live-runtime-preparation.test.ts b/tests/integration/live-runtime-preparation.test.ts index f9d41ba..6ce5c41 100644 --- a/tests/integration/live-runtime-preparation.test.ts +++ b/tests/integration/live-runtime-preparation.test.ts @@ -139,7 +139,9 @@ describe("live runtime preparation", () => { const jobs = asRecord(document.jobs); expect(push.tags).toEqual(["v*"]); - expect(Object.keys(jobs)).toEqual(["release"]); + expect(Object.keys(jobs)).toEqual(["release", "mac-app", "publish"]); + expect(asRecord(jobs["mac-app"]).needs).toBe("release"); + expect(asRecord(jobs.publish).needs).toEqual(["release", "mac-app"]); const runs = workflowRuns(document, "release").join("\n"); for (const command of [ @@ -152,8 +154,17 @@ describe("live runtime preparation", () => { expect(runs).toContain(command); } - expect(runs).toContain("gh release create"); - expect(runs).toContain("--verify-tag"); + const publish = workflowRuns(document, "publish").join("\n"); + const mac = workflowRuns(document, "mac-app").join("\n"); + expect(publish).toContain("gh release create"); + expect(publish).toContain("--verify-tag"); + expect(publish).toContain("sha256sum *.tgz *.zip *.json"); + expect(publish).toContain('test "$source" = "$GITHUB_SHA"'); + expect(publish).toContain("An existing release must not be overwritten"); + for (const command of ['test "$(uname -m)" = arm64', "desktop/prepare_runtime.py", "desktop/build_app.py --runtime", "codesign --verify --deep --strict", "--smoke-check", "--width 390", "desktop/application_manifest.py", "python3 -m unittest discover"]) expect(mac).toContain(command); + expect(asRecord(jobs["mac-app"])["runs-on"]).toBe("macos-15"); + expect(asRecord(asRecord(jobs.publish).permissions)).toEqual({contents: "write"}); + expect(runs).not.toContain("gh release create"); expect(runs).toContain("checksums.txt"); expect(runs).toContain("branch=main&event=push&status=success"); expect(runs).toContain("actions/workflows/skillsync.yml/runs"); @@ -167,7 +178,7 @@ describe("live runtime preparation", () => { expect(content).toContain("package-manager-cache: false"); expect(content).not.toMatch(/npm dist-tag|NODE_AUTH_TOKEN|registry-url|secrets\./i); expect(asRecord(document.permissions)).toEqual({ contents: "read", actions: "read" }); - expect(asRecord(asRecord(jobs.release).permissions)).toEqual({ contents: "write", actions: "read", "id-token": "write", attestations: "write", "artifact-metadata": "write" }); + expect(asRecord(asRecord(jobs.release).permissions)).toEqual({ contents: "read", actions: "read", "id-token": "write", attestations: "write", "artifact-metadata": "write" }); }); it("keeps workflow and test sources outside the package artifact allowlist", async () => { diff --git a/tests/integration/product-trust-loop.test.ts b/tests/integration/product-trust-loop.test.ts index 20419bd..620f497 100644 --- a/tests/integration/product-trust-loop.test.ts +++ b/tests/integration/product-trust-loop.test.ts @@ -1,10 +1,19 @@ -import { access, chmod, cp, mkdtemp, readFile, stat, writeFile } from "node:fs/promises"; +import { access, chmod, cp, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; -import { runCli } from "../../src/cli/index"; +import { runCli as actualRunCli } from "../../src/cli/index"; + +// Every repair test owns its vault; repeated suites never consume the user vault. +const backupFixtures: string[] = []; +afterEach(async () => { for (const path of backupFixtures.splice(0)) await rm(path, {recursive: true, force: true}); }); +async function runCli(args: string[]) { + if (args[0] !== "fix" || !args.includes("--apply") || args.includes("--backup-dir")) return actualRunCli(args); + const parent = await mkdtemp(join(tmpdir(), "skillsync-test-backups-")); backupFixtures.push(parent); + return actualRunCli([...args, "--backup-dir", join(parent, "vault")]); +} type VerifyJson = { exitCode: number; diff --git a/tests/reporters/sarif.test.ts b/tests/reporters/sarif.test.ts index 2012377..eb1f113 100644 --- a/tests/reporters/sarif.test.ts +++ b/tests/reporters/sarif.test.ts @@ -44,7 +44,7 @@ describe("renderSarif", () => { expect(sarif.version).toBe("2.1.0"); expect(sarif.runs[0]?.tool.driver.name).toBe("skillsync"); - expect(sarif.runs[0]?.tool.driver.version).toBe("0.3.0"); + expect(sarif.runs[0]?.tool.driver.version).toBe("0.4.0"); expect(sarif.runs[0]?.tool.driver.rules[0]?.id).toBe("structure.missing-reference"); expect(sarif.runs[0]?.tool.driver.rules[0]?.help?.text).toBe("Add the referenced file."); expect(sarif.runs[0]?.results[0]?.ruleId).toBe("structure.missing-reference"); diff --git a/tests/workbench/page.test.ts b/tests/workbench/page.test.ts index 13e8a25..29c2f2a 100644 --- a/tests/workbench/page.test.ts +++ b/tests/workbench/page.test.ts @@ -16,7 +16,8 @@ class Element { events=new Mapvoid>(); addEventListener(name:string,handler:()=>void) {this.events.set(name,handler);} replaceWith(element: Element) { Object.assign(this, element); } - replaceChildren() { this.children = []; } + replaceChildren(...elements: Element[]) { this.children = elements; } + add(element: Element) { this.children.push(element); } append(...elements: Element[]) { this.children.push(...elements); } } @@ -59,12 +60,35 @@ async function page(failure?: "network" | "invalid-json" | "expired-session", de }}; }; const timers=new Mapvoid>(),events=new Mapvoid>();let nextTimer=0; - runInNewContext(workbenchScript, {document: {hidden:false,addEventListener:(name:string,fn:()=>void)=>events.set(name,fn),getElementById: get, querySelector: () => get("meta"), querySelectorAll: () => [], createElement: () => new Element()},window:{addEventListener:(name:string,fn:()=>void)=>events.set(name,fn)},crypto:{randomUUID},fetch, URL, Blob, setTimeout:(fn:()=>void)=>{timers.set(++nextTimer,fn);return nextTimer;},clearTimeout:(id:number)=>timers.delete(id), AbortController}); + class OptionElement extends Element { constructor(text='',value=''){super();this.textContent=text;this.value=value;} } + runInNewContext(workbenchScript, {Option:OptionElement,document: {hidden:false,addEventListener:(name:string,fn:()=>void)=>events.set(name,fn),getElementById: get, querySelector: () => get("meta"), querySelectorAll: () => [], createElement: () => new Element()},window:{addEventListener:(name:string,fn:()=>void)=>events.set(name,fn)},crypto:{randomUUID},fetch, URL, Blob, setTimeout:(fn:()=>void)=>{timers.set(++nextTimer,fn);return nextTimer;},clearTimeout:(id:number)=>timers.delete(id), AbortController}); await new Promise(resolve => setImmediate(resolve)); return {get, offsets, actions,inputs,timers,events,respond(action:string,value:unknown){responses.set(action,value);}, fail(action: string, message: string) { rejected.set(action, message); }, async finishInitialHistory() { releaseHistory(); await new Promise(resolve => setImmediate(resolve)); }, async click(id: string) { await get(id).onclick?.(); await new Promise(resolve => setImmediate(resolve)); }}; } describe("workbench interactions", () => { + async function recoveryUi(){ + const ui=await page(),id=randomUUID(),path='/private/synthetic/recovery/workspace';await ui.click('verify'); + ui.respond('repair/list',{items:[{id:'slot-00/'+randomUUID(),state:'unchecked',legacy:false}],plans:[],copies:[{id,createdAt:'2026-11-16T00:00:00Z',state:'recorded'}]}); + await ui.click('repair-list');ui.get('repair-choice').value='slot-00/'+randomUUID();ui.get('repair-choice').onchange?.(); + ui.respond('repair/check',{token:randomUUID(),files:1,bytes:16,message:'保留当前目录'});await ui.click('repair-check'); + ui.respond('repair/restore',{id,path,snapshot:'sha256:'+'a'.repeat(64)});await ui.click('repair-restore');return {ui,id,path}; + } + it('binds copy verification to its exact id/path and drops a wrong response before download',async()=>{ + const {ui,id,path}=await recoveryUi(); + ui.respond('repair/verify',{id:randomUUID(),path,snapshot:'sha256:'+'a'.repeat(64),readOnly:true,html:'

wrong result

',report:{schema_version:1,targets:[{path}],issues:[]}}); + await ui.click('repair-verify');expect(ui.get('repair-download').disabled).toBe(true);expect(ui.get('repair-report').hidden).toBe(true);expect(ui.get('repair-scope').textContent).toContain('未能绑定'); + ui.respond('repair/verify',{id,path,snapshot:'sha256:'+'a'.repeat(64),readOnly:true,html:'

scoped saved report

',report:{schema_version:1,targets:[{path}],issues:[]}});await ui.click('repair-verify');expect(ui.get('repair-download').disabled).toBe(false); + ui.get('repair-legacy-plan').onchange?.();expect(ui.get('repair-download').disabled).toBe(true);expect(ui.get('repair-verify').disabled).toBe(true);expect(ui.get('repair-report').srcdoc).toBe(''); + }); + it('reopens an existing recovery from metadata without submitting a second restore',async()=>{ + const {ui,id,path}=await recoveryUi();const submissions=ui.actions.filter(action=>action==='repair/restore').length; + ui.get('repair-existing').value=id;ui.respond('repair/status',{id,status:'ready',path,snapshot:'sha256:'+'a'.repeat(64)});await ui.click('repair-return');expect(ui.get('repair-copy-path').textContent).toBe(path);expect(ui.actions.filter(action=>action==='repair/restore')).toHaveLength(submissions); + }); + it('keeps the owned restore operation cancellable while its reply is pending',async()=>{ + const {ui,id,path}=await recoveryUi();ui.respond('repair/check',{token:randomUUID(),files:1,bytes:16,message:'check'});await ui.click('repair-check'); + let finish!:(value:unknown)=>void;ui.respond('repair/restore',new Promise(resolve=>{finish=resolve;}));const pending=ui.click('repair-restore');await new Promise(resolve=>setImmediate(resolve));expect(ui.get('cancel').disabled).toBe(false);finish({id,path,snapshot:'sha256:'+'a'.repeat(64)});await pending; + }); it('a cached return cannot display an old report as the current result',async()=>{ const ui=await page();await ui.click('verify');expect(ui.get('result').hidden).toBe(false); ui.events.get('pagehide')?.();expect(ui.get('result').hidden).toBe(true);expect(ui.get('report').srcdoc).toBe('');expect(ui.get('root').value).toBe('/synthetic/review'); diff --git a/tests/workbench/repair-recovery.test.ts b/tests/workbench/repair-recovery.test.ts new file mode 100644 index 0000000..4249ade --- /dev/null +++ b/tests/workbench/repair-recovery.test.ts @@ -0,0 +1,45 @@ +import { randomUUID } from 'node:crypto'; +import { chmod, lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, relative } from 'node:path'; +import { afterEach, expect, test } from 'vitest'; +import { createRepairBackup } from '../../src/domain/repair-backups.js'; +import { RepairRecovery } from '../../src/workbench/repair-recovery.js'; +import { WorkbenchHistory, type Selection } from '../../src/workbench/history.js'; + +const owned:string[]=[]; +afterEach(async()=>{for(const root of owned.splice(0))await rm(root,{recursive:true,force:true});}); +async function fixture(){ + const base=await realpath(await mkdtemp(join(tmpdir(),'sync-copy-')));owned.push(base); + const root=join(base,'selected'),state=join(base,'state');await mkdir(root,{mode:0o700});await mkdir(state,{mode:0o700}); + await writeFile(join(root,'one.md'),'current contents\n');const info=await lstat(root); + const selection:Selection={path:root,identity:`${info.dev}:${info.ino}`,kind:'skill',delivery:false}; + const backupRoot=join(state,'repair-backups');const backup=await createRepairBackup([{normalizedPath:'one.md',content:'retained originals\n',mode:0o600}],'synthetic-plan',backupRoot,{rootPath:root,rootIdentity:selection.identity}); + const stamp=await lstat(state),history=new WorkbenchHistory(state,`${stamp.dev}:${stamp.ino}`); + return {base,root,state,selection,id:relative(backupRoot,backup.directory).split('\\').join('/'),store:new RepairRecovery(state,`${stamp.dev}:${stamp.ino}`,history)}; +} +test('cancelled copies stay incomplete and cannot hide a later completed copy',async()=>{ + const {root,store,selection,id}=await fixture();const checked=await store.check(id,selection),cancelled=randomUUID(); + await expect(store.restore(checked.token,selection,cancelled,()=>true)).rejects.toThrow('停止'); + expect((await store.status(cancelled,selection)).status).toBe('incomplete');await expect(store.copy(cancelled,selection)).rejects.toThrow('完整副本'); + const second=await store.check(id,selection);let finalized=false;const done=await store.restore(second.token,selection,randomUUID(),()=>false,()=>{finalized=true;}); + expect(finalized).toBe(true);expect((await store.status(done.id,selection)).status).toBe('ready'); + expect(await readFile(join(done.path,'one.md'),'utf8')).toBe('retained originals\n');expect(await readFile(join(root,'one.md'),'utf8')).toBe('current contents\n'); +}); +test('an identical replacement selected directory cannot consume an old restore confirmation',async()=>{ + const {root,base,store,selection,id}=await fixture();const checked=await store.check(id,selection); + await rename(root,join(base,'retained-directory'));await mkdir(root);await writeFile(join(root,'one.md'),'current contents\n'); + await expect(store.restore(checked.token,selection,randomUUID(),()=>false)).rejects.toThrow('目录已变化'); + expect(await readFile(join(root,'one.md'),'utf8')).toBe('current contents\n'); +}); +test('corrupt original backup bytes cannot become a checked or published recovery',async()=>{ + const {state,root,store,selection,id}=await fixture();await writeFile(join(state,'repair-backups',id,'files/one.md'),'changed backup\n'); + await expect(store.check(id,selection)).rejects.toThrow('checksum');expect(await readFile(join(root,'one.md'),'utf8')).toBe('current contents\n'); +}); +test('a modified completed copy is no longer reported as the original recovery result',async()=>{ + const {root,store,selection,id}=await fixture(),checked=await store.check(id,selection); + const done=await store.restore(checked.token,selection,randomUUID(),()=>false); + await chmod(join(done.path,'one.md'),0o640); + expect((await store.status(done.id,selection)).status).toBe('modified');await expect(store.copy(done.id,selection)).rejects.toThrow('完整副本'); + expect(await readFile(join(root,'one.md'),'utf8')).toBe('current contents\n'); +}); diff --git a/tests/workbench/server.test.ts b/tests/workbench/server.test.ts index 2c1e59d..595711f 100644 --- a/tests/workbench/server.test.ts +++ b/tests/workbench/server.test.ts @@ -23,6 +23,63 @@ async function setup(cliPath = resolve("dist/cli/index.js")) { return {base, root, script, app, api, token}; } describe("real CLI graphical workbench", () => { + it("checks retained repair originals and restores only to a new copy before verifying it", async () => { + const { api, base, root, script } = await setup(); + await api('select', { path: root, kind: 'skill' }); + await api('verify'); const planned = await api('plan'); + expect((await api('apply', { id: planned.data.id, confirm: true })).status).toBe(200); + const originalMode = (await stat(script)).mode & 0o777; + const listed = await api('repair/list'); expect(listed.status).toBe(200); + expect(listed.data.items).toHaveLength(1); + const checked = await api('repair/check', { id: listed.data.items[0].id }); expect(checked.status).toBe(200); + const copy = await api('repair/restore', { token: checked.data.token, confirm: true }); expect(copy.status).toBe(200); + expect(copy.data.path.startsWith(join(base, 'state', 'recovery-copies'))).toBe(true); + expect((await stat(script)).mode & 0o777).toBe(originalMode); + expect((await stat(join(copy.data.path, 'scripts/check.sh'))).mode & 0o777).toBe(0o777); + const verified = await api('repair/verify', { id: copy.data.id }); expect(verified.status).toBe(200); + expect(verified.data.readOnly).toBe(true); expect(verified.data.report).toHaveProperty('issues'); + expect((await stat(script)).mode & 0o777).toBe(originalMode); + }); + it('does not expose or restore another selected directory backup and rejects path-shaped IDs', async()=>{ + const {api,base,root}=await setup();await api('select',{path:root,kind:'skill'});await api('verify');const plan=await api('plan');await api('apply',{id:plan.data.id,confirm:true}); + const list=await api('repair/list'),id=list.data.items[0].id,checked=await api('repair/check',{id}); + const other=join(base,'other');await mkdir(other);await writeFile(join(other,'SKILL.md'),'---\nname: other\ndescription: Other.\n---\n'); + await api('select',{path:other,kind:'skill'}); + expect((await api('repair/list')).data.items).toEqual([]); + expect((await api('repair/check',{id})).status).not.toBe(200); + expect((await api('repair/restore',{token:checked.data.token,confirm:true})).status).not.toBe(200); + expect((await api('repair/check',{id:'../outside'})).status).not.toBe(200); + expect(await readdir(join(base,'state'))).not.toContain('recovery-copies'); + }); + it('invalidates a reviewed recovery on permission or content changes and never repeats an old confirmation',async()=>{ + const {api,root,script,base}=await setup();await api('select',{path:root,kind:'skill'});await api('verify');const plan=await api('plan');await api('apply',{id:plan.data.id,confirm:true}); + const id=(await api('repair/list')).data.items[0].id; + const first=await api('repair/check',{id});await chmod(script,0o750); + const stale=await api('repair/restore',{token:first.data.token,confirm:true});expect(stale.status).not.toBe(200);expect(stale.data.error).toContain('变化'); + const next=await api('repair/check',{id});await writeFile(join(root,'SKILL.md'),'later user edit\n'); + expect((await api('repair/restore',{token:next.data.token,confirm:true})).status).not.toBe(200); + expect((await api('repair/restore',{token:next.data.token,confirm:true})).status).not.toBe(200); + expect(await readFile(join(root,'SKILL.md'),'utf8')).toBe('later user edit\n');expect(await readdir(join(base,'state'))).not.toContain('recovery-copies'); + }); + it('reads legacy repair backups only with the matching scoped original plan',async()=>{ + const {api,base,root}=await setup();await api('select',{path:root,kind:'skill'});await api('verify');const plan=await api('plan');await api('apply',{id:plan.data.id,confirm:true}); + const id=(await api('repair/list')).data.items[0].id; + const scope=join(base,'state','repair-backups',id,'scope.json');await rename(scope,scope+'.retained'); + const legacy=await api('repair/list');expect(legacy.data.items[0].legacy).toBe(true); + expect((await api('repair/check',{id})).status).not.toBe(200); + const checked=await api('repair/check',{id,planHistoryId:legacy.data.plans[0].id});expect(checked.status).toBe(200); + const restored=await api('repair/restore',{token:checked.data.token,confirm:true});expect(restored.status).toBe(200); + const state=await api('repair/status',{id:restored.data.id});expect(state.data.status).toBe('ready');expect(state.data.path).toBe(restored.data.path); + expect((await api('repair/status',{id:restored.data.id})).data.path).toBe(restored.data.path); + const operation=await api('operation');expect(operation.data.last.id).toBe(restored.data.id);expect(operation.data.last.kind).toBe('repair_restore'); + }); + it('bounds retained recovery copies without evicting prior completed material',async()=>{ + const {api,base,root}=await setup();await api('select',{path:root,kind:'skill'});await api('verify');const plan=await api('plan');await api('apply',{id:plan.data.id,confirm:true}); + const id=(await api('repair/list')).data.items[0].id,completed=[]; + for(let i=0;i<4;i++){const checked=await api('repair/check',{id});const restored=await api('repair/restore',{token:checked.data.token,confirm:true});expect(restored.status).toBe(200);completed.push(restored.data.id);} + const checked=await api('repair/check',{id});const full=await api('repair/restore',{token:checked.data.token,confirm:true});expect(full.status).not.toBe(200);expect(full.data.error).toContain('4份'); + expect(await readdir(join(base,'state','recovery-copies'))).toHaveLength(4);for(const copyId of completed)expect((await api('repair/status',{id:copyId})).data.status).toBe('ready'); + }); it("accepts an activated top-level page navigation while rejecting cross-site APIs and frames", async () => { const {app,token}=await setup(); const get=(path:string,headers:Record)=>new Promise((resolve,reject)=>{const request=httpRequest(app.url+path,{headers},response=>{response.resume();response.on('end',()=>resolve(response.statusCode!));});request.on('error',reject);request.end();});