From a06cd647afb65076c9e31ce3ae259bf21286138f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=97=A5=E5=A4=A9?= Date: Sun, 12 Apr 2026 17:40:06 +0800 Subject: [PATCH 1/3] Fix GUI artifact paths and export the SDK fallback bridge --- .github/actions/build-gui-platform/action.yml | 2 +- .github/actions/setup-tauri/action.yml | 6 ++-- .github/workflows/build-gui-all.yml | 36 +++++++++---------- .github/workflows/release-gui-linux.yml | 16 ++++----- .github/workflows/release-gui-macos.yml | 12 +++---- .github/workflows/release-gui-win.yml | 8 ++--- cli/src/internal/native-command-bridge.ts | 4 +-- sdk/src/index.ts | 3 ++ 8 files changed, 45 insertions(+), 42 deletions(-) diff --git a/.github/actions/build-gui-platform/action.yml b/.github/actions/build-gui-platform/action.yml index e6236a4f..8a05a67c 100644 --- a/.github/actions/build-gui-platform/action.yml +++ b/.github/actions/build-gui-platform/action.yml @@ -48,7 +48,7 @@ runs: shell: bash run: | echo "=== Finding all bundle artifacts ===" - find target -path '*/bundle/*' -type f 2>/dev/null || echo 'No bundle files found' + find gui/src-tauri/target -path '*/bundle/*' -type f 2>/dev/null || echo 'No bundle files found' - name: Upload artifacts uses: actions/upload-artifact@v7 diff --git a/.github/actions/setup-tauri/action.yml b/.github/actions/setup-tauri/action.yml index cb70c705..118d578f 100644 --- a/.github/actions/setup-tauri/action.yml +++ b/.github/actions/setup-tauri/action.yml @@ -91,7 +91,7 @@ runs: path: | ~/.cargo/registry ~/.cargo/git - target + gui/src-tauri/target key: ${{ runner.os }}-cargo-${{ inputs.rust-version }}-${{ steps.cargo-deps-hash.outputs.hash }} restore-keys: | ${{ runner.os }}-cargo-${{ inputs.rust-version }}- @@ -113,6 +113,6 @@ runs: - name: Clean old bundle artifacts shell: bash run: | - if [ -d "target" ]; then - find target -type d -name bundle -prune -exec rm -rf {} + + if [ -d "gui/src-tauri/target" ]; then + find gui/src-tauri/target -type d -name bundle -prune -exec rm -rf {} + fi diff --git a/.github/workflows/build-gui-all.yml b/.github/workflows/build-gui-all.yml index 0d414bbf..c82c8262 100644 --- a/.github/workflows/build-gui-all.yml +++ b/.github/workflows/build-gui-all.yml @@ -20,32 +20,32 @@ jobs: rust-targets: '' tauri-command: pnpm tauri build artifact-path: | - target/*/release/bundle/**/*.exe - target/release/bundle/**/*.exe - target/*/release/bundle/**/*.sig - target/release/bundle/**/*.sig + gui/src-tauri/target/*/release/bundle/**/*.exe + gui/src-tauri/target/release/bundle/**/*.exe + gui/src-tauri/target/*/release/bundle/**/*.sig + gui/src-tauri/target/release/bundle/**/*.sig - os: ubuntu-24.04 rust-targets: '' tauri-command: pnpm tauri build artifact-path: | - target/*/release/bundle/**/*.AppImage - target/*/release/bundle/**/*.deb - target/*/release/bundle/**/*.rpm - target/*/release/bundle/**/*.sig - target/release/bundle/**/*.AppImage - target/release/bundle/**/*.deb - target/release/bundle/**/*.rpm - target/release/bundle/**/*.sig + gui/src-tauri/target/*/release/bundle/**/*.AppImage + gui/src-tauri/target/*/release/bundle/**/*.deb + gui/src-tauri/target/*/release/bundle/**/*.rpm + gui/src-tauri/target/*/release/bundle/**/*.sig + gui/src-tauri/target/release/bundle/**/*.AppImage + gui/src-tauri/target/release/bundle/**/*.deb + gui/src-tauri/target/release/bundle/**/*.rpm + gui/src-tauri/target/release/bundle/**/*.sig - os: macos-14 rust-targets: aarch64-apple-darwin,x86_64-apple-darwin tauri-command: pnpm tauri build --target universal-apple-darwin artifact-path: | - target/*/release/bundle/**/*.dmg - target/*/release/bundle/**/*.tar.gz - target/*/release/bundle/**/*.sig - target/release/bundle/**/*.dmg - target/release/bundle/**/*.tar.gz - target/release/bundle/**/*.sig + gui/src-tauri/target/*/release/bundle/**/*.dmg + gui/src-tauri/target/*/release/bundle/**/*.tar.gz + gui/src-tauri/target/*/release/bundle/**/*.sig + gui/src-tauri/target/release/bundle/**/*.dmg + gui/src-tauri/target/release/bundle/**/*.tar.gz + gui/src-tauri/target/release/bundle/**/*.sig runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v6 diff --git a/.github/workflows/release-gui-linux.yml b/.github/workflows/release-gui-linux.yml index f411cebc..6dbc931f 100644 --- a/.github/workflows/release-gui-linux.yml +++ b/.github/workflows/release-gui-linux.yml @@ -23,14 +23,14 @@ jobs: tauri-command: pnpm tauri build artifact-name: debug-gui-ubuntu-24.04 artifact-path: | - target/*/release/bundle/**/*.AppImage - target/release/bundle/**/*.AppImage - target/*/release/bundle/**/*.deb - target/release/bundle/**/*.deb - target/*/release/bundle/**/*.rpm - target/release/bundle/**/*.rpm - target/*/release/bundle/**/*.sig - target/release/bundle/**/*.sig + gui/src-tauri/target/*/release/bundle/**/*.AppImage + gui/src-tauri/target/release/bundle/**/*.AppImage + gui/src-tauri/target/*/release/bundle/**/*.deb + gui/src-tauri/target/release/bundle/**/*.deb + gui/src-tauri/target/*/release/bundle/**/*.rpm + gui/src-tauri/target/release/bundle/**/*.rpm + gui/src-tauri/target/*/release/bundle/**/*.sig + gui/src-tauri/target/release/bundle/**/*.sig signing-private-key: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} signing-private-key-password: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} version: ${{ inputs.version }} diff --git a/.github/workflows/release-gui-macos.yml b/.github/workflows/release-gui-macos.yml index 21fa2042..e1f7fe66 100644 --- a/.github/workflows/release-gui-macos.yml +++ b/.github/workflows/release-gui-macos.yml @@ -22,12 +22,12 @@ jobs: tauri-command: pnpm tauri build --target universal-apple-darwin artifact-name: debug-gui-macos-14 artifact-path: | - target/*/release/bundle/**/*.dmg - target/*/release/bundle/**/*.tar.gz - target/*/release/bundle/**/*.sig - target/release/bundle/**/*.dmg - target/release/bundle/**/*.tar.gz - target/release/bundle/**/*.sig + gui/src-tauri/target/*/release/bundle/**/*.dmg + gui/src-tauri/target/*/release/bundle/**/*.tar.gz + gui/src-tauri/target/*/release/bundle/**/*.sig + gui/src-tauri/target/release/bundle/**/*.dmg + gui/src-tauri/target/release/bundle/**/*.tar.gz + gui/src-tauri/target/release/bundle/**/*.sig rust-targets: aarch64-apple-darwin,x86_64-apple-darwin signing-private-key: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} signing-private-key-password: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} diff --git a/.github/workflows/release-gui-win.yml b/.github/workflows/release-gui-win.yml index 570fa2cf..d363a1ab 100644 --- a/.github/workflows/release-gui-win.yml +++ b/.github/workflows/release-gui-win.yml @@ -23,10 +23,10 @@ jobs: tauri-command: pnpm tauri build artifact-name: debug-gui-windows-latest artifact-path: | - target/*/release/bundle/**/*.exe - target/*/release/bundle/**/*.sig - target/release/bundle/**/*.exe - target/release/bundle/**/*.sig + gui/src-tauri/target/*/release/bundle/**/*.exe + gui/src-tauri/target/*/release/bundle/**/*.sig + gui/src-tauri/target/release/bundle/**/*.exe + gui/src-tauri/target/release/bundle/**/*.sig signing-private-key: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} signing-private-key-password: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} version: ${{ inputs.version }} diff --git a/cli/src/internal/native-command-bridge.ts b/cli/src/internal/native-command-bridge.ts index 19fb252a..f3d0822c 100644 --- a/cli/src/internal/native-command-bridge.ts +++ b/cli/src/internal/native-command-bridge.ts @@ -1,7 +1,7 @@ -import type {MemorySyncCommandOptions, MemorySyncCommandResult} from '../../../sdk/src/internal/sdk-binding' +import type {MemorySyncCommandOptions, MemorySyncCommandResult} from '@truenine/memory-sync-sdk' import {writeFile} from 'node:fs/promises' import process from 'node:process' -import {createTsFallbackMemorySyncBinding} from '../../../sdk/src/internal/sdk-binding' +import {createTsFallbackMemorySyncBinding} from '@truenine/memory-sync-sdk' type InternalBridgeCommand = 'install' | 'dry-run' | 'clean' | 'self-test' diff --git a/sdk/src/index.ts b/sdk/src/index.ts index 395a2ef7..24fa15a7 100644 --- a/sdk/src/index.ts +++ b/sdk/src/index.ts @@ -162,6 +162,9 @@ export type { MemorySyncSdkBinding, PublicLoggerDiagnosticRecord } from './internal/sdk-binding' +export { + createTsFallbackMemorySyncBinding +} from './internal/sdk-binding' export { clearBufferedDiagnostics, createLogger, From 49704a9a2c6a38f432bccf60b9250fc8f05da1fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=97=A5=E5=A4=A9?= Date: Sun, 12 Apr 2026 19:45:44 +0800 Subject: [PATCH 2/3] Consolidate workspace libraries into the sdk core --- .github/CODEOWNERS | 2 +- .github/pull_request_template.md | 2 +- .github/workflows/pull-request.yml | 6 +- .github/workflows/release-cli.yml | 8 +- CODE_OF_CONDUCT.md | 8 +- Cargo.lock | 107 +----------- Cargo.toml | 8 +- README.md | 34 ++-- SECURITY.md | 10 +- cli-integration-test/package.json | 2 +- cli-integration-test/src/container.ts | 6 +- cli-integration-test/src/fixtures.ts | 43 ++++- .../test/claude-code-cli.integration.test.ts | 2 +- .../test/codex.integration.test.ts | 46 +++++- cli/Cargo.toml | 1 - cli/npm/darwin-arm64/package.json | 2 +- cli/npm/darwin-x64/package.json | 2 +- cli/npm/linux-arm64-gnu/package.json | 2 +- cli/npm/linux-x64-gnu/package.json | 2 +- cli/npm/win32-x64-msvc/package.json | 2 +- cli/package.json | 4 +- cli/src/cli-runtime.ts | 3 +- cli/src/cli.rs | 12 +- cli/src/main.rs | 2 +- cli/src/script-runtime-worker.ts | 2 +- cli/src/tsdown-config.test.ts | 15 +- cli/tsdown.config.ts | 7 +- doc/content/sdk/architecture.mdx | 98 +++++------ doc/content/sdk/index.mdx | 6 +- doc/content/sdk/logger/index.mdx | 22 +-- doc/content/sdk/md-compiler/index.mdx | 26 +-- doc/content/sdk/script-runtime/index.mdx | 46 +++--- .../technical-details/architecture.mdx | 2 +- doc/content/technical-details/libraries.mdx | 10 +- doc/package.json | 2 +- gui/package.json | 2 +- gui/src-tauri/Cargo.toml | 2 +- gui/src-tauri/tauri.conf.json | 2 +- libraries/logger/Cargo.toml | 25 --- libraries/logger/build.rs | 4 - libraries/logger/eslint.config.ts | 26 --- libraries/logger/index.d.ts | 0 libraries/logger/package.json | 58 ------- libraries/logger/src/index.ts | 1 - libraries/logger/tsconfig.json | 70 -------- libraries/logger/tsconfig.lib.json | 23 --- libraries/logger/tsdown.config.ts | 20 --- libraries/md-compiler/Cargo.toml | 30 ---- libraries/md-compiler/build.rs | 4 - libraries/md-compiler/eslint.config.ts | 35 ---- libraries/md-compiler/index.d.ts | 0 libraries/md-compiler/package.json | 81 --------- libraries/md-compiler/tsconfig.json | 73 -------- libraries/md-compiler/tsconfig.lib.json | 22 --- libraries/md-compiler/tsdown.config.ts | 20 --- libraries/md-compiler/vite.config.ts | 10 -- libraries/md-compiler/vitest.config.ts | 22 --- libraries/script-runtime/Cargo.toml | 27 --- libraries/script-runtime/build.rs | 4 - libraries/script-runtime/eslint.config.ts | 26 --- libraries/script-runtime/package.json | 60 ------- libraries/script-runtime/src/index.test.ts | 106 ------------ libraries/script-runtime/src/index.ts | 1 - .../src/resolve-proxy-worker.ts | 1 - libraries/script-runtime/src/runtime-core.ts | 1 - libraries/script-runtime/src/types.ts | 1 - libraries/script-runtime/tsconfig.json | 70 -------- libraries/script-runtime/tsconfig.lib.json | 23 --- libraries/script-runtime/tsdown.config.ts | 21 --- mcp/package.json | 2 +- package.json | 2 +- pnpm-lock.yaml | 156 ++++-------------- pnpm-workspace.yaml | 3 - scripts/build-native.ts | 3 - scripts/copy-napi.ts | 7 +- scripts/write-platform-package-shims.ts | 6 +- sdk/Cargo.toml | 6 +- sdk/package.json | 26 +-- sdk/src/Aindex.test.ts | 28 ++++ sdk/src/Aindex.ts | 31 ++-- .../adaptors/ClaudeCodeCLIOutputAdaptor.ts | 2 +- .../adaptor-core/AbstractOutputAdaptor.ts | 6 +- .../adaptor-core/GlobalScopeCollector.ts | 6 +- .../adaptor-core/LocalizedPromptReader.ts | 2 +- .../adaptor-core/PromptArtifactCache.test.ts | 24 ++- .../adaptor-core/PromptArtifactCache.ts | 35 +++- .../PromptCompilerDiagnostics.test.ts | 2 +- .../adaptor-core/PromptCompilerDiagnostics.ts | 2 +- sdk/src/adaptors/adaptor-core/PromptTypes.ts | 2 +- sdk/src/adaptors/adaptor-core/plugin.ts | 2 +- sdk/src/core/cleanup.rs | 60 +++---- sdk/src/core/config/mod.rs | 14 +- sdk/src/core/input_plugins/aindex.rs | 44 ++++- sdk/src/core/input_plugins/command.rs | 5 +- sdk/src/core/input_plugins/global_memory.rs | 5 +- sdk/src/core/input_plugins/project_prompt.rs | 5 +- sdk/src/core/input_plugins/prompt_artifact.rs | 77 ++++++++- sdk/src/core/input_plugins/readme.rs | 5 +- sdk/src/core/input_plugins/rule.rs | 5 +- sdk/src/core/input_plugins/skill.rs | 5 +- sdk/src/core/input_plugins/subagent.rs | 5 +- sdk/src/core/input_plugins/workspace.rs | 6 +- sdk/src/core/native-binding-loader.test.ts | 9 +- sdk/src/core/native-binding-loader.ts | 2 + sdk/src/diagnostic_helpers.rs | 2 +- sdk/src/globals.ts | 2 +- sdk/src/index.ts | 64 +++++++ sdk/src/inputs/AbstractInputCapability.ts | 4 +- .../input-agentskills-export-fallback.test.ts | 2 +- sdk/src/inputs/runtime.ts | 2 +- sdk/src/internal/prompts-legacy.ts | 2 +- sdk/src/internal/sdk-binding.ts | 153 +++++++++-------- sdk/src/lib.rs | 18 ++ .../src/libraries/logger.test.ts | 13 +- sdk/src/libraries/logger.ts | 4 +- sdk/src/libraries/script-runtime/index.ts | 13 +- .../script-runtime}/native-binding.test.ts | 10 +- .../compiler/backward-compat.test.ts | 2 +- .../component-processor.property.test.ts | 0 .../compiler/component-processor.ts | 0 .../component-registry.property.test.ts | 0 .../compiler/component-registry.test.ts | 0 .../compiler/component-registry.ts | 0 .../compiler/export-parser.test.ts | 2 +- .../md-compiler}/compiler/export-parser.ts | 2 +- .../compiler/expression-eval.property.test.ts | 0 .../compiler/expression-eval.test.ts | 2 +- .../md-compiler}/compiler/expression-eval.ts | 2 +- .../src/md-compiler}/compiler/index.ts | 2 +- .../md-compiler}/compiler/jsx-converter.ts | 0 .../compiler/jsx-expression-eval.ts | 0 .../compiler/mdx-to-md.property.test.ts | 2 +- .../md-compiler}/compiler/mdx-to-md.test.ts | 4 +- .../src/md-compiler}/compiler/mdx-to-md.ts | 2 +- .../compiler/parser.property.test.ts | 0 .../src/md-compiler}/compiler/parser.ts | 0 .../src/md-compiler}/compiler/transformer.ts | 0 .../src/md-compiler}/compiler/types.ts | 4 +- .../src/md-compiler}/components/Md.test.ts | 2 +- .../src/md-compiler}/components/Md.ts | 6 +- .../src/md-compiler}/components/index.ts | 4 +- .../src/md-compiler}/errors/index.ts | 0 .../src/md-compiler}/globals/index.ts | 0 .../src => sdk/src/md-compiler}/index.ts | 9 + .../src/md-compiler}/markdown/index.ts | 2 +- .../md-compiler}/markdown/markdown.test.ts | 0 .../markdown/native-binding.test.ts | 10 +- .../src/md-compiler}/mdx-to-md.test.ts | 0 .../src => sdk/src/md-compiler}/mdx-to-md.ts | 2 +- .../src/md-compiler}/native-binding.ts | 6 +- .../src => sdk/src/md-compiler}/toml.test.ts | 0 .../src => sdk/src/md-compiler}/toml.ts | 0 .../src/lib.rs => sdk/src/native_logger.rs | 10 ++ .../native_md_compiler}/expression_eval.rs | 0 .../src => sdk/src/native_md_compiler}/lib.rs | 3 +- .../src/native_md_compiler}/mdx_to_md.rs | 8 +- .../src/native_md_compiler}/parser.rs | 0 .../src/native_md_compiler}/serializer.rs | 2 +- .../src/native_md_compiler}/toml_artifact.rs | 0 .../src/native_md_compiler}/transformer.rs | 8 +- .../src/native_script_runtime.rs | 0 sdk/tsconfig.eslint.json | 8 +- sdk/tsdown.config.ts | 20 ++- sdk/vite.config.ts | 7 - 164 files changed, 874 insertions(+), 1569 deletions(-) delete mode 100644 libraries/logger/Cargo.toml delete mode 100644 libraries/logger/build.rs delete mode 100644 libraries/logger/eslint.config.ts delete mode 100644 libraries/logger/index.d.ts delete mode 100644 libraries/logger/package.json delete mode 100644 libraries/logger/src/index.ts delete mode 100644 libraries/logger/tsconfig.json delete mode 100644 libraries/logger/tsconfig.lib.json delete mode 100644 libraries/logger/tsdown.config.ts delete mode 100644 libraries/md-compiler/Cargo.toml delete mode 100644 libraries/md-compiler/build.rs delete mode 100644 libraries/md-compiler/eslint.config.ts delete mode 100644 libraries/md-compiler/index.d.ts delete mode 100644 libraries/md-compiler/package.json delete mode 100644 libraries/md-compiler/tsconfig.json delete mode 100644 libraries/md-compiler/tsconfig.lib.json delete mode 100644 libraries/md-compiler/tsdown.config.ts delete mode 100644 libraries/md-compiler/vite.config.ts delete mode 100644 libraries/md-compiler/vitest.config.ts delete mode 100644 libraries/script-runtime/Cargo.toml delete mode 100644 libraries/script-runtime/build.rs delete mode 100644 libraries/script-runtime/eslint.config.ts delete mode 100644 libraries/script-runtime/package.json delete mode 100644 libraries/script-runtime/src/index.test.ts delete mode 100644 libraries/script-runtime/src/index.ts delete mode 100644 libraries/script-runtime/src/resolve-proxy-worker.ts delete mode 100644 libraries/script-runtime/src/runtime-core.ts delete mode 100644 libraries/script-runtime/src/types.ts delete mode 100644 libraries/script-runtime/tsconfig.json delete mode 100644 libraries/script-runtime/tsconfig.lib.json delete mode 100644 libraries/script-runtime/tsdown.config.ts create mode 100644 sdk/src/Aindex.test.ts rename libraries/logger/src/index.test.ts => sdk/src/libraries/logger.test.ts (92%) rename {libraries/script-runtime/src => sdk/src/libraries/script-runtime}/native-binding.test.ts (80%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/backward-compat.test.ts (99%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/component-processor.property.test.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/component-processor.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/component-registry.property.test.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/component-registry.test.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/component-registry.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/export-parser.test.ts (97%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/export-parser.ts (99%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/expression-eval.property.test.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/expression-eval.test.ts (99%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/expression-eval.ts (99%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/index.ts (97%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/jsx-converter.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/jsx-expression-eval.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/mdx-to-md.property.test.ts (98%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/mdx-to-md.test.ts (99%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/mdx-to-md.ts (98%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/parser.property.test.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/parser.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/transformer.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/compiler/types.ts (94%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/components/Md.test.ts (98%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/components/Md.ts (94%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/components/index.ts (66%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/errors/index.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/globals/index.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/index.ts (76%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/markdown/index.ts (98%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/markdown/markdown.test.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/markdown/native-binding.test.ts (82%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/mdx-to-md.test.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/mdx-to-md.ts (97%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/native-binding.ts (92%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/toml.test.ts (100%) rename {libraries/md-compiler/src => sdk/src/md-compiler}/toml.ts (100%) rename libraries/logger/src/lib.rs => sdk/src/native_logger.rs (99%) rename {libraries/md-compiler/src => sdk/src/native_md_compiler}/expression_eval.rs (100%) rename {libraries/md-compiler/src => sdk/src/native_md_compiler}/lib.rs (99%) rename {libraries/md-compiler/src => sdk/src/native_md_compiler}/mdx_to_md.rs (99%) rename {libraries/md-compiler/src => sdk/src/native_md_compiler}/parser.rs (100%) rename {libraries/md-compiler/src => sdk/src/native_md_compiler}/serializer.rs (99%) rename {libraries/md-compiler/src => sdk/src/native_md_compiler}/toml_artifact.rs (100%) rename {libraries/md-compiler/src => sdk/src/native_md_compiler}/transformer.rs (99%) rename libraries/script-runtime/src/lib.rs => sdk/src/native_script_runtime.rs (100%) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index b0c922ad..67e2e920 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -4,7 +4,7 @@ # High-risk directories /.github/ @TrueNine /cli/ @TrueNine -/libraries/ @TrueNine +/sdk/ @TrueNine /gui/ @TrueNine /doc/ @TrueNine /scripts/ @TrueNine diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index dfd9d304..2c1c260d 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -5,7 +5,7 @@ ## Scope - [ ] CLI (`cli/`) -- [ ] Shared Rust / N-API libraries (`libraries/`) +- [ ] SDK core (`sdk/`) - [ ] GUI (`gui/`) - [ ] Docs (`doc/`) - [ ] GitHub automation / release chain (`.github/`) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index b8780563..5adfe8e5 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -245,7 +245,7 @@ jobs: - name: MCP tests run: pnpm turbo test --filter=@truenine/memory-sync-mcp - test-libraries: + test-sdk-core: if: github.event.pull_request.draft == false runs-on: ubuntu-24.04 timeout-minutes: 15 @@ -261,8 +261,8 @@ jobs: - name: Build native modules run: pnpm run build:native - - name: Library tests - run: pnpm turbo test --filter=@truenine/logger --filter=@truenine/md-compiler --filter=@truenine/script-runtime + - name: SDK core tests + run: pnpm turbo test --filter=@truenine/memory-sync-sdk test-rust: if: github.event.pull_request.draft == false diff --git a/.github/workflows/release-cli.yml b/.github/workflows/release-cli.yml index 9a80b49a..af787c97 100644 --- a/.github/workflows/release-cli.yml +++ b/.github/workflows/release-cli.yml @@ -3,14 +3,8 @@ name: Release Packages env: NPM_REGISTRY_URL: https://registry.npmjs.org/ CLI_NATIVE_MODULE_DIRS: | - libraries/logger - libraries/md-compiler - libraries/script-runtime sdk CLI_NATIVE_BINDING_PREFIXES: | - napi-logger. - napi-md-compiler. - napi-script-runtime. napi-memory-sync-cli. concurrency: @@ -29,7 +23,7 @@ on: - cli/** - mcp/** - gui/** - - libraries/** + - sdk/** - scripts/** - Cargo.toml - Cargo.lock diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index b3ae05d5..d358fd51 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -16,6 +16,7 @@ We are rats. We accept that. - **Students and beginners**: Genuinely willing to learn and get hands dirty, not here to beg for ready-made answers - **Anyone, any language, any region**: If you use this tool, you are part of the community - **AI Agents**: Automation pipelines, Agent workflows, LLM-driven toolchains — as long as behaviour complies with this code, Issues and PRs from Agents are treated equally + We welcome Issues, PRs, discussions, rants — as long as you are serious, regardless of whether the author is human or Agent. --- @@ -30,6 +31,7 @@ The following behaviours result in immediate Issue closure / PR rejection / acco - **Resource predators**: Stable income, corporate budget, yet competing with marginal developers for free resources and community attention - **Harassment**: Personal attacks, discrimination, stalking, harassing maintainers or other contributors - **Hustle-culture pushers**: Glorify overwork, promote 996, or use this tool to exploit other developers + --- ## Contributor Obligations @@ -40,12 +42,14 @@ If you submit an Issue (human or Agent): - State your OS, Node.js version, and tool version - Agent submissions must include trigger context (call chain, input params, error stack) - Do not rush maintainers — they are humans, not customer support + If you submit a PR (human or Agent): - Open an Issue first to discuss, avoid wasted effort - Follow existing code style (TypeScript strict, functional, immutable-first) - Do not sneak unrelated changes into a PR - Agent-generated PRs must declare the generation tool and prompt source in the description; do not disguise as hand-written + --- ## Maintainer Rights @@ -55,11 +59,13 @@ Maintainers may: - Close any Issue or PR without explanation - Ban any account violating this code - Amend this code at any time + Maintainers are not obligated to: - Respond to every Issue - Accept every PR - Be responsible for anyone's commercial needs + --- ## Licence and Enforcement @@ -67,4 +73,4 @@ Maintainers are not obligated to: This project is licensed under [AGPL-3.0](LICENSE). Commercial use violating the licence will be subject to legal action. -Enforcement of this code of conduct is at the maintainers' sole discretion; final interpretation rests with [@TrueNine](https://github.com/TrueNine). \ No newline at end of file +Enforcement of this code of conduct is at the maintainers' sole discretion; final interpretation rests with [@TrueNine](https://github.com/TrueNine). diff --git a/Cargo.lock b/Cargo.lock index e99c5bc7..bec4a9c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1937,17 +1937,6 @@ dependencies = [ "thiserror 1.0.69", ] -[[package]] -name = "json5" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96b0db21af676c1ce64250b5f40f3ce2cf27e4e47cb91ed91eb6fe9350b430c1" -dependencies = [ - "pest", - "pest_derive", - "serde", -] - [[package]] name = "json5" version = "1.3.1" @@ -2170,7 +2159,7 @@ dependencies = [ [[package]] name = "memory-sync-gui" -version = "2026.10412.11551" +version = "2026.10412.11942" dependencies = [ "dirs", "proptest", @@ -2637,49 +2626,6 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" -[[package]] -name = "pest" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0848c601009d37dfa3430c4666e147e49cdcf1b92ecd3e63657d8a5f19da662" -dependencies = [ - "memchr", - "ucd-trie", -] - -[[package]] -name = "pest_derive" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11f486f1ea21e6c10ed15d5a7c77165d0ee443402f0780849d1768e7d9d6fe77" -dependencies = [ - "pest", - "pest_generator", -] - -[[package]] -name = "pest_generator" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8040c4647b13b210a963c1ed407c1ff4fdfa01c31d6d2a098218702e6664f94f" -dependencies = [ - "pest", - "pest_meta", - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "pest_meta" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89815c69d36021a140146f26659a81d6c2afa33d216d736dd4be5381a7362220" -dependencies = [ - "pest", - "sha2 0.10.9", -] - [[package]] name = "phf" version = "0.8.0" @@ -4505,14 +4451,15 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tnmsc" -version = "2026.10412.11551" +version = "2026.10412.11942" dependencies = [ "base64 0.22.1", "chrono", "clap", "dirs", "globset", - "json5 1.3.1", + "json5", + "markdown", "napi", "napi-build", "napi-derive", @@ -4525,59 +4472,17 @@ dependencies = [ "sha2 0.11.0", "tempfile", "thiserror 2.0.18", - "tnmsc-logger", - "tnmsc-md-compiler", + "wait-timeout", "walkdir", ] [[package]] name = "tnmsc-cli-shell" -version = "2026.10412.11551" +version = "2026.10412.11942" dependencies = [ "clap", "serde_json", "tnmsc", - "tnmsc-logger", -] - -[[package]] -name = "tnmsc-logger" -version = "2026.10412.11551" -dependencies = [ - "napi", - "napi-build", - "napi-derive", - "serde", - "serde_json", -] - -[[package]] -name = "tnmsc-md-compiler" -version = "2026.10412.11551" -dependencies = [ - "json5 0.4.1", - "markdown", - "napi", - "napi-build", - "napi-derive", - "regex-lite", - "serde", - "serde_json", - "serde_yml", - "tnmsc-logger", -] - -[[package]] -name = "tnmsc-script-runtime" -version = "2026.10412.11551" -dependencies = [ - "napi", - "napi-build", - "napi-derive", - "serde", - "serde_json", - "tempfile", - "wait-timeout", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index d030f77f..1fd2d146 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,14 +3,11 @@ resolver = "2" members = [ "sdk", "cli", - "libraries/logger", - "libraries/md-compiler", - "libraries/script-runtime", "gui/src-tauri", ] [workspace.package] -version = "2026.10412.11551" +version = "2026.10412.11942" edition = "2024" rust-version = "1.88" license = "AGPL-3.0-only" @@ -20,9 +17,6 @@ repository = "https://github.com/TrueNine/memory-sync" [workspace.dependencies] # Internal crates tnmsc = { path = "sdk" } -tnmsc-logger = { path = "libraries/logger" } -tnmsc-md-compiler = { path = "libraries/md-compiler" } -tnmsc-script-runtime = { path = "libraries/script-runtime" } # Serialization serde = { version = "1.0.228", features = ["derive"] } diff --git a/README.md b/README.md index fcf40e8b..67e27cda 100644 --- a/README.md +++ b/README.md @@ -6,10 +6,10 @@ I am a rat. No resource is going to walk up and offer itself to me. So as a rat, I eat whatever I can reach: maggots in the sewer, leftovers in a slop bucket, and in extreme cases even my own kind. That is what survival looks like in a world where resource distribution is brutally unequal. `memory-sync` is the same kind of **tool-rat**: - - It does not wait for any platform to hand out an "official all-in-one solution" - It does not rely on the privileged interface of any single IDE or CLI - Any configuration, prompt, memory file, or generated artifact it can read becomes something edible: something to haul away, break apart, and recombine + In this ecosystem, the giants hoard the resources while developers get thrown into a corner like rats. `memory-sync` accepts this cruel reality, does not fantasize about fairness, and focuses on one thing only: **to chew through every fragment of resource you already have and turn it into portable "memory" that can flow between AI tools.** @@ -25,6 +25,7 @@ What can it do for you? - **Control write scope precisely**: use `outputScopes`, `cleanupProtection`, and related settings to constrain writes and cleanup by project, topic, and tool. - **Keep source and derived outputs auditable**: source files, generated artifacts, and target-tool configs stay clearly separated. No hidden source edits. No hidden residue. - **Let memory grow with you**: memory follows you as a person instead of leaking with the project. If a project changes hands, they do not get your context. If you move to another project, your accumulated memory goes with you unchanged. + ## Install ```sh @@ -54,6 +55,7 @@ More platforms are still being added. - **MCP** (`@truenine/memory-sync-mcp`): an stdio server that exposes prompt-asset management to MCP-capable hosts. - **Libraries** (`logger`, `md-compiler`, `script-runtime`): Rust-first shared libraries. - **GUI** (Tauri): the desktop workflow entry, consuming the `tnmsc` crate from `sdk`. + ## FAQ **When AI tools finally have a unified standard, what use will this project be?** @@ -77,37 +79,40 @@ To use `memory-sync` you need: - Solid development experience and long-term exposure to dev tools - Competence with version control (Git) - Competence with the terminal + --- - You are writing code in a forgotten sewer. -No one is going to proactively feed you, not even a tiny free quota, not even a decent document. + No one is going to proactively feed you, not even a tiny free quota, not even a decent document. - As a rat, you were never going to get good food anyway: -you keep scurrying between free tiers, trial credits, education discounts, and random third-party scripts. + you keep scurrying between free tiers, trial credits, education discounts, and random third-party scripts. - What can you do? -Keep darting between IDEs, CLIs, browser extensions, and cloud agents, copying and pasting the same memory a hundred times. + Keep darting between IDEs, CLIs, browser extensions, and cloud agents, copying and pasting the same memory a hundred times. - You keep scraping vendor API deals day after day: -today one platform discounts something, so you top up a little; tomorrow another launches a promotion, so you rush over there too. + today one platform discounts something, so you top up a little; tomorrow another launches a promotion, so you rush over there too. - Once they have harvested the telemetry, user profile, and usage pattern they wanted, -they can kick you away at any moment: price hikes, quotas, bans, and no real channel for complaint. + they can kick you away at any moment: price hikes, quotas, bans, and no real channel for complaint. + If you are barely surviving in this environment, `memory-sync` is built for you: to help you carry a little less brick, paste the same prompt a few fewer times, and at least stop being completely passive around "memory". ## Who is NOT welcome - Your income is already fucking high. -Stable salary, project revenue share, budget to sign official APIs yearly. + Stable salary, project revenue share, budget to sign official APIs yearly. - And yet you still come down here, -competing with us filthy sewer rats for the scraps in the slop bucket. + competing with us filthy sewer rats for the scraps in the slop bucket. - If you can afford APIs and enterprise plans, go pay for them. -Do things that actually create value: pay properly, give proper feedback, and nudge the ecosystem slightly in the right direction. + Do things that actually create value: pay properly, give proper feedback, and nudge the ecosystem slightly in the right direction. - Instead of coming back down -to strip away the tiny gap left for marginalized developers, squeezing out the last crumbs with us rats. + to strip away the tiny gap left for marginalized developers, squeezing out the last crumbs with us rats. - You are a freeloader. -Everything must be pre-chewed and spoon-fed; you will not even touch a terminal. + Everything must be pre-chewed and spoon-fed; you will not even touch a terminal. - You love grind culture. -Treating "hustle" as virtue, "996" as glory, stepping on peers as a promotion strategy. + Treating "hustle" as virtue, "996" as glory, stepping on peers as a promotion strategy. - You leave no room for others. -This is not about whether you share everything. It is about actively stomping on people, competing maliciously, and treating other people's survival space as your stepping stone. + This is not about whether you share everything. It is about actively stomping on people, competing maliciously, and treating other people's survival space as your stepping stone. + In other words: **this is not a tool for optimizing capital cost. It is a small counterattack for the "rats with no choice" in a world of extreme resource inequality.** @@ -115,6 +120,7 @@ In other words: - [TrueNine](https://github.com/TrueNine) - [zjarlin](https://github.com/zjarlin) + ## License -[AGPL-3.0](LICENSE) \ No newline at end of file +[AGPL-3.0](LICENSE) diff --git a/SECURITY.md b/SECURITY.md index aeac0517..6e52b087 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -5,7 +5,7 @@ Only the latest release receives security fixes. No backport patches for older versions. | Version | Supported | -| --- | --- | +|---------|-----------| | Latest | ✅ | | Older | ❌ | @@ -17,12 +17,14 @@ Contact the maintainer privately via: - GitHub Security Advisory: submit a private report under the repository's **Security** tab - Email: contact [@TrueNine](https://github.com/TrueNine) directly + Please include: - Vulnerability description and impact scope - Reproduction steps (minimal example) - Your OS, Node.js version, and `memory-sync` version - Suggested fix if any + ## Response Timeline The maintainer is a person, not a security team. No SLA, no 24-hour response guarantee. @@ -30,6 +32,7 @@ The maintainer is a person, not a security team. No SLA, no 24-hour response gua - Will acknowledge receipt as soon as possible - Will release a patch within a reasonable timeframe after confirmation - Will publicly disclose vulnerability details after the fix is released + Don't rush. ## Scope @@ -39,18 +42,21 @@ Don't rush. - **Reads**: user `.src.mdx` source files, project config files, the global config file (`~/.aindex/.tnmsc.json`), and repository metadata needed for sync - **Writes**: target-tool config directories, managed prompt artifacts such as `dist/`, generated skills / README-like outputs, and related helper configs - **Cleans**: removes stale managed outputs and target-directory residue during sync or cleanup + The following are **out of scope**: - Security vulnerabilities in target AI tools themselves - Compliance of user prompt content - Hardening of third-party dependencies, hosted platforms, or the local workstation outside this repository - External scripts, private plugins, or unmanaged files injected by the user into the workflow + ## Design Principles - **Separation between source and derived state**: source files, generated artifacts, and target-tool configs must stay clearly separated, auditable, and traceable - **Cleanup touches managed outputs only**: cleanup should only remove generated outputs or explicitly configured targets, never silently widen its delete boundary - **No hidden telemetry**: no user data is collected or reported - **External network behavior must be explicit**: core sync logic must not depend on hidden outbound requests; if release or docs-deploy automation talks to npm, GitHub, or Vercel, that behavior must remain visible in workflow files + ## License -This project is licensed under [AGPL-3.0](LICENSE). Unauthorised commercial use in violation of the licence will be pursued legally. \ No newline at end of file +This project is licensed under [AGPL-3.0](LICENSE). Unauthorised commercial use in violation of the licence will be pursued legally. diff --git a/cli-integration-test/package.json b/cli-integration-test/package.json index 5f90d629..78e750c9 100644 --- a/cli-integration-test/package.json +++ b/cli-integration-test/package.json @@ -2,7 +2,7 @@ "name": "@truenine/memory-sync-cli-integration-test", "private": true, "type": "module", - "version": "2026.10412.11551", + "version": "2026.10412.11942", "description": "Container-backed CLI integration tests for tnmsc", "scripts": { "test": "vitest run", diff --git a/cli-integration-test/src/container.ts b/cli-integration-test/src/container.ts index 907b6e8f..d1be988a 100644 --- a/cli-integration-test/src/container.ts +++ b/cli-integration-test/src/container.ts @@ -30,7 +30,7 @@ export interface InstalledCliResolution { readonly mainPackageDir: string readonly platformPackageDir: string readonly resolvedAddonPath: string - readonly scriptRuntimePackagePath: string + readonly sdkPackagePath: string } export interface CliIntegrationFixture { @@ -190,12 +190,12 @@ export class PreparedCliIntegrationContainer { 'const platformPackageDir = process.argv[3];', 'const requireFromBridge = createRequire(path.join(mainPackageDir, "dist", "internal", "native-command-bridge.mjs"));', 'const resolvedAddonPath = requireFromBridge.resolve("@truenine/memory-sync-cli-linux-x64-gnu/napi-memory-sync-cli.linux-x64-gnu.node");', - 'const scriptRuntimePackagePath = requireFromBridge.resolve("@truenine/script-runtime/package.json");', + 'const sdkPackagePath = requireFromBridge.resolve("@truenine/memory-sync-sdk/package.json");', 'process.stdout.write(JSON.stringify({', ' mainPackageDir,', ' platformPackageDir,', ' resolvedAddonPath,', - ' scriptRuntimePackagePath', + ' sdkPackagePath', '}));' ].join(' ') diff --git a/cli-integration-test/src/fixtures.ts b/cli-integration-test/src/fixtures.ts index f9216231..efc79222 100644 --- a/cli-integration-test/src/fixtures.ts +++ b/cli-integration-test/src/fixtures.ts @@ -9,6 +9,9 @@ export const CONTAINER_EXTERNAL_CWD = '/tmp/tnmsc-external' export interface CodexFixtureOptions { readonly seedGlobalSystemSkill?: boolean readonly seedGlobalStaleSkill?: boolean + readonly logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error' + readonly workspaceLocation?: 'root' | 'home' + readonly seedWorkspaceGit?: boolean } interface FixturePluginFlags { @@ -62,15 +65,19 @@ function writeTextFile(filePath: string, content: string): void { function writeGlobalConfig( homeDir: string, - plugins: FixturePluginFlags + plugins: FixturePluginFlags, + options: { + readonly workspaceDir: string + readonly logLevel: 'trace' | 'debug' | 'info' | 'warn' | 'error' + } ): void { const configPath = path.join(homeDir, '.aindex', '.tnmsc.json') writeTextFile( configPath, JSON.stringify( { - workspaceDir: CONTAINER_WORKSPACE_DIR, - logLevel: 'warn', + workspaceDir: options.workspaceDir, + logLevel: options.logLevel, plugins }, null, @@ -202,6 +209,10 @@ function writeManagedProjectFixtures(workspaceDir: string): void { ensureDir(path.join(workspaceDir, 'aindex', 'dist', 'app', 'project-a')) } +function seedWorkspaceGit(workspaceDir: string): void { + ensureDir(path.join(workspaceDir, '.git')) +} + function writeProjectPromptFixtures(workspaceDir: string): void { writeTextFile( path.join(workspaceDir, 'aindex', 'app', 'project-a', 'agt.src.mdx'), @@ -271,18 +282,31 @@ export function createCodexFixture( ): CodexFixture { const rootDir = mkdtempSync(path.join(tmpdir(), 'tnmsc-codex-fixture-')) const homeDir = path.join(rootDir, 'home') - const workspaceDir = path.join(rootDir, 'workspace') + const workspaceLocation = options.workspaceLocation ?? 'root' + const workspaceDir = workspaceLocation === 'home' + ? path.join(homeDir, 'workspace') + : path.join(rootDir, 'workspace') + const workspaceDirConfig = workspaceLocation === 'home' + ? '~/workspace' + : CONTAINER_WORKSPACE_DIR + const workspaceContainerDir = workspaceLocation === 'home' + ? path.posix.join(CONTAINER_HOME_DIR, 'workspace') + : CONTAINER_WORKSPACE_DIR writeGlobalConfig(homeDir, { codex: true, claudeCode: false, git: false, readme: false + }, { + workspaceDir: workspaceDirConfig, + logLevel: options.logLevel ?? 'warn' }) writeCommandFixtures(workspaceDir) writeSubAgentFixtures(workspaceDir) writeSkillFixtures(workspaceDir) writeManagedProjectFixtures(workspaceDir) + if (options.seedWorkspaceGit === true) seedWorkspaceGit(workspaceDir) seedGlobalCodexSkills(homeDir, options) return { @@ -297,20 +321,20 @@ export function createCodexFixture( 'find-opensource.md' ), workspaceCommand: path.posix.join( - CONTAINER_WORKSPACE_DIR, + workspaceContainerDir, '.codex', 'prompts', 'find-opensource.md' ), projectAgent: path.posix.join( - CONTAINER_WORKSPACE_DIR, + workspaceContainerDir, 'project-a', '.codex', 'agents', 'qa-reviewer.toml' ), projectSkill: path.posix.join( - CONTAINER_WORKSPACE_DIR, + workspaceContainerDir, 'project-a', '.codex', 'skills', @@ -318,7 +342,7 @@ export function createCodexFixture( 'SKILL.md' ), projectSkillMcp: path.posix.join( - CONTAINER_WORKSPACE_DIR, + workspaceContainerDir, 'project-a', '.codex', 'skills', @@ -356,6 +380,9 @@ export function createClaudeCodeFixture(): ClaudeCodeFixture { claudeCode: true, git: false, readme: false + }, { + workspaceDir: CONTAINER_WORKSPACE_DIR, + logLevel: 'warn' }) writeGlobalMemoryFixtures(workspaceDir) writeCommandFixtures(workspaceDir) diff --git a/cli-integration-test/test/claude-code-cli.integration.test.ts b/cli-integration-test/test/claude-code-cli.integration.test.ts index 511d770f..9eda7c3d 100644 --- a/cli-integration-test/test/claude-code-cli.integration.test.ts +++ b/cli-integration-test/test/claude-code-cli.integration.test.ts @@ -53,7 +53,7 @@ describeForHost('claude code cli integration', () => { expect(installedResolution.mainPackageDir).toContain('@truenine+memory-sync-cli@file') expect(installedResolution.platformPackageDir).toContain('@truenine+memory-sync-cli-linux-x64-gnu@file') expect(installedResolution.resolvedAddonPath).toContain('@truenine+memory-sync-cli-linux-x64-gnu@file') - expect(installedResolution.scriptRuntimePackagePath).toContain('@truenine+script-runtime@file') + expect(installedResolution.sdkPackagePath).toContain('@truenine+memory-sync-sdk@file') const help = container.assertExecSuccess('tnmsc help') expect(help.stdout).toContain('install') diff --git a/cli-integration-test/test/codex.integration.test.ts b/cli-integration-test/test/codex.integration.test.ts index fe400b0b..67ad3ffb 100644 --- a/cli-integration-test/test/codex.integration.test.ts +++ b/cli-integration-test/test/codex.integration.test.ts @@ -1,6 +1,7 @@ import type {CliIntegrationArtifacts} from '../src/artifacts' import type {CodexFixture} from '../src/fixtures' import {beforeAll, describe, expect, it} from 'vitest' +import path from 'node:path' import {prepareCliIntegrationArtifacts} from '../src/artifacts' import { PreparedCliIntegrationContainer, @@ -18,6 +19,16 @@ function expectSuccess(exitCode: number): void { expect(exitCode).toBe(0) } +function expectNoLegacyNoise(output: string): void { + expect(output).not.toContain('Aindex is not inside a Git repository') + expect(output).not.toContain('Prepared output plan') + expect(output).not.toContain('Removed stale generated files') + expect(output).not.toContain('Wrote output files') + expect(output).not.toContain('cleanup native') + expect(output).not.toContain('Current directory:') + expect(output).not.toContain('**Context**') +} + async function withCodexEnvironment( artifacts: CliIntegrationArtifacts, fixture: CodexFixture, @@ -53,7 +64,7 @@ describeForHost('codex cli integration', () => { expect(installedResolution.mainPackageDir).toContain('@truenine+memory-sync-cli@file') expect(installedResolution.platformPackageDir).toContain('@truenine+memory-sync-cli-linux-x64-gnu@file') expect(installedResolution.resolvedAddonPath).toContain('@truenine+memory-sync-cli-linux-x64-gnu@file') - expect(installedResolution.scriptRuntimePackagePath).toContain('@truenine+script-runtime@file') + expect(installedResolution.sdkPackagePath).toContain('@truenine+memory-sync-sdk@file') const help = container.assertExecSuccess('tnmsc help') expect(help.stdout).toContain('install') @@ -156,4 +167,37 @@ describeForHost('codex cli integration', () => { expect(container.pathExists(fixture.outputPaths.globalSystemSkill)).toBe(true) }) }) + + it('runs the packed dist entry with tilde workspace config, resolves parent git, and keeps output concise', async () => { + const fixture = createCodexFixture({ + logLevel: 'info', + workspaceLocation: 'home', + seedWorkspaceGit: true + }) + + await withCodexEnvironment(artifacts, fixture, async container => { + const installedResolution = container.inspectInstalledCliResolution() + const cliDistEntry = path.posix.join(installedResolution.mainPackageDir, 'dist', 'index.mjs') + + const result = container.exec(`node "${cliDistEntry}"`, CONTAINER_EXTERNAL_CWD) + expectSuccess(result.exitCode) + + expect(result.stderr).toContain('### Running outside the workspace') + expect(result.stderr).toContain('tnmsc will sync "/root/workspace" and every managed project from the current directory.') + expect(result.stderr).toContain('Run tnmsc in "/root/workspace" for workspace-only sync, or inside a managed project for project-only sync.') + expect(result.stderr).not.toContain('/tmp/~/workspace') + + expect(result.stdout).toContain('### Wrote outputs') + expect(result.stdout).toContain('### Sync complete') + expect(result.stdout).not.toContain('### version control detected') + + expectNoLegacyNoise(result.stdout) + expectNoLegacyNoise(result.stderr) + + expect(container.pathExists(fixture.outputPaths.globalCommand)).toBe(true) + expect(container.pathExists(fixture.outputPaths.projectAgent)).toBe(true) + expect(container.pathExists(fixture.outputPaths.projectSkill)).toBe(true) + expect(container.pathExists(fixture.outputPaths.projectSkillMcp)).toBe(true) + }) + }) }) diff --git a/cli/Cargo.toml b/cli/Cargo.toml index f7e98554..ff58fefb 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -14,6 +14,5 @@ path = "src/main.rs" [dependencies] tnmsc = { workspace = true } -tnmsc-logger = { workspace = true } clap = { workspace = true } serde_json = { workspace = true } diff --git a/cli/npm/darwin-arm64/package.json b/cli/npm/darwin-arm64/package.json index 90e30860..3c30f75c 100644 --- a/cli/npm/darwin-arm64/package.json +++ b/cli/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@truenine/memory-sync-cli-darwin-arm64", - "version": "2026.10412.11551", + "version": "2026.10412.11942", "os": [ "darwin" ], diff --git a/cli/npm/darwin-x64/package.json b/cli/npm/darwin-x64/package.json index 14419158..25905771 100644 --- a/cli/npm/darwin-x64/package.json +++ b/cli/npm/darwin-x64/package.json @@ -1,6 +1,6 @@ { "name": "@truenine/memory-sync-cli-darwin-x64", - "version": "2026.10412.11551", + "version": "2026.10412.11942", "os": [ "darwin" ], diff --git a/cli/npm/linux-arm64-gnu/package.json b/cli/npm/linux-arm64-gnu/package.json index 82b41cae..1b096d5c 100644 --- a/cli/npm/linux-arm64-gnu/package.json +++ b/cli/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@truenine/memory-sync-cli-linux-arm64-gnu", - "version": "2026.10412.11551", + "version": "2026.10412.11942", "os": [ "linux" ], diff --git a/cli/npm/linux-x64-gnu/package.json b/cli/npm/linux-x64-gnu/package.json index 0de722bc..009e8347 100644 --- a/cli/npm/linux-x64-gnu/package.json +++ b/cli/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@truenine/memory-sync-cli-linux-x64-gnu", - "version": "2026.10412.11551", + "version": "2026.10412.11942", "os": [ "linux" ], diff --git a/cli/npm/win32-x64-msvc/package.json b/cli/npm/win32-x64-msvc/package.json index 6416ed17..169af54a 100644 --- a/cli/npm/win32-x64-msvc/package.json +++ b/cli/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@truenine/memory-sync-cli-win32-x64-msvc", - "version": "2026.10412.11551", + "version": "2026.10412.11942", "os": [ "win32" ], diff --git a/cli/package.json b/cli/package.json index 664fd369..a9f1e274 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,7 +1,7 @@ { "name": "@truenine/memory-sync-cli", "type": "module", - "version": "2026.10412.11551", + "version": "2026.10412.11942", "description": "TrueNine Memory Synchronization CLI shell", "author": "TrueNine", "license": "AGPL-3.0-only", @@ -76,14 +76,12 @@ "@truenine/memory-sync-cli-linux-arm64-gnu": "workspace:*", "@truenine/memory-sync-cli-linux-x64-gnu": "workspace:*", "@truenine/memory-sync-cli-win32-x64-msvc": "workspace:*", - "@truenine/script-runtime": "workspace:*", "json5": "catalog:", "yaml": "catalog:", "zod": "catalog:" }, "devDependencies": { "@truenine/eslint10-config": "catalog:", - "@truenine/logger": "workspace:*", "@truenine/memory-sync-sdk": "workspace:*", "@types/node": "catalog:", "@vitest/coverage-v8": "catalog:", diff --git a/cli/src/cli-runtime.ts b/cli/src/cli-runtime.ts index b4753dd0..03406ee0 100644 --- a/cli/src/cli-runtime.ts +++ b/cli/src/cli-runtime.ts @@ -1,8 +1,7 @@ import type {MemorySyncAdaptorInfo, MemorySyncCommandResult} from '@truenine/memory-sync-sdk' import process from 'node:process' -import {flushOutput, setGlobalLogLevel} from '@truenine/logger' -import {getMemorySyncSdkBinding} from '@truenine/memory-sync-sdk' +import {flushOutput, getMemorySyncSdkBinding, setGlobalLogLevel} from '@truenine/memory-sync-sdk' import {extractUserArgs, parseArgs} from './cli-args' const CLI_NAME = 'tnmsc' diff --git a/cli/src/cli.rs b/cli/src/cli.rs index c9a3538a..c2bdc8f7 100644 --- a/cli/src/cli.rs +++ b/cli/src/cli.rs @@ -99,13 +99,13 @@ impl ResolvedLogLevel { } } - pub fn to_logger_level(self) -> tnmsc_logger::LogLevel { + pub fn to_logger_level(self) -> tnmsc::logger::LogLevel { match self { - Self::Trace => tnmsc_logger::LogLevel::Trace, - Self::Debug => tnmsc_logger::LogLevel::Debug, - Self::Info => tnmsc_logger::LogLevel::Info, - Self::Warn => tnmsc_logger::LogLevel::Warn, - Self::Error => tnmsc_logger::LogLevel::Error, + Self::Trace => tnmsc::logger::LogLevel::Trace, + Self::Debug => tnmsc::logger::LogLevel::Debug, + Self::Info => tnmsc::logger::LogLevel::Info, + Self::Warn => tnmsc::logger::LogLevel::Warn, + Self::Error => tnmsc::logger::LogLevel::Error, } } } diff --git a/cli/src/main.rs b/cli/src/main.rs index 7ceccdf6..9cd4fa68 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -9,7 +9,7 @@ mod commands; use std::process::ExitCode; use clap::Parser; -use tnmsc_logger::{flush_output, set_global_log_level}; +use tnmsc::logger::{flush_output, set_global_log_level}; use cli::{Cli, ResolvedCommand, resolve_command, resolve_log_level}; diff --git a/cli/src/script-runtime-worker.ts b/cli/src/script-runtime-worker.ts index d29cfaed..a9446a9c 100644 --- a/cli/src/script-runtime-worker.ts +++ b/cli/src/script-runtime-worker.ts @@ -1,6 +1,6 @@ import {readFileSync} from 'node:fs' import process from 'node:process' -import {resolvePublicPathUnchecked} from '@truenine/script-runtime' +import {resolvePublicPathUnchecked} from '@truenine/memory-sync-sdk' async function main(): Promise { const [, , filePath, ctxJsonPath, logicalPath] = process.argv diff --git a/cli/src/tsdown-config.test.ts b/cli/src/tsdown-config.test.ts index 1dc3981c..ffb61486 100644 --- a/cli/src/tsdown-config.test.ts +++ b/cli/src/tsdown-config.test.ts @@ -1,4 +1,3 @@ -import {resolve} from 'node:path' import {describe, expect, it} from 'vitest' import tsconfig from '../tsconfig.json' import tsdownConfig from '../tsdown.config' @@ -18,21 +17,15 @@ function includesEntry(config: TsdownEntryConfig, targetEntry: string): boolean } describe('cli tsdown config', () => { - it('lets TypeScript resolve the script runtime package through workspace metadata', () => { + it('keeps worker bundling anchored on the sdk package only', () => { const paths = tsconfig.compilerOptions.paths as Record - expect(paths['@truenine/script-runtime']).toBeUndefined() - }) - - it('bundles the worker against the built script runtime module', () => { const workerConfig = (tsdownConfig as readonly TsdownEntryConfig[]).find(config => includesEntry(config, './src/script-runtime-worker.ts')) - expect(workerConfig?.alias?.['@truenine/script-runtime']).toBe( - resolve('../libraries/script-runtime/dist/index.mjs') - ) + expect(paths['@truenine/script-runtime']).toBeUndefined() + expect(workerConfig?.alias).toBeUndefined() expect(workerConfig?.deps?.alwaysBundle).toEqual(expect.arrayContaining([ - '@truenine/memory-sync-sdk', - '@truenine/script-runtime' + '@truenine/memory-sync-sdk' ])) expect(workerConfig?.deps?.neverBundle).toEqual(expect.arrayContaining(['jiti'])) }) diff --git a/cli/tsdown.config.ts b/cli/tsdown.config.ts index fcff3722..c357f6f5 100644 --- a/cli/tsdown.config.ts +++ b/cli/tsdown.config.ts @@ -1,8 +1,6 @@ -import {resolve} from 'node:path' import {defineConfig} from 'tsdown' const alwaysBundleDeps = ['@truenine/memory-sync-sdk'] -const scriptRuntimeWorkerBundleDeps = [...alwaysBundleDeps, '@truenine/script-runtime'] const neverBundleDeps = ['jiti'] export default defineConfig([ @@ -41,12 +39,9 @@ export default defineConfig([ platform: 'node', sourcemap: false, deps: { - alwaysBundle: scriptRuntimeWorkerBundleDeps, + alwaysBundle: alwaysBundleDeps, neverBundle: neverBundleDeps }, - alias: { - '@truenine/script-runtime': resolve('../libraries/script-runtime/dist/index.mjs') - }, format: ['esm'], minify: true, dts: false diff --git a/doc/content/sdk/architecture.mdx b/doc/content/sdk/architecture.mdx index f23c2d4f..77ca6a64 100644 --- a/doc/content/sdk/architecture.mdx +++ b/doc/content/sdk/architecture.mdx @@ -20,13 +20,13 @@ import { Callout, Cards, Steps, Tabs } from 'nextra/components' - 拥有 Rust crate `tnmsc` 的实际 workspace 路径和 facade 定义 - 提供 npm 包 `@truenine/memory-sync-sdk` 作为内部消费者(`cli/`、`mcp/`、`gui/`)的统一依赖入口 - 负责 Prompt Service 的实现(基于 MDX-Compiler)、Schema 生成以及最小化的 TypeScript loader 入口 -- 编排 Logger、MDX-Compiler、Script-Runtime 三类基础能力;其中 Logger / Script-Runtime 的 TypeScript facade 已内联到 `sdk/src/libraries/*`,`libraries/*` 保留 Rust crate 与发布壳层 +- 编排 Logger、MDX-Compiler、Script-Runtime 三类基础能力;其中 Logger / Script-Runtime 的 TypeScript facade 已内联到 `sdk/src/sdk/*`,`sdk/*` 保留 Rust crate 与发布壳层 -**消费者依赖方向**是单向的:`cli/`、`mcp/`、`gui/` 都依赖 `sdk/`。在 `sdk/` 下游,MDX-Compiler 仍完整保留在 `libraries/`,而 Logger / Script-Runtime 已形成“`sdk/src/libraries/*` 作为 TypeScript 事实来源 + `libraries/*` 作为 Rust crate / wrapper 发布层”的分层。这种边界确保了核心逻辑不会散落在多个入口中,也避免了 `cli/` 再次成为隐式的事实来源。 +**消费者依赖方向**是单向的:`cli/`、`mcp/`、`gui/` 都依赖 `sdk/`。在 `sdk/` 下游,MDX-Compiler 仍完整保留在 `sdk/`,而 Logger / Script-Runtime 已形成“`sdk/src/sdk/*` 作为 TypeScript 事实来源 + `sdk/*` 作为 Rust crate / wrapper 发布层”的分层。这种边界确保了核心逻辑不会散落在多个入口中,也避免了 `cli/` 再次成为隐式的事实来源。 ## 为什么还保留 Libraries 层 -`libraries/` 仍然有存在价值,但它现在主要承载 **Rust-first** 的 crate、本地 NAPI 制品和对外发布 wrapper,而不再默认承担全部 TypeScript 事实来源。它们覆盖了 `tnmsc` 工具链中性能最关键的路径: +`sdk/` 仍然有存在价值,但它现在主要承载 **Rust-first** 的 crate、本地 NAPI 制品和对外发布 wrapper,而不再默认承担全部 TypeScript 事实来源。它们覆盖了 `tnmsc` 工具链中性能最关键的路径: | 性能关键路径 | 对应 Library | Rust 提供的优势 | | --- | --- | --- | @@ -34,7 +34,7 @@ import { Callout, Cards, Steps, Tabs } from 'nextra/components' | MDX 解析与转换 | MDX-Compiler | 原生 AST 遍历、零成本抽象的编译器流水线 | | 路径规范化与安全验证 | Script-Runtime | OS 级路径遍历防护、进程隔离的超时控制 | -将这些能力下沉到独立的 Rust crate 中,使得 `gui/`(Tauri 应用)可以直接调用 crate 而无需 NAPI 开销,同时也让每个库可以独立演进和测试。当前只有 Logger / Script-Runtime 的 TypeScript facade 回收到了 `sdk/src/libraries/*`;`md-compiler` 仍完整保留在 `libraries/`。 +将这些能力下沉到独立的 Rust crate 中,使得 `gui/`(Tauri 应用)可以直接调用 crate 而无需 NAPI 开销,同时也让每个库可以独立演进和测试。当前只有 Logger / Script-Runtime 的 TypeScript facade 回收到了 `sdk/src/sdk/*`;`md-compiler` 仍完整保留在 `sdk/`。 --- @@ -50,25 +50,25 @@ graph TB subgraph SDK["@truenine/memory-sync-sdk
私有混合核心"] SDKCore["SDK Core
Prompt Service / Schema / Bridge"] - LOG_TS["sdk/src/libraries/logger.ts
(Logger TS facade)"] - MDC_TS["libraries/md-compiler/src/index.ts
(MDX-Compiler TS API)"] - SR_TS["sdk/src/libraries/script-runtime
(Script-Runtime TS facade)"] + LOG_TS["sdk/src/sdk/logger.ts
(Logger TS facade)"] + MDC_TS["sdk/src/md-compiler/src/index.ts
(MDX-Compiler TS API)"] + SR_TS["sdk/src/sdk/script-runtime
(Script-Runtime TS facade)"] end subgraph Libraries["Workspace Libraries (Rust-first)"] direction LR subgraph L1["Logger
基础设施层"] - LOG_R["tnmsc-logger
(Rust crate)"] - LOG_PKG["@truenine/logger
(wrapper package)"] + LOG_R["tnmsc
(Rust crate)"] + LOG_PKG["@truenine/memory-sync-sdk
(wrapper package)"] end subgraph L2["MDX-Compiler
编译层"] - MDC_R["tnmsc-md-compiler
(Rust crate)"] + MDC_R["tnmsc
(Rust crate)"] end subgraph L3["Script-Runtime
运行时层"] - SR_R["tnmsc-script-runtime
(Rust crate)"] - SR_PKG["@truenine/script-runtime
(wrapper package)"] + SR_R["tnmsc
(Rust crate)"] + SR_PKG["@truenine/memory-sync-sdk
(wrapper package)"] end end @@ -113,18 +113,18 @@ graph TB ### Logger — 基础设施层 -Logger 是整个依赖树的 **叶子节点之一**(另一个是 Script-Runtime),不依赖任何其他 workspace library。当前 `sdk/src/libraries/logger.ts` 是 TypeScript 事实来源,而 `libraries/logger/src/index.ts` 只保留对外发布 wrapper。 +Logger 是整个依赖树的 **叶子节点之一**(另一个是 Script-Runtime),不依赖任何其他 workspace library。当前 `sdk/src/sdk/logger.ts` 是 TypeScript 事实来源,而 `sdk/src/sdk/logger.ts` 只保留对外发布 wrapper。 ```mermaid graph LR SDK["@truenine/memory-sync-sdk"] --> LOGGER["Logger facade"] - MDC["@truenine/md-compiler"] --> LOGGER + MDC["@truenine/memory-sync-sdk"] --> LOGGER - subgraph Logger["tnmsc-logger / Logger"] + subgraph Logger["tnmsc / Logger"] L_CORE["Rust 核心
lib.rs"] L_NAPI["NAPI Binding
条件编译"] - L_TS["TS facade
sdk/src/libraries/logger.ts"] - L_WRAPPER["wrapper
libraries/logger/src/index.ts"] + L_TS["TS facade
sdk/src/sdk/logger.ts"] + L_WRAPPER["wrapper
sdk/src/sdk/logger.ts"] L_WORKER["Output Worker
异步线程"] end @@ -156,10 +156,10 @@ MDX-Compiler 位于依赖树的中层,**仅依赖 Logger**,被 SDK 的 Promp ```mermaid graph LR - SDK["@truenine/memory-sync-sdk"] --> MDC["@truenine/md-compiler"] - MDC --> LOGGER["@truenine/logger"] + SDK["@truenine/memory-sync-sdk"] --> MDC["@truenine/memory-sync-sdk"] + MDC --> LOGGER["@truenine/memory-sync-sdk"] - subgraph MDXCompiler["tnmsc-md-compiler / @truenine/md-compiler"] + subgraph MDXCompiler["tnmsc / @truenine/memory-sync-sdk"] direction TB MC_PARSER["Parser
unified + remark 插件链"] MC_EXPR["Expression Eval
简单引用 / Function 构造器"] @@ -201,9 +201,9 @@ Script-Runtime 是依赖树中的 **另一个叶子节点**,与其他两个 li ```mermaid graph LR - SDK["@truenine/memory-sync-sdk"] --> SR["@truenine/script-runtime"] + SDK["@truenine/memory-sync-sdk"] --> SR["@truenine/memory-sync-sdk"] - subgraph ScriptRuntime["tnmsc-script-runtime / @truenine/script-runtime"] + subgraph ScriptRuntime["tnmsc / @truenine/memory-sync-sdk"] direction TB SR_LOADER["Module Loader
Jiti Runtime"] SR_PATH["Path Validator
Rust 原生绑定"] @@ -318,17 +318,17 @@ SDK 的构建是一个多阶段的有序流水线,从 Rust 源码到最终的 ```bash # TypeScript 编译(并行) - pnpm -F @truenine/logger -F @truenine/md-compiler -F @truenine/script-runtime run build:ts + pnpm -F @truenine/memory-sync-sdk -F @truenine/memory-sync-sdk -F @truenine/memory-sync-sdk run build:ts # Native binding 构建(按依赖顺序) - pnpm -F @truenine/logger -F @truenine/script-runtime run build # 无相互依赖,可并行 - pnpm -F @truenine/md-compiler run build:native # 依赖 logger 的 .node 文件 + pnpm -F @truenine/memory-sync-sdk -F @truenine/memory-sync-sdk run build # 无相互依赖,可并行 + pnpm -F @truenine/memory-sync-sdk run build:native # 依赖 logger 的 .node 文件 ``` 此阶段产出: - - `libraries/logger/dist/index.js` + `napi-logger.*.node` - - `libraries/md-compiler/dist/index.js` + `napi-md-compiler.*.node` - - `libraries/script-runtime/dist/index.js` + `napi-script-runtime.*.node` + - `sdk/src/native_logger.rsdist/index.js` + `napi-logger.*.node` + - `sdk/src/md-compiler/dist/index.js` + `napi-md-compiler.*.node` + - `sdk/src/sdk/script-runtime/dist/index.js` + `napi-script-runtime.*.node` ### Step 2: SDK Native Binding 编译 @@ -389,7 +389,7 @@ memory-sync/ │ │ ├── index.ts # 公共 API 入口 │ │ ├── core/ │ │ │ └── native-binding-loader.ts # 统一绑定加载器 -│ │ ├── libraries/ +│ │ ├── sdk/ │ │ │ ├── logger.ts # Logger TS facade (事实来源) │ │ │ └── script-runtime/ # Script-Runtime TS facade (事实来源) │ │ ├── adaptors/ # 输出适配器 @@ -402,13 +402,13 @@ memory-sync/ │ ├── generate-schema.ts # Schema 生成 │ └── finalize-bundle.ts # Bundle 后处理 │ -├── libraries/ # Rust-first workspace 库 +├── sdk/ # Rust-first workspace 库 │ ├── logger/ # 日志库 │ │ ├── src/ │ │ │ ├── lib.rs # Rust 核心 (LogLevel, Logger, OutputWorker, NAPI) -│ │ │ └── index.ts # 发布 wrapper (re-export sdk/src/libraries/logger.ts) -│ │ ├── Cargo.toml # tnmsc-logger crate -│ │ └── package.json # @truenine/logger +│ │ │ └── index.ts # 发布 wrapper (re-export sdk/src/sdk/logger.ts) +│ │ ├── Cargo.toml # tnmsc crate +│ │ └── package.json # @truenine/memory-sync-sdk │ │ │ ├── md-compiler/ # 编译器 │ │ ├── src/ @@ -431,15 +431,15 @@ memory-sync/ │ │ │ ├── globals/ # 全局作用域定义 │ │ │ ├── toml.ts # TOML 构建 │ │ │ └── errors/ # 错误类型体系 -│ │ ├── Cargo.toml # tnmsc-md-compiler crate -│ │ └── package.json # @truenine/md-compiler +│ │ ├── Cargo.toml # tnmsc crate +│ │ └── package.json # @truenine/memory-sync-sdk │ │ │ └── script-runtime/ # 运行时 │ ├── src/ │ │ ├── lib.rs # Rust 核心 (validate/resolve_public_path) -│ │ └── index.ts # 发布 wrapper (re-export sdk/src/libraries/script-runtime) -│ ├── Cargo.toml # tnmsc-script-runtime crate -│ └── package.json # @truenine/script-runtime +│ │ └── index.ts # 发布 wrapper (re-export sdk/src/sdk/script-runtime) +│ ├── Cargo.toml # tnmsc crate +│ └── package.json # @truenine/memory-sync-sdk ``` ### 关键文件职责映射 @@ -451,15 +451,15 @@ memory-sync/ | `sdk/src/ConfigLoader.ts` | SDK | 配置文件加载与验证 | Logger, Zod | | `sdk/src/runtime-environment.ts` | SDK | 运行时环境初始化 | Logger | | `sdk/src/core/native-binding-loader.ts` | SDK | 统一的 NAPI binding 加载(消除重复) | — | -| `sdk/src/libraries/logger.ts` | SDK | Logger TypeScript facade、`ILogger` 适配器、共享加载器接入 | Logger Rust crate | -| `sdk/src/libraries/script-runtime/index.ts` | SDK | Script-Runtime TypeScript facade、Worker 路径发现、共享加载器接入 | Script-Runtime Rust crate | -| `sdk/src/libraries/script-runtime/runtime-core.ts` | SDK | Jiti 加载、代理路由分发 | — | -| `libraries/logger/src/lib.rs` | Logger | Rust 核心:日志级别、格式化、诊断、OutputWorker | — | -| `libraries/logger/src/index.ts` | Logger | 发布 wrapper:re-export `sdk/src/libraries/logger.ts` | — | -| `libraries/md-compiler/src/compiler/` | MDX-Compiler | 编译器流水线全组件 | Logger (workspace) | -| `libraries/md-compiler/src/native-binding.ts` | MDX-Compiler | 共享加载器接入、env flag gate、binding validator | — | -| `libraries/script-runtime/src/lib.rs` | Script-Runtime | Rust 核心:路径验证、Worker 管理 | — | -| `libraries/script-runtime/src/index.ts` | Script-Runtime | 发布 wrapper:re-export `sdk/src/libraries/script-runtime` | — | +| `sdk/src/sdk/logger.ts` | SDK | Logger TypeScript facade、`ILogger` 适配器、共享加载器接入 | Logger Rust crate | +| `sdk/src/sdk/src/sdk/script-runtime/index.ts` | SDK | Script-Runtime TypeScript facade、Worker 路径发现、共享加载器接入 | Script-Runtime Rust crate | +| `sdk/src/sdk/src/sdk/script-runtime/runtime-core.ts` | SDK | Jiti 加载、代理路由分发 | — | +| `sdk/src/native_logger.rs` | Logger | Rust 核心:日志级别、格式化、诊断、OutputWorker | — | +| `sdk/src/sdk/logger.ts` | Logger | 发布 wrapper:re-export `sdk/src/sdk/logger.ts` | — | +| `sdk/src/md-compiler/compiler/` | MDX-Compiler | 编译器流水线全组件 | Logger (workspace) | +| `sdk/src/md-compiler/native-binding.ts` | MDX-Compiler | 共享加载器接入、env flag gate、binding validator | — | +| `sdk/src/native_script_runtime.rs` | Script-Runtime | Rust 核心:路径验证、Worker 管理 | — | +| `sdk/src/sdk/src/sdk/script-runtime/index.ts` | Script-Runtime | 发布 wrapper:re-export `sdk/src/sdk/script-runtime` | — | --- @@ -585,13 +585,13 @@ TypeScript 层的价值,不只是“把 Rust 包起来”。 ### 新库扩展指南 -当需要在 `libraries/` 下添加新的 workspace library 时,遵循以下约定: +当需要在 `sdk/` 下添加新的 workspace library 时,遵循以下约定: ### 1. 创建目录结构 ``` - libraries/new-lib/ + sdk/new-lib/ ├── src/ │ ├── lib.rs # Rust 核心(如有 native 需求) │ └── index.ts # TypeScript 入口 / 绑定层 diff --git a/doc/content/sdk/index.mdx b/doc/content/sdk/index.mdx index aac759d3..a82da4b0 100644 --- a/doc/content/sdk/index.mdx +++ b/doc/content/sdk/index.mdx @@ -18,7 +18,7 @@ import { Callout, Cards } from 'nextra/components' - 它负责 Rust crate `tnmsc` 的 facade、NAPI 构建、prompt service、schema 生成,以及最小化的 TypeScript loader 入口 - 它仍然承接少量过渡期 bridge 逻辑,但这些 bridge 路径已经退回到 `sdk/` 内部实现,不再是 `cli/` 的公共组合中心 - 它是 `mcp/`、`gui/` 以及未来内部消费者的默认依赖入口 -- 它编排 Logger、MDX-Compiler、Script-Runtime 三类基础能力;其中 Logger 和 Script-Runtime 的 TypeScript facade 已内联到 `sdk/src/libraries/*`,`libraries/*` 保留 Rust crate 与发布壳层 +- 它编排 Logger、MDX-Compiler、Script-Runtime 三类基础能力;其中 Logger 和 Script-Runtime 的 TypeScript facade 已内联到 `sdk/src/sdk/*`,`sdk/*` 保留 Rust crate 与发布壳层 ## 这一层不负责什么 @@ -87,7 +87,7 @@ import { Callout, Cards } from 'nextra/components' | `mcp/` | 通过 `@truenine/memory-sync-sdk` 的最小 binding 访问 prompt 管理能力 | | `gui/src-tauri` | 继续依赖 crate `tnmsc`,其实际路径现在位于 `sdk/` 下 | -消费者依赖方向是**单向**的:`cli/`、`mcp/`、`gui/` 都依赖 `sdk/`。在 `sdk/` 下游,MDX-Compiler 仍完整保留在 `libraries/`,而 Logger / Script-Runtime 已形成“`sdk/src/libraries/*` 作为 TypeScript 事实来源 + `libraries/*` 作为 Rust crate / wrapper 发布层”的边界。Library 之间的依赖为:MDX-Compiler → Logger;Logger 和 Script-Runtime 互不依赖。 +消费者依赖方向是**单向**的:`cli/`、`mcp/`、`gui/` 都依赖 `sdk/`。在 `sdk/` 下游,MDX-Compiler 仍完整保留在 `sdk/`,而 Logger / Script-Runtime 已形成“`sdk/src/sdk/*` 作为 TypeScript 事实来源 + `sdk/*` 作为 Rust crate / wrapper 发布层”的边界。Library 之间的依赖为:MDX-Compiler → Logger;Logger 和 Script-Runtime 互不依赖。 ## 边界规则 @@ -99,7 +99,7 @@ import { Callout, Cards } from 'nextra/components' **最近更新** — 本次重构的主要成果: - **统一的 NAPI Binding 加载器**:将平台映射、候选路径探测、CLI 平台包扫描和错误聚合收敛到 `sdk/src/core/native-binding-loader.ts` -- **Logger / Script-Runtime 内联**:TypeScript facade 已迁入 `sdk/src/libraries/*`,公共包 `@truenine/logger` / `@truenine/script-runtime` 仅保留 wrapper 入口 +- **Logger / Script-Runtime 内联**:TypeScript facade 已迁入 `sdk/src/sdk/*`,公共包 `@truenine/memory-sync-sdk` / `@truenine/memory-sync-sdk` 仅保留 wrapper 入口 - **完整的技术文档体系**:新增 4 个文档页面(Logger、MDX-Compiler、Script-Runtime、架构总览),覆盖 API 参考、架构图、使用示例和最佳实践 - **标准化的包配置和构建流程**:三个 library 统一收敛到共享加载器 + 包级验证/适配层的职责分工,构建脚本支持增量缓存 diff --git a/doc/content/sdk/logger/index.mdx b/doc/content/sdk/logger/index.mdx index 93ff7ded..d6dfab61 100644 --- a/doc/content/sdk/logger/index.mdx +++ b/doc/content/sdk/logger/index.mdx @@ -11,12 +11,12 @@ import { Callout, Cards, Tabs } from 'nextra/components' **包信息** -- **npm 包名**: `@truenine/logger` -- **Rust crate**: `tnmsc-logger` -- **Rust 源码位置**: `libraries/logger/` -- **TypeScript 事实来源**: `sdk/src/libraries/logger.ts` -- **发布壳层**: `libraries/logger/src/index.ts` -- **核心文件**: `libraries/logger/src/lib.rs` (Rust 核心) · `sdk/src/libraries/logger.ts` (TypeScript facade) +- **npm 包名**: `@truenine/memory-sync-sdk` +- **Rust crate**: `tnmsc` +- **Rust 源码位置**: `sdk/src/native_logger.rs` +- **TypeScript 事实来源**: `sdk/src/sdk/logger.ts` +- **发布壳层**: `sdk/src/sdk/logger.ts` +- **核心文件**: `sdk/src/native_logger.rs` (Rust 核心) · `sdk/src/sdk/logger.ts` (TypeScript facade) Logger 是一个 **Rust 驱动的 AI 友好型 Markdown 日志库**,专为 `tnmsc` 工具链设计。它将日志输出格式化为结构化 Markdown(`###` 标题 + 列表),使终端输出对人类可读的同时也能被 AI 工具高效解析。 @@ -92,7 +92,7 @@ graph TB ```ts -import { createLogger } from '@truenine/logger' +import { createLogger } from '@truenine/memory-sync-sdk' const logger = createLogger('my-namespace') const debugLogger = createLogger('my-namespace', 'debug') @@ -322,7 +322,7 @@ enum OutputCommand { ### 共享 Native Binding 加载 -Logger 的 TypeScript facade 已迁到 `sdk/src/libraries/logger.ts`,`libraries/logger/src/index.ts` 现在只是一个薄 re-export wrapper。SDK 内联实现不再复制平台检测、本地候选路径和 CLI 平台包扫描逻辑,只保留三件 Logger 特有的事情: +Logger 的 TypeScript facade 已迁到 `sdk/src/sdk/logger.ts`,`sdk/src/sdk/logger.ts` 现在只是一个薄 re-export wrapper。SDK 内联实现不再复制平台检测、本地候选路径和 CLI 平台包扫描逻辑,只保留三件 Logger 特有的事情: - `isNapiLoggerModule()`:校验 native export 的形状 - `createNativeBindingLoader(...)`:声明 `packageName`、`binaryName` 和 `cliExportName` @@ -348,7 +348,7 @@ Logger 的 TypeScript facade 已迁到 `sdk/src/libraries/logger.ts`,`librarie 演示 info、debug、trace 三种普通日志的使用方式: ```ts -import { createLogger } from '@truenine/logger' +import { createLogger } from '@truenine/memory-sync-sdk' const logger = createLogger('example-app') @@ -377,7 +377,7 @@ logger.trace('进入函数', { fn: 'processRequest', args: ['req', 'res'] }) 演示 error、warn、fatal 三种结构化诊断日志: ```ts -import { createLogger } from '@truenine/logger' +import { createLogger } from '@truenine/memory-sync-sdk' const logger = createLogger('config-loader') @@ -453,7 +453,7 @@ import { clearBufferedDiagnostics, drainBufferedDiagnostics, flushOutput -} from '@truenine/logger' +} from '@truenine/memory-sync-sdk' // 1. 设置全局级别为 warn — 只显示 error/warn/fatal setGlobalLogLevel('warn') diff --git a/doc/content/sdk/md-compiler/index.mdx b/doc/content/sdk/md-compiler/index.mdx index 387f5474..cfe915e9 100644 --- a/doc/content/sdk/md-compiler/index.mdx +++ b/doc/content/sdk/md-compiler/index.mdx @@ -10,8 +10,8 @@ import { Callout, Cards, Steps, Tabs } from 'nextra/components' # MDX-Compiler 编译器 - **包标识**: `@truenine/md-compiler` (npm) / `tnmsc-md-compiler` (Rust crate) - **源码位置**: `libraries/md-compiler/` + **包标识**: `@truenine/memory-sync-sdk` (npm) / `tnmsc` (Rust crate) + **源码位置**: `sdk/src/md-compiler/` **导出入口**: `src/index.ts` @@ -33,7 +33,7 @@ MDX-Compiler 是 memory-sync monorepo 中的 **Rust-first MDX/Markdown 编译与 MDX-Compiler 当前采用 **Native-first 入口 + TypeScript 参考实现** 的结构: -1. **Native Binding 层(Rust/NAPI)**:核心编译逻辑由 Rust crate `tnmsc-md-compiler` 实现,通过 NAPI-RS 暴露给 Node.js。公开包入口默认走这条路径。 +1. **Native Binding 层(Rust/NAPI)**:核心编译逻辑由 Rust crate `tnmsc` 实现,通过 NAPI-RS 暴露给 Node.js。公开包入口默认走这条路径。 2. **TypeScript 参考实现(`src/compiler/`)**:仓库内保留完整的 TypeScript 编译流水线,用于源级测试、实现对照和调试,但公共包入口不会自动切换到它。 运行时入口通过 `native-binding.ts` 中的 `getNapiMdCompilerBinding()` 接入 `sdk/src/core/native-binding-loader.ts`: @@ -371,7 +371,7 @@ flowchart LR ### 内部依赖 - MDX-Compiler 通过 workspace 依赖使用 `tnmsc-logger` 库进行编译过程中的日志输出。 + MDX-Compiler 通过 workspace 依赖使用 `tnmsc` 库进行编译过程中的日志输出。 ### 外部依赖 (devDependencies) @@ -393,7 +393,7 @@ flowchart LR | Crate | 用途 | | --- | --- | -| `tnmsc-logger` | Workspace 日志库 | +| `tnmsc` | Workspace 日志库 | | `serde` / `serde_json` | JSON 序列化(NAPI 参数传递) | | `serde_yml` | YAML 解析(frontmatter 处理) | | `markdown` | markdown-rs 解析器(Rust 端 MDX 解析) | @@ -421,7 +421,7 @@ interface MdxGlobalScope { 库提供了三组工具名称预设,适配不同的 AI 工具环境: ```typescript -import { ToolPresets } from '@truenine/md-compiler/globals' +import { ToolPresets } from '@truenine/memory-sync-sdk/globals' // 默认预设 (snake_case) ToolPresets.default @@ -443,7 +443,7 @@ ToolPresets.kiro 最简单的用法——传入 MDX 字符串,获取编译后的 Markdown: ```typescript -import { mdxToMd } from '@truenine/md-compiler' +import { mdxToMd } from '@truenine/memory-sync-sdk' const mdxSource = ` # Hello MDX @@ -477,7 +477,7 @@ console.log(markdown) 使用自定义作用域、全局作用域和文件路径进行编译: ```typescript -import { mdxToMd, MdxToMdOptions } from '@truenine/md-compiler' +import { mdxToMd, MdxToMdOptions } from '@truenine/memory-sync-sdk' const mdxSource = ` # Profile Page @@ -526,7 +526,7 @@ console.log(result.metadata) 构建用于 AI Prompt 的结构化 TOML 文档: ```typescript -import { mdxToMd, buildPromptTomlArtifact } from '@truenine/md-compiler' +import { mdxToMd, buildPromptTomlArtifact } from '@truenine/memory-sync-sdk' const promptContent = ` # System Prompt @@ -587,7 +587,7 @@ console.log(tomlOutput) 从 MDX 的 `export` 语句中提取结构化元数据: ```typescript -import { mdxToMd } from '@truenine/md-compiler' +import { mdxToMd } from '@truenine/memory-sync-sdk' const mdxWithExports = ` --- @@ -649,7 +649,7 @@ import { type MdxJsxFlowElement, type ProcessingContext, type RootContent -} from '@truenine/md-compiler' +} from '@truenine/memory-sync-sdk' // 定义一个 组件 const alertHandler: ComponentHandler = async ( @@ -852,7 +852,7 @@ import { ExportParseError, MetadataValidationError, formatCompilerDiagnostic -} from '@truenine/md-compiler' +} from '@truenine/memory-sync-sdk' try { const result = await mdxToMd(mdxSource, { filePath: '/path/to/file.mdx', extractMetadata: true }) @@ -878,7 +878,7 @@ try { ### 类型导出速查 -以下是 `@truenine/md-compiler` 的完整公共类型导出清单: +以下是 `@truenine/memory-sync-sdk` 的完整公共类型导出清单: ```typescript // ===== 核心类型 (来自 types.ts) ===== diff --git a/doc/content/sdk/script-runtime/index.mdx b/doc/content/sdk/script-runtime/index.mdx index 46148cd6..caf4f4a8 100644 --- a/doc/content/sdk/script-runtime/index.mdx +++ b/doc/content/sdk/script-runtime/index.mdx @@ -10,7 +10,7 @@ import { Callout, Cards, Steps, Tabs } from 'nextra/components' # Script-Runtime -**包名**: `@truenine/script-runtime`  |  **Rust Crate**: `tnmsc-script-runtime`  |  **Rust / 包位置**: `libraries/script-runtime/`  |  **TypeScript 事实来源**: `sdk/src/libraries/script-runtime/` +**包名**: `@truenine/memory-sync-sdk`  |  **Rust Crate**: `tnmsc`  |  **Rust / 包位置**: `sdk/src/sdk/script-runtime/`  |  **TypeScript 事实来源**: `sdk/src/sdk/src/sdk/script-runtime/` Script-Runtime 是一个 **Rust 支持的 TypeScript 代理模块加载器和路径验证运行时**,为 `tnmsc` 核心系统提供安全的动态模块代理与公共路径解析能力。它通过 NAPI 将 Rust 原生的高性能路径验证逻辑暴露给 Node.js 层,同时利用 Jiti 运行时实现灵活的代理模块加载与执行。 @@ -89,7 +89,7 @@ import { resolvePublicPath, resolvePublicPathUnchecked, getProxyModuleConfig -} from '@truenine/script-runtime' +} from '@truenine/memory-sync-sdk' ``` --- @@ -354,7 +354,7 @@ Script-Runtime 支持两种代理定义方式: ```typescript // proxy.ts - 函数式定义 -import {defineProxy} from '@truenine/script-runtime' +import {defineProxy} from '@truenine/memory-sync-sdk' import {join} from 'node:path' export default defineProxy((logicalPath: string, ctx: ProxyContext) => { @@ -365,7 +365,7 @@ export default defineProxy((logicalPath: string, ctx: ProxyContext) => { ```typescript // proxy.ts - 对象式定义 -import {defineProxy, type ProxyDefinition} from '@truenine/script-runtime' +import {defineProxy, type ProxyDefinition} from '@truenine/memory-sync-sdk' import {join} from 'node:path' const proxy: ProxyDefinition = { @@ -583,7 +583,7 @@ pub fn resolve_public_path_impl( ### 共享 Native Binding 加载 -Script-Runtime 现在与 Logger、MDX-Compiler 共用 `sdk/src/core/native-binding-loader.ts`。它的 TypeScript 事实来源已经迁到 `sdk/src/libraries/script-runtime/`,而 `libraries/script-runtime/src/index.ts` 只保留 wrapper 角色;真正的实现只保留 Script-Runtime 自己必须关心的部分: +Script-Runtime 现在与 Logger、MDX-Compiler 共用 `sdk/src/core/native-binding-loader.ts`。它的 TypeScript 事实来源已经迁到 `sdk/src/sdk/src/sdk/script-runtime/`,而 `sdk/src/sdk/src/sdk/script-runtime/index.ts` 只保留 wrapper 角色;真正的实现只保留 Script-Runtime 自己必须关心的部分: - `isScriptRuntimeBinding()`:校验 native export - `optionalMethods` 映射:把 `validate_public_path` / `resolve_public_path` 归一成 TypeScript 侧的首选方法名 @@ -644,7 +644,7 @@ LR ```typescript // project/proxy.ts -import {defineProxy, type ProxyRouteHandler} from '@truenine/script-runtime' +import {defineProxy, type ProxyRouteHandler} from '@truenine/memory-sync-sdk' const handler: ProxyRouteHandler = (logicalPath) => { // 简单的前缀映射 @@ -657,7 +657,7 @@ export default defineProxy(handler) ### 示例 2: 加载和使用外部代理 ```typescript -import {loadProxyModule, getProxyModuleConfig} from '@truenine/script-runtime' +import {loadProxyModule, getProxyModuleConfig} from '@truenine/memory-sync-sdk' async function useExternalProxy(proxyPath: string) { // 加载代理模块 @@ -686,7 +686,7 @@ useExternalProxy('./project/proxy.ts') ### 示例 3: 公共路径验证 ```typescript -import {validatePublicPath} from '@truenine/script-runtime' +import {validatePublicPath} from '@truenine/memory-sync-sdk' const options = {aindexPublicDir: '/workspace/.aindex/public'} @@ -719,7 +719,7 @@ try { ### 示例 4: 带上下文的路径解析 ```typescript -import {resolvePublicPath} from '@truenine/script-runtime' +import {resolvePublicPath} from '@truenine/memory-sync-sdk' const ctx = { cwd: '/home/user/project', @@ -757,7 +757,7 @@ import { type ProxyRouteHandler, type ProxyContext, type ProxyModuleConfig -} from '@truenine/script-runtime' +} from '@truenine/memory-sync-sdk' import {join, extname} from 'node:path' /** @@ -813,7 +813,7 @@ export const config: ProxyModuleConfig = { **消费端使用:** ```typescript -import {resolvePublicPath, loadProxyModule, getProxyModuleConfig} from '@truenine/script-runtime' +import {resolvePublicPath, loadProxyModule, getProxyModuleConfig} from '@truenine/memory-sync-sdk' async function demonstrateFullProxy() { const ctx = { @@ -864,7 +864,7 @@ project/ ### 错误处理和超时配置 ```typescript -import {resolvePublicPath, loadProxyModule} from '@truenine/script-runtime' +import {resolvePublicPath, loadProxyModule} from '@truenine/memory-sync-sdk' class ProxyResolutionError extends Error { constructor( @@ -933,13 +933,13 @@ async function safeResolve( ```typescript // ❌ 错误:直接使用 unchecked 结果访问文件系统 import {readFile} from 'node:fs/promises' -import {resolvePublicPathUnchecked} from '@truenine/script-runtime' +import {resolvePublicPathUnchecked} from '@truenine/memory-sync-sdk' const unsafePath = await resolvePublicPathUnchecked(proxyPath, ctx, userInput) const content = await readFile(unsafePath, 'utf8') // 危险!未经验证 // ✅ 正确:始终经过验证 -import {resolvePublicPath} from '@truenine/script-runtime' +import {resolvePublicPath} from '@truenine/memory-sync-sdk' import {readFile} from 'node:fs/promises' const safePath = resolvePublicPath(proxyPath, ctx, userInput) // 含 Rust 验证 @@ -991,7 +991,7 @@ graph TB ProxyTS["proxy.ts
(用户编写)"] end - subgraph ScriptRuntimeAPI["@truenine/script-runtime"] + subgraph ScriptRuntimeAPI["@truenine/memory-sync-sdk"] direction TB PublicAPI["公开 API
defineProxy / loadProxyModule
validatePublicPath / resolvePublicPath"] @@ -1002,7 +1002,7 @@ graph TB end end - subgraph NativeLayer["Rust Native Layer (tnmsc-script-runtime)"] + subgraph NativeLayer["Rust Native Layer (tnmsc)"] direction TB NAPIExport["NAPI Binding
validate_public_path()
resolve_public_path()"] PathValidator["路径验证引擎
normalize_path()
ensure_within_root()"] @@ -1032,11 +1032,11 @@ graph TB ## 相关资源 -- **Rust / 包位置**: `libraries/script-runtime/` -- **TypeScript 事实来源**: `sdk/src/libraries/script-runtime/` -- **主入口**: `sdk/src/libraries/script-runtime/index.ts` -- **类型定义**: `sdk/src/libraries/script-runtime/types.ts` -- **核心运行时**: `sdk/src/libraries/script-runtime/runtime-core.ts` -- **Worker 处理器**: `sdk/src/libraries/script-runtime/resolve-proxy-worker.ts` -- **Rust Native**: `libraries/script-runtime/src/lib.rs` +- **Rust / 包位置**: `sdk/src/sdk/script-runtime/` +- **TypeScript 事实来源**: `sdk/src/sdk/src/sdk/script-runtime/` +- **主入口**: `sdk/src/sdk/src/sdk/script-runtime/index.ts` +- **类型定义**: `sdk/src/sdk/src/sdk/script-runtime/types.ts` +- **核心运行时**: `sdk/src/sdk/src/sdk/script-runtime/runtime-core.ts` +- **Worker 处理器**: `sdk/src/sdk/src/sdk/script-runtime/resolve-proxy-worker.ts` +- **Rust Native**: `sdk/src/native_script_runtime.rs` - **依赖库**: `logger`(类似的 Native Binding 模式参考) diff --git a/doc/content/technical-details/architecture.mdx b/doc/content/technical-details/architecture.mdx index bb85a895..0177a28b 100644 --- a/doc/content/technical-details/architecture.mdx +++ b/doc/content/technical-details/architecture.mdx @@ -22,7 +22,7 @@ status: stable | `cli/` | `tnmsc` 命令入口、公开 npm CLI 包,以及兼容发布外壳 | | `mcp/` | 复用 sdk prompt service 的 MCP stdio server | | `gui/` | Tauri 桌面调用与呈现层 | -| `libraries/` | Rust-first / NAPI-first 基础库 | +| `sdk/` | Rust-first / NAPI-first 基础库 | ## 关键边界 diff --git a/doc/content/technical-details/libraries.mdx b/doc/content/technical-details/libraries.mdx index 7de836b6..aedf347b 100644 --- a/doc/content/technical-details/libraries.mdx +++ b/doc/content/technical-details/libraries.mdx @@ -1,6 +1,6 @@ --- title: 基础库(概述) -description: libraries/ 下三个 Rust-first 基础库的快速导航与重定向指引。详细文档已迁移至 SDK 文档体系。 +description: sdk/ 下三个 Rust-first 基础库的快速导航与重定向指引。详细文档已迁移至 SDK 文档体系。 sidebarTitle: 基础库 status: stable --- @@ -18,11 +18,11 @@ import { Callout, Cards } from 'nextra/components' ## 现状说明 -`libraries/` 目录仍然存在且正常运作,但它不再等同于全部 TypeScript 事实来源。当前边界是: +`sdk/` 目录仍然存在且正常运作,但它不再等同于全部 TypeScript 事实来源。当前边界是: -- `libraries/logger/` 与 `libraries/script-runtime/` 继续保留 Rust crate、NAPI 制品和对外发布 wrapper -- `sdk/src/libraries/logger.ts` 与 `sdk/src/libraries/script-runtime/` 已成为对应 TypeScript facade 的事实来源 -- `libraries/md-compiler/` 仍保留完整的 Rust + TypeScript 实现 +- `sdk/src/native_logger.rs` 与 `sdk/src/sdk/script-runtime/` 继续保留 Rust crate、NAPI 制品和对外发布 wrapper +- `sdk/src/sdk/logger.ts` 与 `sdk/src/sdk/src/sdk/script-runtime/` 已成为对应 TypeScript facade 的事实来源 +- `sdk/src/md-compiler/` 仍保留完整的 Rust + TypeScript 实现 这三个 Rust-first / NAPI-first 基础能力继续作为 memory-sync 工具链的共享基础设施,被 `sdk/` 核心层编排后统一暴露给 `cli/`、`mcp/` 和 `gui/` 消费。 diff --git a/doc/package.json b/doc/package.json index 910fcdc7..f313c0c0 100644 --- a/doc/package.json +++ b/doc/package.json @@ -1,6 +1,6 @@ { "name": "@truenine/memory-sync-docs", - "version": "2026.10412.11551", + "version": "2026.10412.11942", "private": true, "description": "Chinese-first manifesto-led documentation site for @truenine/memory-sync.", "engines": { diff --git a/gui/package.json b/gui/package.json index cd107712..9a0e7cc4 100644 --- a/gui/package.json +++ b/gui/package.json @@ -1,6 +1,6 @@ { "name": "@truenine/memory-sync-gui", - "version": "2026.10412.11551", + "version": "2026.10412.11942", "private": true, "engines": { "node": ">= 22" diff --git a/gui/src-tauri/Cargo.toml b/gui/src-tauri/Cargo.toml index b09bc883..cd6f5ed7 100644 --- a/gui/src-tauri/Cargo.toml +++ b/gui/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "memory-sync-gui" -version = "2026.10412.11551" +version = "2026.10412.11942" description = "Memory Sync desktop GUI application" authors.workspace = true edition.workspace = true diff --git a/gui/src-tauri/tauri.conf.json b/gui/src-tauri/tauri.conf.json index 0bdae673..7598b7a7 100644 --- a/gui/src-tauri/tauri.conf.json +++ b/gui/src-tauri/tauri.conf.json @@ -1,6 +1,6 @@ { "$schema": "https://schema.tauri.app/config/2", - "version": "2026.10412.11551", + "version": "2026.10412.11942", "productName": "Memory Sync", "identifier": "org.truenine.memory-sync", "build": { diff --git a/libraries/logger/Cargo.toml b/libraries/logger/Cargo.toml deleted file mode 100644 index 114ae2e2..00000000 --- a/libraries/logger/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -name = "tnmsc-logger" -description = "AI-friendly Markdown logger with minimal terminal noise for tnmsc" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -authors.workspace = true -repository.workspace = true - -[lib] -crate-type = ["rlib", "cdylib"] - -[features] -default = [] -napi = ["dep:napi", "dep:napi-derive"] - -[dependencies] -serde = { workspace = true } -serde_json = { workspace = true } -napi = { workspace = true, optional = true } -napi-derive = { workspace = true, optional = true } - -[build-dependencies] -napi-build = { workspace = true } diff --git a/libraries/logger/build.rs b/libraries/logger/build.rs deleted file mode 100644 index ef0415d4..00000000 --- a/libraries/logger/build.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - #[cfg(feature = "napi")] - napi_build::setup(); -} diff --git a/libraries/logger/eslint.config.ts b/libraries/logger/eslint.config.ts deleted file mode 100644 index d1de0a15..00000000 --- a/libraries/logger/eslint.config.ts +++ /dev/null @@ -1,26 +0,0 @@ -import {dirname, resolve} from 'node:path' -import {fileURLToPath} from 'node:url' - -import eslint10 from '@truenine/eslint10-config' - -const configDir = dirname(fileURLToPath(import.meta.url)) - -const config = eslint10({ - type: 'lib', - typescript: { - strictTypescriptEslint: true, - tsconfigPath: resolve(configDir, 'tsconfig.json'), - parserOptions: { - allowDefaultProject: true - } - }, - ignores: [ - '.turbo/**', - '*.md', - '**/*.md', - '**/*.toml', - '**/*.d.ts' - ] -}) - -export default config as unknown diff --git a/libraries/logger/index.d.ts b/libraries/logger/index.d.ts deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/logger/package.json b/libraries/logger/package.json deleted file mode 100644 index ee55fbc8..00000000 --- a/libraries/logger/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "@truenine/logger", - "type": "module", - "version": "2026.10412.11551", - "private": true, - "description": "Rust-powered AI-friendly Markdown logger for Node.js via N-API", - "license": "AGPL-3.0-only", - "exports": { - "./package.json": "./package.json", - ".": { - "types": "./dist/index.d.mts", - "import": "./dist/index.mjs" - } - }, - "module": "dist/index.mjs", - "types": "dist/index.d.mts", - "files": [ - "dist" - ], - "napi": { - "binaryName": "napi-logger", - "targets": [ - "x86_64-pc-windows-msvc", - "x86_64-unknown-linux-gnu", - "aarch64-unknown-linux-gnu", - "aarch64-apple-darwin", - "x86_64-apple-darwin" - ] - }, - "scripts": { - "build": "run-s build:ts build:native", - "build:all": "run-s build:ts build:native", - "build:native": "napi build --platform --release --output-dir dist -- --features napi", - "build:native:debug": "napi build --platform --output-dir dist -- --features napi", - "build:ts": "tsdown", - "check": "run-p check:type lint", - "lint": "run-p lint:ts lint:rust", - "lint:ts": "eslint --cache --cache-location .eslintcache .", - "lint:rust": "cargo fmt --check --manifest-path Cargo.toml", - "lint:fix": "run-s lint:fix:ts lint:fix:rust", - "lint:fix:ts": "eslint --fix --cache --cache-location .eslintcache .", - "lint:fix:rust": "cargo fmt --manifest-path Cargo.toml", - "prepublishOnly": "run-s build", - "test": "run-s build:native:debug test:rust test:ts", - "test:rust": "tsx ../../scripts/cargo-test.ts", - "test:ts": "vitest run --passWithNoTests", - "check:type": "tsc --noEmit -p tsconfig.lib.json" - }, - "devDependencies": { - "@napi-rs/cli": "catalog:", - "@truenine/eslint10-config": "catalog:", - "eslint": "catalog:", - "npm-run-all2": "catalog:", - "tsdown": "catalog:", - "typescript": "catalog:", - "vitest": "catalog:" - } -} diff --git a/libraries/logger/src/index.ts b/libraries/logger/src/index.ts deleted file mode 100644 index ed0199a1..00000000 --- a/libraries/logger/src/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '../../../sdk/src/libraries/logger' diff --git a/libraries/logger/tsconfig.json b/libraries/logger/tsconfig.json deleted file mode 100644 index f4a0bd0c..00000000 --- a/libraries/logger/tsconfig.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "noUncheckedSideEffectImports": true, - "incremental": true, - "composite": false, - "target": "ESNext", - "lib": [ - "ESNext" - ], - "moduleDetection": "force", - "useDefineForClassFields": true, - "module": "ESNext", - "moduleResolution": "Bundler", - "paths": { - "@/*": [ - "./src/*" - ] - }, - "resolveJsonModule": true, - "types": [ - "node" - ], - "allowImportingTsExtensions": true, - "strict": true, - "strictBindCallApply": true, - "strictFunctionTypes": true, - "strictNullChecks": true, - "strictPropertyInitialization": true, - "allowUnreachableCode": false, - "allowUnusedLabels": false, - "alwaysStrict": true, - "exactOptionalPropertyTypes": true, - "noFallthroughCasesInSwitch": true, - "noImplicitAny": true, - "noImplicitOverride": true, - "noImplicitReturns": true, - "noImplicitThis": true, - "noPropertyAccessFromIndexSignature": true, - "noUncheckedIndexedAccess": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "useUnknownInCatchVariables": true, - "declaration": true, - "declarationMap": true, - "importHelpers": true, - "newLine": "lf", - "noEmit": true, - "noEmitHelpers": false, - "removeComments": false, - "sourceMap": true, - "stripInternal": true, - "allowSyntheticDefaultImports": true, - "esModuleInterop": true, - "forceConsistentCasingInFileNames": true, - "isolatedModules": true, - "verbatimModuleSyntax": true, - "skipLibCheck": true - }, - "include": [ - "src/**/*", - "env.d.ts", - "eslint.config.ts", - "tsdown.config.ts" - ], - "exclude": [ - "../node_modules", - "dist" - ] -} diff --git a/libraries/logger/tsconfig.lib.json b/libraries/logger/tsconfig.lib.json deleted file mode 100644 index 7221e516..00000000 --- a/libraries/logger/tsconfig.lib.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/tsconfig", - "extends": "./tsconfig.json", - "compilerOptions": { - "composite": true, - "rootDir": "../..", - "noEmit": false, - "outDir": "./dist", - "skipLibCheck": true - }, - "include": [ - "src/**/*", - "env.d.ts", - "../../sdk/src/libraries/logger.ts", - "../../sdk/src/core/native-binding-loader.ts" - ], - "exclude": [ - "../node_modules", - "dist", - "**/*.spec.ts", - "**/*.test.ts" - ] -} diff --git a/libraries/logger/tsdown.config.ts b/libraries/logger/tsdown.config.ts deleted file mode 100644 index 953f9582..00000000 --- a/libraries/logger/tsdown.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -import {resolve} from 'node:path' -import {defineConfig} from 'tsdown' - -export default defineConfig([ - { - entry: ['./src/index.ts', '!**/*.{spec,test}.*'], - platform: 'node', - sourcemap: false, - unbundle: false, - deps: { - onlyBundle: false - }, - alias: { - '@': resolve('src') - }, - format: ['esm'], - minify: false, - dts: {sourcemap: false} - } -]) diff --git a/libraries/md-compiler/Cargo.toml b/libraries/md-compiler/Cargo.toml deleted file mode 100644 index 863eb484..00000000 --- a/libraries/md-compiler/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "tnmsc-md-compiler" -description = "MDX to Markdown compiler with expression evaluation and JSX component processing" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -authors.workspace = true -repository.workspace = true - -[lib] -crate-type = ["rlib", "cdylib"] - -[features] -default = [] -napi = ["dep:napi", "dep:napi-derive", "dep:regex-lite"] - -[dependencies] -tnmsc-logger = { workspace = true } -serde = { workspace = true } -serde_json = { workspace = true } -serde_yml = { workspace = true } -markdown = { workspace = true } -json5 = "0.4.1" -napi = { workspace = true, optional = true } -napi-derive = { workspace = true, optional = true } -regex-lite = { version = "0.1.9", optional = true } - -[build-dependencies] -napi-build = { workspace = true } diff --git a/libraries/md-compiler/build.rs b/libraries/md-compiler/build.rs deleted file mode 100644 index ef0415d4..00000000 --- a/libraries/md-compiler/build.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - #[cfg(feature = "napi")] - napi_build::setup(); -} diff --git a/libraries/md-compiler/eslint.config.ts b/libraries/md-compiler/eslint.config.ts deleted file mode 100644 index f2c61717..00000000 --- a/libraries/md-compiler/eslint.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -import {dirname, resolve} from 'node:path' -import {fileURLToPath} from 'node:url' - -import eslint10 from '@truenine/eslint10-config' - -const configDir = dirname(fileURLToPath(import.meta.url)) - -const config = eslint10({ - type: 'lib', - typescript: { - strictTypescriptEslint: true, - tsconfigPath: resolve(configDir, 'tsconfig.json'), - parserOptions: { - allowDefaultProject: true - } - }, - ignores: [ - '.turbo/**', - 'aindex/**', - '*.md', - '**/*.md', - '.kiro/**', - '.claude/**', - '.factory/**', - 'src/AGENTS.md', - 'public/**', - '.skills/**', - '**/.skills/**', - '.agent/**', - '**/*.toml', - '**/*.d.ts' - ] -}) - -export default config as unknown diff --git a/libraries/md-compiler/index.d.ts b/libraries/md-compiler/index.d.ts deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/md-compiler/package.json b/libraries/md-compiler/package.json deleted file mode 100644 index 6b6ddb08..00000000 --- a/libraries/md-compiler/package.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "name": "@truenine/md-compiler", - "type": "module", - "version": "2026.10412.11551", - "private": true, - "description": "Rust-powered MDX→Markdown compiler for Node.js with shared N-API loading", - "license": "AGPL-3.0-only", - "exports": { - "./package.json": "./package.json", - ".": { - "types": "./dist/index.d.mts", - "import": "./dist/index.mjs" - }, - "./globals": { - "types": "./dist/globals/index.d.mts", - "import": "./dist/globals/index.mjs" - }, - "./errors": { - "types": "./dist/errors/index.d.mts", - "import": "./dist/errors/index.mjs" - }, - "./markdown": { - "types": "./dist/markdown/index.d.mts", - "import": "./dist/markdown/index.mjs" - } - }, - "module": "dist/index.mjs", - "types": "dist/index.d.mts", - "files": [ - "dist" - ], - "napi": { - "binaryName": "napi-md-compiler", - "targets": [ - "x86_64-pc-windows-msvc", - "x86_64-unknown-linux-gnu", - "aarch64-unknown-linux-gnu", - "aarch64-apple-darwin", - "x86_64-apple-darwin" - ] - }, - "scripts": { - "build": "run-s build:ts build:native", - "build:all": "run-s build:ts build:native", - "build:native": "napi build --platform --release --output-dir dist -- --features napi", - "build:native:debug": "napi build --platform --output-dir dist -- --features napi", - "build:ts": "tsdown", - "check": "run-p check:type lint", - "lint": "run-p lint:ts lint:rust", - "lint:ts": "eslint --cache --cache-location .eslintcache .", - "lint:rust": "cargo fmt --check --manifest-path Cargo.toml", - "lint:fix": "run-s lint:fix:ts lint:fix:rust", - "lint:fix:ts": "eslint --fix --cache --cache-location .eslintcache .", - "lint:fix:rust": "cargo fmt --manifest-path Cargo.toml", - "prepublishOnly": "run-s build", - "test": "run-s build:native:debug test:rust test:ts", - "test:rust": "tsx ../../scripts/cargo-test.ts", - "test:ts": "vitest run --passWithNoTests", - "check:type": "tsc --noEmit -p tsconfig.lib.json" - }, - "devDependencies": { - "@napi-rs/cli": "catalog:", - "@truenine/eslint10-config": "catalog:", - "@types/estree": "catalog:", - "@types/estree-jsx": "catalog:", - "@types/mdast": "catalog:", - "eslint": "catalog:", - "mdast-util-mdx": "catalog:", - "npm-run-all2": "catalog:", - "remark-frontmatter": "catalog:", - "remark-gfm": "catalog:", - "remark-mdx": "catalog:", - "remark-parse": "catalog:", - "remark-stringify": "catalog:", - "tsdown": "catalog:", - "typescript": "catalog:", - "unified": "catalog:", - "vitest": "catalog:", - "yaml": "catalog:" - } -} diff --git a/libraries/md-compiler/tsconfig.json b/libraries/md-compiler/tsconfig.json deleted file mode 100644 index 8ea6064c..00000000 --- a/libraries/md-compiler/tsconfig.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "noUncheckedSideEffectImports": true, - "incremental": true, - "composite": false, // Projects - "target": "ESNext", // Language and Environment - "jsx": "react", - "lib": [ - "ESNext" - ], - "moduleDetection": "force", - "useDefineForClassFields": true, - "module": "ESNext", // Module Resolution - "moduleResolution": "Bundler", - "paths": { - "@/*": [ - "./src/*" - ] - }, - "resolveJsonModule": true, - "types": [ - "node" - ], - "allowImportingTsExtensions": true, - "strict": true, // Type Checking - Maximum Strictness - "strictBindCallApply": true, - "strictFunctionTypes": true, - "strictNullChecks": true, - "strictPropertyInitialization": true, - "allowUnreachableCode": false, - "allowUnusedLabels": false, - "alwaysStrict": true, - "exactOptionalPropertyTypes": true, - "noFallthroughCasesInSwitch": true, - "noImplicitAny": true, - "noImplicitOverride": true, - "noImplicitReturns": true, - "noImplicitThis": true, - "noPropertyAccessFromIndexSignature": true, - "noUncheckedIndexedAccess": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "useUnknownInCatchVariables": true, - "declaration": true, // Emit - "declarationMap": true, - "importHelpers": true, - "newLine": "lf", - "noEmit": true, - "noEmitHelpers": false, - "removeComments": false, - "sourceMap": true, - "stripInternal": true, - "allowSyntheticDefaultImports": true, - "esModuleInterop": true, // Interop Constraints - "forceConsistentCasingInFileNames": true, - "isolatedModules": true, - "verbatimModuleSyntax": true, - "skipLibCheck": true - }, - "include": [ - "src/**/*", - "env.d.ts", - "eslint.config.ts", - "tsdown.config.ts", - "vite.config.ts", - "vitest.config.ts" - ], - "exclude": [ - "../node_modules", - "dist" - ] -} diff --git a/libraries/md-compiler/tsconfig.lib.json b/libraries/md-compiler/tsconfig.lib.json deleted file mode 100644 index 7c0c9719..00000000 --- a/libraries/md-compiler/tsconfig.lib.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/tsconfig", - "extends": "./tsconfig.json", - "compilerOptions": { - "composite": true, - "rootDir": "../..", - "noEmit": false, - "outDir": "./dist", - "skipLibCheck": true - }, - "include": [ - "src/**/*", - "env.d.ts", - "../../sdk/src/core/native-binding-loader.ts" - ], - "exclude": [ - "../node_modules", - "dist", - "**/*.spec.ts", - "**/*.test.ts" - ] -} diff --git a/libraries/md-compiler/tsdown.config.ts b/libraries/md-compiler/tsdown.config.ts deleted file mode 100644 index f9712cc7..00000000 --- a/libraries/md-compiler/tsdown.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -import {resolve} from 'node:path' -import {defineConfig} from 'tsdown' - -export default defineConfig([ - { - entry: ['./src/index.ts', './src/globals/index.ts', './src/errors/index.ts', './src/markdown/index.ts', '!**/*.{spec,test}.*'], - platform: 'node', - sourcemap: false, - unbundle: false, - deps: { - onlyBundle: false - }, - alias: { - '@': resolve('src') - }, - format: ['esm'], - minify: false, - dts: {sourcemap: false} - } -]) diff --git a/libraries/md-compiler/vite.config.ts b/libraries/md-compiler/vite.config.ts deleted file mode 100644 index 2dcc5646..00000000 --- a/libraries/md-compiler/vite.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import {fileURLToPath, URL} from 'node:url' -import {defineConfig} from 'vite' - -export default defineConfig({ - resolve: { - alias: { - '@': fileURLToPath(new URL('./src', import.meta.url)) - } - } -}) diff --git a/libraries/md-compiler/vitest.config.ts b/libraries/md-compiler/vitest.config.ts deleted file mode 100644 index d63a5806..00000000 --- a/libraries/md-compiler/vitest.config.ts +++ /dev/null @@ -1,22 +0,0 @@ -import {fileURLToPath} from 'node:url' -import {configDefaults, defineConfig, mergeConfig} from 'vitest/config' -import viteConfig from './vite.config' - -export default mergeConfig( - viteConfig, - defineConfig({ - test: { - environment: 'node', - exclude: [...configDefaults.exclude], - include: [ - 'src/mdx-to-md.test.ts', - 'src/toml.test.ts', - 'src/markdown/**/*.test.ts' - ], - root: fileURLToPath(new URL('./', import.meta.url)), - testTimeout: 30000, - onConsoleLog: () => false, - passWithNoTests: true - } - }) -) diff --git a/libraries/script-runtime/Cargo.toml b/libraries/script-runtime/Cargo.toml deleted file mode 100644 index 671ee7f9..00000000 --- a/libraries/script-runtime/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "tnmsc-script-runtime" -description = "Rust-backed TypeScript proxy runtime validation for tnmsc" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -authors.workspace = true -repository.workspace = true - -[lib] -crate-type = ["rlib", "cdylib"] - -[features] -default = [] -napi = ["dep:napi", "dep:napi-derive"] - -[dependencies] -serde = { workspace = true } -serde_json = { workspace = true } -napi = { workspace = true, optional = true } -napi-derive = { workspace = true, optional = true } -tempfile = "3.27.0" -wait-timeout = "0.2.1" - -[build-dependencies] -napi-build = { workspace = true } diff --git a/libraries/script-runtime/build.rs b/libraries/script-runtime/build.rs deleted file mode 100644 index ef0415d4..00000000 --- a/libraries/script-runtime/build.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - #[cfg(feature = "napi")] - napi_build::setup(); -} diff --git a/libraries/script-runtime/eslint.config.ts b/libraries/script-runtime/eslint.config.ts deleted file mode 100644 index d1de0a15..00000000 --- a/libraries/script-runtime/eslint.config.ts +++ /dev/null @@ -1,26 +0,0 @@ -import {dirname, resolve} from 'node:path' -import {fileURLToPath} from 'node:url' - -import eslint10 from '@truenine/eslint10-config' - -const configDir = dirname(fileURLToPath(import.meta.url)) - -const config = eslint10({ - type: 'lib', - typescript: { - strictTypescriptEslint: true, - tsconfigPath: resolve(configDir, 'tsconfig.json'), - parserOptions: { - allowDefaultProject: true - } - }, - ignores: [ - '.turbo/**', - '*.md', - '**/*.md', - '**/*.toml', - '**/*.d.ts' - ] -}) - -export default config as unknown diff --git a/libraries/script-runtime/package.json b/libraries/script-runtime/package.json deleted file mode 100644 index 1fdedcf0..00000000 --- a/libraries/script-runtime/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "name": "@truenine/script-runtime", - "type": "module", - "version": "2026.10412.11551", - "private": true, - "description": "Rust-backed TypeScript proxy runtime for tnmsc", - "license": "AGPL-3.0-only", - "exports": { - "./package.json": "./package.json", - ".": { - "types": "./dist/index.d.mts", - "import": "./dist/index.mjs" - } - }, - "module": "dist/index.mjs", - "types": "dist/index.d.mts", - "files": [ - "dist" - ], - "napi": { - "binaryName": "napi-script-runtime", - "targets": [ - "x86_64-pc-windows-msvc", - "x86_64-unknown-linux-gnu", - "aarch64-unknown-linux-gnu", - "aarch64-apple-darwin", - "x86_64-apple-darwin" - ] - }, - "scripts": { - "build": "run-s build:ts build:native", - "build:all": "run-s build:ts build:native", - "build:native": "napi build --platform --release --output-dir dist -- --features napi", - "build:native:debug": "napi build --platform --output-dir dist -- --features napi", - "build:ts": "tsdown", - "check": "run-p check:type lint", - "lint": "run-p lint:ts lint:rust", - "lint:ts": "eslint --cache --cache-location .eslintcache .", - "lint:rust": "cargo fmt --check --manifest-path Cargo.toml", - "lint:fix": "run-s lint:fix:ts lint:fix:rust", - "lint:fix:ts": "eslint --fix --cache --cache-location .eslintcache .", - "lint:fix:rust": "cargo fmt --manifest-path Cargo.toml", - "prepublishOnly": "run-s build", - "test": "run-s build:native:debug test:rust test:ts", - "test:rust": "tsx ../../scripts/cargo-test.ts", - "test:ts": "vitest run --passWithNoTests", - "check:type": "tsc --noEmit -p tsconfig.lib.json" - }, - "devDependencies": { - "@napi-rs/cli": "catalog:", - "@truenine/eslint10-config": "catalog:", - "@types/node": "catalog:", - "eslint": "catalog:", - "jiti": "catalog:", - "npm-run-all2": "catalog:", - "tsdown": "catalog:", - "typescript": "catalog:", - "vitest": "catalog:" - } -} diff --git a/libraries/script-runtime/src/index.test.ts b/libraries/script-runtime/src/index.test.ts deleted file mode 100644 index b1fb7a39..00000000 --- a/libraries/script-runtime/src/index.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import type {ProxyContext} from './types' - -import * as fs from 'node:fs' -import * as os from 'node:os' -import * as path from 'node:path' -import process from 'node:process' -import {afterEach, describe, expect, it} from 'vitest' -import {defineProxy} from './index' -import {loadProxyModule, resolvePublicPathModule} from './runtime-core' - -const tempDirs: string[] = [] - -function createTempDir(): string { - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tnmsc-script-runtime-')) - tempDirs.push(tempDir) - return tempDir -} - -function createContext(tempDir: string, command: ProxyContext['command'] = 'install'): ProxyContext { - const workspaceDir = path.join(tempDir, 'workspace') - const aindexDir = path.join(workspaceDir, 'aindex') - fs.mkdirSync(path.join(aindexDir, 'public'), {recursive: true}) - - return { - cwd: workspaceDir, - workspaceDir, - aindexDir, - command, - platform: process.platform - } -} - -function writeProxyFile(tempDir: string, source: string): string { - const filePath = path.join(tempDir, 'workspace', 'aindex', 'public', 'proxy.ts') - fs.mkdirSync(path.dirname(filePath), {recursive: true}) - fs.writeFileSync(filePath, source, 'utf8') - return filePath -} - -afterEach(() => { - for (const tempDir of tempDirs.splice(0)) fs.rmSync(tempDir, {recursive: true, force: true}) -}) - -describe('runtime-core', () => { - it('loads object default exports', async () => { - const tempDir = createTempDir() - const ctx = createContext(tempDir) - const filePath = writeProxyFile( - tempDir, - 'export default { resolvePublicPath(logicalPath) { return logicalPath.replace(/^\\.git\\//, "____git/") } }\n' - ) - - const loadedModule = await loadProxyModule(filePath) - const result = await resolvePublicPathModule(filePath, ctx, '.git/info/exclude') - - expect(loadedModule.default).toBeDefined() - expect(result).toBe('____git/info/exclude') - }) - - it('loads async function exports', async () => { - const tempDir = createTempDir() - const ctx = createContext(tempDir, 'dry-run') - const filePath = writeProxyFile( - tempDir, - 'export default async (logicalPath, ctx) => ctx.command === "dry-run" ? "dry/" + logicalPath : logicalPath\n' - ) - - const result = await resolvePublicPathModule(filePath, ctx, '.vscode/settings.json') - - expect(result).toBe('dry/.vscode/settings.json') - }) - - it('skips unmatched commands', async () => { - const tempDir = createTempDir() - const ctx = createContext(tempDir, 'clean') - const filePath = writeProxyFile( - tempDir, - 'export const config = { matcher: { commands: ["install"] } }\nexport default (logicalPath) => "shadow/" + logicalPath\n' - ) - - const result = await resolvePublicPathModule(filePath, ctx, '.editorconfig') - - expect(filePath.endsWith('proxy.ts')).toBe(true) - expect(result).toBe('.editorconfig') - }) - - it('rejects non-string path results', async () => { - const tempDir = createTempDir() - const ctx = createContext(tempDir) - const filePath = writeProxyFile(tempDir, 'export default () => ({ bad: true })\n') - - await expect(resolvePublicPathModule(filePath, ctx, '.gitignore')) - .rejects - .toThrow('proxy.ts must resolve public paths to a string') - }) - - it('exposes defineProxy as identity', () => { - const proxy = defineProxy({ - resolvePublicPath(logicalPath: string) { - return logicalPath - } - }) - - expect(proxy.resolvePublicPath?.('.gitignore', createContext(createTempDir()))).toBe('.gitignore') - }) -}) diff --git a/libraries/script-runtime/src/index.ts b/libraries/script-runtime/src/index.ts deleted file mode 100644 index 3fd60a71..00000000 --- a/libraries/script-runtime/src/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '../../../sdk/src/libraries/script-runtime' diff --git a/libraries/script-runtime/src/resolve-proxy-worker.ts b/libraries/script-runtime/src/resolve-proxy-worker.ts deleted file mode 100644 index 43a60d16..00000000 --- a/libraries/script-runtime/src/resolve-proxy-worker.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../sdk/src/libraries/script-runtime/resolve-proxy-worker' diff --git a/libraries/script-runtime/src/runtime-core.ts b/libraries/script-runtime/src/runtime-core.ts deleted file mode 100644 index 9cc6dd9f..00000000 --- a/libraries/script-runtime/src/runtime-core.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '../../../sdk/src/libraries/script-runtime/runtime-core' diff --git a/libraries/script-runtime/src/types.ts b/libraries/script-runtime/src/types.ts deleted file mode 100644 index c96f42ff..00000000 --- a/libraries/script-runtime/src/types.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '../../../sdk/src/libraries/script-runtime/types' diff --git a/libraries/script-runtime/tsconfig.json b/libraries/script-runtime/tsconfig.json deleted file mode 100644 index f4a0bd0c..00000000 --- a/libraries/script-runtime/tsconfig.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/tsconfig", - "compilerOptions": { - "noUncheckedSideEffectImports": true, - "incremental": true, - "composite": false, - "target": "ESNext", - "lib": [ - "ESNext" - ], - "moduleDetection": "force", - "useDefineForClassFields": true, - "module": "ESNext", - "moduleResolution": "Bundler", - "paths": { - "@/*": [ - "./src/*" - ] - }, - "resolveJsonModule": true, - "types": [ - "node" - ], - "allowImportingTsExtensions": true, - "strict": true, - "strictBindCallApply": true, - "strictFunctionTypes": true, - "strictNullChecks": true, - "strictPropertyInitialization": true, - "allowUnreachableCode": false, - "allowUnusedLabels": false, - "alwaysStrict": true, - "exactOptionalPropertyTypes": true, - "noFallthroughCasesInSwitch": true, - "noImplicitAny": true, - "noImplicitOverride": true, - "noImplicitReturns": true, - "noImplicitThis": true, - "noPropertyAccessFromIndexSignature": true, - "noUncheckedIndexedAccess": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "useUnknownInCatchVariables": true, - "declaration": true, - "declarationMap": true, - "importHelpers": true, - "newLine": "lf", - "noEmit": true, - "noEmitHelpers": false, - "removeComments": false, - "sourceMap": true, - "stripInternal": true, - "allowSyntheticDefaultImports": true, - "esModuleInterop": true, - "forceConsistentCasingInFileNames": true, - "isolatedModules": true, - "verbatimModuleSyntax": true, - "skipLibCheck": true - }, - "include": [ - "src/**/*", - "env.d.ts", - "eslint.config.ts", - "tsdown.config.ts" - ], - "exclude": [ - "../node_modules", - "dist" - ] -} diff --git a/libraries/script-runtime/tsconfig.lib.json b/libraries/script-runtime/tsconfig.lib.json deleted file mode 100644 index 61dead36..00000000 --- a/libraries/script-runtime/tsconfig.lib.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/tsconfig", - "extends": "./tsconfig.json", - "compilerOptions": { - "composite": true, - "rootDir": "../..", - "noEmit": false, - "outDir": "./dist", - "skipLibCheck": true - }, - "include": [ - "src/**/*", - "env.d.ts", - "../../sdk/src/libraries/script-runtime/**/*.ts", - "../../sdk/src/core/native-binding-loader.ts" - ], - "exclude": [ - "../node_modules", - "dist", - "**/*.spec.ts", - "**/*.test.ts" - ] -} diff --git a/libraries/script-runtime/tsdown.config.ts b/libraries/script-runtime/tsdown.config.ts deleted file mode 100644 index f63bf7f7..00000000 --- a/libraries/script-runtime/tsdown.config.ts +++ /dev/null @@ -1,21 +0,0 @@ -import {resolve} from 'node:path' -import {defineConfig} from 'tsdown' - -export default defineConfig([ - { - entry: ['./src/index.ts', './src/resolve-proxy-worker.ts', '!**/*.{spec,test}.*'], - platform: 'node', - sourcemap: false, - unbundle: false, - deps: { - neverBundle: ['jiti'], - onlyBundle: false - }, - alias: { - '@': resolve('src') - }, - format: ['esm'], - minify: false, - dts: {sourcemap: false} - } -]) diff --git a/mcp/package.json b/mcp/package.json index 5297f2a6..9bad9ae3 100644 --- a/mcp/package.json +++ b/mcp/package.json @@ -1,7 +1,7 @@ { "name": "@truenine/memory-sync-mcp", "type": "module", - "version": "2026.10412.11551", + "version": "2026.10412.11942", "description": "MCP stdio server for managing memory-sync prompt sources and translation artifacts", "author": "TrueNine", "license": "AGPL-3.0-only", diff --git a/package.json b/package.json index d976a144..64b80469 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@truenine/memory-sync", - "version": "2026.10412.11551", + "version": "2026.10412.11942", "description": "Cross-AI-tool prompt synchronisation toolkit (CLI + Tauri desktop GUI) — one ruleset, multi-target adaptation. Monorepo powered by pnpm + Turbo.", "license": "AGPL-3.0-only", "keywords": [ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fc58892f..d6fcec6b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -327,9 +327,6 @@ importers: '@truenine/eslint10-config': specifier: 'catalog:' version: 2026.10411.10025(4d9df9c0640d97cc4e32b4ae40243784) - '@truenine/logger': - specifier: workspace:* - version: link:../libraries/logger '@truenine/memory-sync-sdk': specifier: workspace:* version: link:../sdk @@ -373,9 +370,6 @@ importers: '@truenine/memory-sync-cli-win32-x64-msvc': specifier: workspace:* version: link:npm/win32-x64-msvc - '@truenine/script-runtime': - specifier: workspace:* - version: link:../libraries/script-runtime json5: specifier: 'catalog:' version: 2.2.3 @@ -550,117 +544,6 @@ importers: specifier: 'catalog:' version: 4.1.4(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)(yaml@2.8.3)) - libraries/logger: - devDependencies: - '@napi-rs/cli': - specifier: 'catalog:' - version: 3.6.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(@types/node@25.6.0)(node-addon-api@7.1.1) - '@truenine/eslint10-config': - specifier: 'catalog:' - version: 2026.10411.10025(4d9df9c0640d97cc4e32b4ae40243784) - eslint: - specifier: 'catalog:' - version: 10.2.0(jiti@2.6.1) - npm-run-all2: - specifier: 'catalog:' - version: 8.0.4 - tsdown: - specifier: 'catalog:' - version: 0.21.7(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(synckit@0.11.12)(typescript@6.0.2) - typescript: - specifier: 'catalog:' - version: 6.0.2 - vitest: - specifier: 'catalog:' - version: 4.1.4(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)(yaml@2.8.3)) - - libraries/md-compiler: - devDependencies: - '@napi-rs/cli': - specifier: 'catalog:' - version: 3.6.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(@types/node@25.6.0)(node-addon-api@7.1.1) - '@truenine/eslint10-config': - specifier: 'catalog:' - version: 2026.10411.10025(4d9df9c0640d97cc4e32b4ae40243784) - '@types/estree': - specifier: 'catalog:' - version: 1.0.8 - '@types/estree-jsx': - specifier: 'catalog:' - version: 1.0.5 - '@types/mdast': - specifier: 'catalog:' - version: 4.0.4 - eslint: - specifier: 'catalog:' - version: 10.2.0(jiti@2.6.1) - mdast-util-mdx: - specifier: 'catalog:' - version: 3.0.0 - npm-run-all2: - specifier: 'catalog:' - version: 8.0.4 - remark-frontmatter: - specifier: 'catalog:' - version: 5.0.0 - remark-gfm: - specifier: 'catalog:' - version: 4.0.1 - remark-mdx: - specifier: 'catalog:' - version: 3.1.1 - remark-parse: - specifier: 'catalog:' - version: 11.0.0 - remark-stringify: - specifier: 'catalog:' - version: 11.0.0 - tsdown: - specifier: 'catalog:' - version: 0.21.7(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(synckit@0.11.12)(typescript@6.0.2) - typescript: - specifier: 'catalog:' - version: 6.0.2 - unified: - specifier: 'catalog:' - version: 11.0.5 - vitest: - specifier: 'catalog:' - version: 4.1.4(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)(yaml@2.8.3)) - yaml: - specifier: 'catalog:' - version: 2.8.3 - - libraries/script-runtime: - devDependencies: - '@napi-rs/cli': - specifier: 'catalog:' - version: 3.6.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(@types/node@25.6.0)(node-addon-api@7.1.1) - '@truenine/eslint10-config': - specifier: 'catalog:' - version: 2026.10411.10025(4d9df9c0640d97cc4e32b4ae40243784) - '@types/node': - specifier: 'catalog:' - version: 25.6.0 - eslint: - specifier: 'catalog:' - version: 10.2.0(jiti@2.6.1) - jiti: - specifier: 'catalog:' - version: 2.6.1 - npm-run-all2: - specifier: 'catalog:' - version: 8.0.4 - tsdown: - specifier: 'catalog:' - version: 0.21.7(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(synckit@0.11.12)(typescript@6.0.2) - typescript: - specifier: 'catalog:' - version: 6.0.2 - vitest: - specifier: 'catalog:' - version: 4.1.4(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)(yaml@2.8.3)) - mcp: dependencies: '@modelcontextprotocol/sdk': @@ -700,15 +583,6 @@ importers: sdk: dependencies: - '@truenine/logger': - specifier: workspace:* - version: link:../libraries/logger - '@truenine/md-compiler': - specifier: workspace:* - version: link:../libraries/md-compiler - '@truenine/script-runtime': - specifier: workspace:* - version: link:../libraries/script-runtime json5: specifier: 'catalog:' version: 2.2.3 @@ -722,9 +596,18 @@ importers: '@clack/prompts': specifier: 'catalog:' version: 1.2.0 + '@types/estree': + specifier: 'catalog:' + version: 1.0.8 + '@types/estree-jsx': + specifier: 'catalog:' + version: 1.0.5 '@types/fs-extra': specifier: 'catalog:' version: 11.0.4 + '@types/mdast': + specifier: 'catalog:' + version: 4.0.4 '@types/picomatch': specifier: 'catalog:' version: 4.0.3 @@ -743,6 +626,9 @@ importers: lightningcss: specifier: 'catalog:' version: 1.32.0 + mdast-util-mdx: + specifier: 'catalog:' + version: 3.0.0 npm-run-all2: specifier: 'catalog:' version: 8.0.4 @@ -752,9 +638,27 @@ importers: picomatch: specifier: 'catalog:' version: 4.0.4 + remark-frontmatter: + specifier: 'catalog:' + version: 5.0.0 + remark-gfm: + specifier: 'catalog:' + version: 4.0.1 + remark-mdx: + specifier: 'catalog:' + version: 3.1.1 + remark-parse: + specifier: 'catalog:' + version: 11.0.0 + remark-stringify: + specifier: 'catalog:' + version: 11.0.0 tsx: specifier: 'catalog:' version: 4.21.0 + unified: + specifier: 'catalog:' + version: 11.0.5 vitest: specifier: 'catalog:' version: 4.1.4(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)(yaml@2.8.3)) diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 9d6b5b59..b16f1960 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -4,9 +4,6 @@ packages: - cli-integration-test - cli/npm/* - mcp - - libraries/* - - libraries/logger/npm/* - - libraries/md-compiler/npm/* - gui - doc diff --git a/scripts/build-native.ts b/scripts/build-native.ts index 8385dc3b..c9a3669b 100644 --- a/scripts/build-native.ts +++ b/scripts/build-native.ts @@ -8,9 +8,6 @@ import {fileURLToPath} from 'node:url' import {writeError, writeMarkdownBlock, writeWarning} from './markdown-output' const NATIVE_MODULES = [ - {name: 'logger', dir: 'libraries/logger'}, - {name: 'md-compiler', dir: 'libraries/md-compiler'}, - {name: 'script-runtime', dir: 'libraries/script-runtime'}, {name: 'sdk', dir: 'sdk'}, ] as const diff --git a/scripts/copy-napi.ts b/scripts/copy-napi.ts index 3fdbb565..029d170c 100644 --- a/scripts/copy-napi.ts +++ b/scripts/copy-napi.ts @@ -8,9 +8,6 @@ import {writeMarkdownBlock, writeWarning} from './markdown-output' import {resolveTargetDirs, writePlatformPackageShims} from './write-platform-package-shims' const NATIVE_MODULES = [ - {name: 'logger', distDir: 'libraries/logger/dist'}, - {name: 'md-compiler', distDir: 'libraries/md-compiler/dist'}, - {name: 'script-runtime', distDir: 'libraries/script-runtime/dist'}, {name: 'sdk', distDir: 'sdk/dist'}, ] as const @@ -63,7 +60,7 @@ for (const mod of NATIVE_MODULES) { for (const file of nodeFiles) { const src = join(modDist, file) const dst = join(targetDir, file) - cpSync(src, dst) + cpSync(src, dst, {force: true}) writeMarkdownBlock('Copied NAPI artifact', { module: mod.name, file, @@ -81,8 +78,6 @@ if (copied > 0) { } else { writeWarning('No NAPI artifacts were copied', { nextSteps: [ - 'pnpm -F @truenine/logger run build:native', - 'pnpm -F @truenine/md-compiler run build:native', 'pnpm -F @truenine/memory-sync-sdk run build:native', ], }) diff --git a/scripts/write-platform-package-shims.ts b/scripts/write-platform-package-shims.ts index 31d3bd1e..d2808fd9 100644 --- a/scripts/write-platform-package-shims.ts +++ b/scripts/write-platform-package-shims.ts @@ -21,10 +21,10 @@ function loadBinding(prefix) { return file == null ? undefined : require(join(moduleDir, file)) } -export const logger = loadBinding('napi-logger.') -export const mdCompiler = loadBinding('napi-md-compiler.') -export const scriptRuntime = loadBinding('napi-script-runtime.') export const config = loadBinding('napi-memory-sync-cli.') +export const logger = loadBinding('napi-logger.') ?? config +export const mdCompiler = loadBinding('napi-md-compiler.') ?? config +export const scriptRuntime = loadBinding('napi-script-runtime.') ?? config const bindings = {logger, mdCompiler, scriptRuntime, config} diff --git a/sdk/Cargo.toml b/sdk/Cargo.toml index 0f474c9b..1382da3b 100644 --- a/sdk/Cargo.toml +++ b/sdk/Cargo.toml @@ -19,8 +19,6 @@ embedded-runtime = [] napi = ["dep:napi", "dep:napi-derive"] [dependencies] -tnmsc-logger = { workspace = true } -tnmsc-md-compiler = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = "2.0.18" @@ -37,10 +35,12 @@ regex-lite = "0.1" chrono = "0.4" json5 = { workspace = true } base64 = { workspace = true } +markdown = { workspace = true } +tempfile = "3.27.0" +wait-timeout = "0.2.1" [dev-dependencies] proptest = "1.11.0" -tempfile = "3.27.0" [build-dependencies] napi-build = { workspace = true } diff --git a/sdk/package.json b/sdk/package.json index 1c60d01c..b02bab07 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,7 +1,7 @@ { "name": "@truenine/memory-sync-sdk", "type": "module", - "version": "2026.10412.11551", + "version": "2026.10412.11942", "private": true, "description": "TrueNine Memory Synchronization SDK", "author": "TrueNine", @@ -38,16 +38,10 @@ ] }, "scripts": { - "build": "run-s build:deps build:napi bundle finalize:bundle generate:schema", + "build": "run-s build:napi bundle finalize:bundle generate:schema", "build:napi": "run-s build:native build:napi:copy", "build:napi:copy": "tsx ../scripts/copy-napi.ts", "build:native": "napi build --platform --release --output-dir dist -- --features napi", - "build:deps": "run-s build:deps:runtime build:deps:md-compiler", - "build:deps:runtime": "pnpm -F @truenine/logger -F @truenine/script-runtime run build", - "build:deps:md-compiler": "run-s build:deps:md-compiler:ts build:deps:md-compiler:native", - "build:deps:md-compiler:ts": "pnpm -F @truenine/md-compiler run build:ts", - "build:deps:md-compiler:native": "pnpm -F @truenine/md-compiler run build:native", - "build:deps:ts": "pnpm -F @truenine/logger -F @truenine/md-compiler -F @truenine/script-runtime run build:ts", "bundle": "tsx ../scripts/build-quiet.ts", "check": "run-p lint check:type", "finalize:bundle": "tsx scripts/finalize-bundle.ts", @@ -59,7 +53,7 @@ "lint:fix:ts": "eslint --fix --cache --cache-location .eslintcache .", "lint:fix:rust": "cargo fmt --manifest-path Cargo.toml", "prepublishOnly": "run-s build check", - "test": "run-s build:deps test:run", + "test": "run-s build test:run", "test:native-cleanup-smoke": "tsx scripts/cleanup-native-smoke.ts", "test:run": "vitest run", "benchmark:cleanup": "tsx scripts/benchmark-cleanup.ts", @@ -67,9 +61,6 @@ "check:type:run": "tsc --noEmit -p tsconfig.lib.json" }, "dependencies": { - "@truenine/logger": "workspace:*", - "@truenine/md-compiler": "workspace:*", - "@truenine/script-runtime": "workspace:*", "json5": "catalog:", "yaml": "catalog:", "zod": "catalog:" @@ -77,17 +68,28 @@ "devDependencies": { "@clack/prompts": "catalog:", "@types/fs-extra": "catalog:", + "@types/estree": "catalog:", + "@types/estree-jsx": "catalog:", + "@types/mdast": "catalog:", "@types/picomatch": "catalog:", "@vitest/coverage-v8": "catalog:", "fast-glob": "catalog:", "fs-extra": "catalog:", "jiti": "catalog:", "lightningcss": "catalog:", + "mdast-util-mdx": "catalog:", "npm-run-all2": "catalog:", "picocolors": "catalog:", "picomatch": "catalog:", + "remark-frontmatter": "catalog:", + "remark-gfm": "catalog:", + "remark-mdx": "catalog:", + "remark-parse": "catalog:", + "remark-stringify": "catalog:", "tsx": "catalog:", + "unified": "catalog:", "vitest": "catalog:", + "yaml": "catalog:", "zod-to-json-schema": "catalog:" } } diff --git a/sdk/src/Aindex.test.ts b/sdk/src/Aindex.test.ts new file mode 100644 index 00000000..36a50fa9 --- /dev/null +++ b/sdk/src/Aindex.test.ts @@ -0,0 +1,28 @@ +import * as fs from 'node:fs' +import * as os from 'node:os' +import * as path from 'node:path' +import {afterEach, describe, expect, it} from 'vitest' +import {checkVersionControl} from './Aindex' + +describe('checkVersionControl', () => { + const tempDirs: string[] = [] + + afterEach(() => { + for (const tempDir of tempDirs.splice(0)) { + fs.rmSync(tempDir, {recursive: true, force: true}) + } + }) + + it('accepts an aindex directory inside a parent git repository', () => { + const workspaceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tnmsc-aindex-git-parent-')) + tempDirs.push(workspaceDir) + fs.mkdirSync(path.join(workspaceDir, '.git')) + const aindexDir = path.join(workspaceDir, 'aindex') + fs.mkdirSync(aindexDir) + + const result = checkVersionControl(aindexDir) + + expect(result.hasGit).toBe(true) + expect(result.gitPath).toBe(path.join(workspaceDir, '.git')) + }) +}) diff --git a/sdk/src/Aindex.ts b/sdk/src/Aindex.ts index 5a8243b8..5cf8db61 100644 --- a/sdk/src/Aindex.ts +++ b/sdk/src/Aindex.ts @@ -15,6 +15,19 @@ export interface VersionControlCheckResult { readonly gitPath: string } +function findGitPath(startPath: string): string | undefined { + let currentPath = path.resolve(startPath) + + for (;;) { + const gitPath = path.join(currentPath, '.git') + if (fs.existsSync(gitPath)) return gitPath + + const parentPath = path.dirname(currentPath) + if (parentPath === currentPath) return void 0 + currentPath = parentPath + } +} + /** * Check if the aindex has version control (.git directory) * Logs info if .git exists, warns if not @@ -27,24 +40,18 @@ export function checkVersionControl( rootPath: string, logger?: ILogger ): VersionControlCheckResult { - const gitPath = path.join(rootPath, '.git') + const gitPath = findGitPath(rootPath) ?? path.join(rootPath, '.git') const hasGit = fs.existsSync(gitPath) - if (hasGit) logger?.info('version control detected', {path: gitPath}) + if (hasGit) logger?.debug('version control detected', {path: gitPath}) else { logger?.warn(buildUsageDiagnostic({ code: 'AINDEX_VERSION_CONTROL_MISSING', - title: 'Aindex root is not under version control', - rootCause: diagnosticLines(`tnmsc did not find a .git directory under "${rootPath}".`), - exactFix: diagnosticLines( - `Initialize git in "${rootPath}" or place the aindex inside an existing git repository.` - ), - possibleFixes: [ - diagnosticLines('Run `git init` in the aindex root if the directory should be versioned.') - ], + title: 'Aindex is not inside a Git repository', + rootCause: diagnosticLines(`No Git repository was found for "${rootPath}".`), + exactFix: diagnosticLines(`Run \`git init "${rootPath}"\` or move the workspace under an existing Git repository.`), details: { - rootPath, - gitPath + rootPath } })) } diff --git a/sdk/src/adaptors/ClaudeCodeCLIOutputAdaptor.ts b/sdk/src/adaptors/ClaudeCodeCLIOutputAdaptor.ts index 9f192db9..03beecb5 100644 --- a/sdk/src/adaptors/ClaudeCodeCLIOutputAdaptor.ts +++ b/sdk/src/adaptors/ClaudeCodeCLIOutputAdaptor.ts @@ -3,7 +3,7 @@ import type { OutputCleanupDeclarations, RulePrompt } from './adaptor-core' -import {doubleQuoted} from '@truenine/md-compiler/markdown' +import {doubleQuoted} from '@/md-compiler/markdown' import {AbstractOutputAdaptor} from './adaptor-core' const PROJECT_MEMORY_FILE = 'CLAUDE.md' diff --git a/sdk/src/adaptors/adaptor-core/AbstractOutputAdaptor.ts b/sdk/src/adaptors/adaptor-core/AbstractOutputAdaptor.ts index f59cdf5a..85882056 100644 --- a/sdk/src/adaptors/adaptor-core/AbstractOutputAdaptor.ts +++ b/sdk/src/adaptors/adaptor-core/AbstractOutputAdaptor.ts @@ -1,4 +1,4 @@ -import type {BuildPromptTomlArtifactOptions} from '@truenine/md-compiler' +import type {BuildPromptTomlArtifactOptions} from '@/md-compiler' import type {ToolPresetName} from './GlobalScopeCollector' import type {RegistryWriter} from './RegistryWriter' import type { @@ -36,8 +36,8 @@ import {Buffer} from 'node:buffer' import * as path from 'node:path' import process from 'node:process' -import {buildPromptTomlArtifact} from '@truenine/md-compiler' -import {buildMarkdownWithFrontMatter, buildMarkdownWithRawFrontMatter} from '@truenine/md-compiler/markdown' +import {buildPromptTomlArtifact} from '@/md-compiler' +import {buildMarkdownWithFrontMatter, buildMarkdownWithRawFrontMatter} from '@/md-compiler/markdown' import {buildConfigDiagnostic, diagnosticLines} from '@/diagnostics' import {getEffectiveHomeDir} from '@/runtime-environment' import {AbstractAdaptor} from './AbstractAdaptor' diff --git a/sdk/src/adaptors/adaptor-core/GlobalScopeCollector.ts b/sdk/src/adaptors/adaptor-core/GlobalScopeCollector.ts index 08bf9f61..d6573be3 100644 --- a/sdk/src/adaptors/adaptor-core/GlobalScopeCollector.ts +++ b/sdk/src/adaptors/adaptor-core/GlobalScopeCollector.ts @@ -1,9 +1,9 @@ -import type {EvaluationScope} from '@truenine/md-compiler' -import type {CodeStylePreferences, EnvironmentContext, MdComponent, MdxGlobalScope, OsInfo, ToolReferences, UserProfile} from '@truenine/md-compiler/globals' // Collects and manages global scope variables for MDX expression evaluation. +import type {EvaluationScope} from '@/md-compiler' +import type {CodeStylePreferences, EnvironmentContext, MdComponent, MdxGlobalScope, OsInfo, ToolReferences, UserProfile} from '@/md-compiler/globals' // Collects and manages global scope variables for MDX expression evaluation. import type {AdaptorOptions, UserConfigFile} from './types' import * as os from 'node:os' import process from 'node:process' -import {OsKind, ShellKind, ToolPresets} from '@truenine/md-compiler/globals' +import {OsKind, ShellKind, ToolPresets} from '@/md-compiler/globals' import {getEffectiveHomeDir} from '@/runtime-environment' import {buildDefaultCodeStylesOptions, mergeCodeStylesOptions} from './ConfigTypes.schema' diff --git a/sdk/src/adaptors/adaptor-core/LocalizedPromptReader.ts b/sdk/src/adaptors/adaptor-core/LocalizedPromptReader.ts index 6765aa08..45c5d822 100644 --- a/sdk/src/adaptors/adaptor-core/LocalizedPromptReader.ts +++ b/sdk/src/adaptors/adaptor-core/LocalizedPromptReader.ts @@ -1,4 +1,4 @@ -import type {MdxGlobalScope} from '@truenine/md-compiler/globals' +import type {MdxGlobalScope} from '@/md-compiler/globals' import type {PromptCompilerDiagnosticContext} from './PromptCompilerDiagnostics' import type { DirectoryReadResult, diff --git a/sdk/src/adaptors/adaptor-core/PromptArtifactCache.test.ts b/sdk/src/adaptors/adaptor-core/PromptArtifactCache.test.ts index 1c6d6437..553c9d45 100644 --- a/sdk/src/adaptors/adaptor-core/PromptArtifactCache.test.ts +++ b/sdk/src/adaptors/adaptor-core/PromptArtifactCache.test.ts @@ -51,11 +51,11 @@ const {mdxToMdMock, parseMarkdownMock} = vi.hoisted(() => ({ }) })) -vi.mock('@truenine/md-compiler', () => ({ +vi.mock('@/md-compiler', () => ({ mdxToMd: mdxToMdMock })) -vi.mock('@truenine/md-compiler/markdown', () => ({ +vi.mock('@/md-compiler/markdown', () => ({ parseMarkdown: parseMarkdownMock })) @@ -166,6 +166,26 @@ describe('prompt artifact cache', () => { } }) + it('keeps plain dist markdown as-is when it does not contain MDX syntax', async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tnmsc-prompt-cache-plain-dist-')) + const filePath = path.join(tempDir, 'prompt.mdx') + + try { + fs.writeFileSync(filePath, '- **Small projects (<100,000 RMB)**: Keep it simple\n', 'utf8') + + const artifact = await readPromptArtifact(filePath, { + mode: 'dist' + }) + + expect(artifact.content).toBe('- **Small projects (<100,000 RMB)**: Keep it simple\n') + expect(artifact.metadata).toEqual({}) + expect(mdxToMdMock).not.toHaveBeenCalled() + } + finally { + fs.rmSync(tempDir, {recursive: true, force: true}) + } + }) + it('falls back to mdx compilation when export-default metadata is not JSON5-compatible', async () => { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tnmsc-prompt-cache-dist-fallback-')) const filePath = path.join(tempDir, 'prompt.mdx') diff --git a/sdk/src/adaptors/adaptor-core/PromptArtifactCache.ts b/sdk/src/adaptors/adaptor-core/PromptArtifactCache.ts index 2ad98dfe..c283d82e 100644 --- a/sdk/src/adaptors/adaptor-core/PromptArtifactCache.ts +++ b/sdk/src/adaptors/adaptor-core/PromptArtifactCache.ts @@ -1,9 +1,9 @@ -import type {MdxGlobalScope} from '@truenine/md-compiler/globals' -import type {ParsedMarkdown} from '@truenine/md-compiler/markdown' +import type {MdxGlobalScope} from '@/md-compiler/globals' +import type {ParsedMarkdown} from '@/md-compiler/markdown' import * as fs from 'node:fs' import * as path from 'node:path' -import {mdxToMd} from '@truenine/md-compiler' -import {parseMarkdown} from '@truenine/md-compiler/markdown' +import {mdxToMd} from '@/md-compiler' +import {parseMarkdown} from '@/md-compiler/markdown' import JSON5 from 'json5' export interface PromptArtifact { @@ -215,6 +215,23 @@ function tryReadFastDistArtifact( } } +function hasTagLikeMdx(content: string): boolean { + return /<[A-Za-z/_$]/u.test(content) +} + +function hasExpressionLikeMdx(content: string): boolean { + return /\{[A-Za-z_$]/u.test(content) +} + +function shouldCompileDistArtifact(rawMdx: string): boolean { + const trimmed = rawMdx.trimStart() + return trimmed.startsWith('---') + || trimmed.startsWith('export default') + || rawMdx.split('\n').some(line => line.trimStart().startsWith('export const ')) + || hasTagLikeMdx(rawMdx) + || hasExpressionLikeMdx(rawMdx) +} + async function buildPromptArtifact( filePath: string, options: ReadPromptArtifactOptions @@ -234,6 +251,16 @@ async function buildPromptArtifact( lastModified } } + + if (!shouldCompileDistArtifact(rawMdx)) { + return { + rawMdx, + parsed, + content: rawMdx, + metadata: {}, + lastModified + } + } } const compileResult = await mdxToMd(rawMdx, { diff --git a/sdk/src/adaptors/adaptor-core/PromptCompilerDiagnostics.test.ts b/sdk/src/adaptors/adaptor-core/PromptCompilerDiagnostics.test.ts index f4989728..872543d0 100644 --- a/sdk/src/adaptors/adaptor-core/PromptCompilerDiagnostics.test.ts +++ b/sdk/src/adaptors/adaptor-core/PromptCompilerDiagnostics.test.ts @@ -1,5 +1,5 @@ import * as path from 'node:path' -import {UndefinedNamespaceError} from '@truenine/md-compiler/errors' +import {UndefinedNamespaceError} from '@/md-compiler/errors' import {describe, expect, it} from 'vitest' import { formatPromptCompilerDiagnostic, diff --git a/sdk/src/adaptors/adaptor-core/PromptCompilerDiagnostics.ts b/sdk/src/adaptors/adaptor-core/PromptCompilerDiagnostics.ts index e36ed182..9be2349a 100644 --- a/sdk/src/adaptors/adaptor-core/PromptCompilerDiagnostics.ts +++ b/sdk/src/adaptors/adaptor-core/PromptCompilerDiagnostics.ts @@ -1,4 +1,4 @@ -import {CompilerDiagnosticError, formatCompilerDiagnostic} from '@truenine/md-compiler/errors' +import {CompilerDiagnosticError, formatCompilerDiagnostic} from '@/md-compiler/errors' export interface PromptCompilerDiagnosticContext { readonly promptKind: string diff --git a/sdk/src/adaptors/adaptor-core/PromptTypes.ts b/sdk/src/adaptors/adaptor-core/PromptTypes.ts index 03de03ff..7ac4ec8c 100644 --- a/sdk/src/adaptors/adaptor-core/PromptTypes.ts +++ b/sdk/src/adaptors/adaptor-core/PromptTypes.ts @@ -1,4 +1,4 @@ -import type {Root, RootContent} from '@truenine/md-compiler' +import type {Root, RootContent} from '@/md-compiler' import type {ClaudeCodeCLISubAgentColors, CodingAgentTools, FilePathKind, NamingCaseKind, PromptKind, RuleScope} from './enums' import type {GlobalConfigDirectory} from './OutputTypes' diff --git a/sdk/src/adaptors/adaptor-core/plugin.ts b/sdk/src/adaptors/adaptor-core/plugin.ts index bad1c613..11547fa6 100644 --- a/sdk/src/adaptors/adaptor-core/plugin.ts +++ b/sdk/src/adaptors/adaptor-core/plugin.ts @@ -1,4 +1,4 @@ -import type {MdxGlobalScope} from '@truenine/md-compiler/globals' +import type {MdxGlobalScope} from '@/md-compiler/globals' import type { AindexConfig, CodeStylesOptions, diff --git a/sdk/src/core/cleanup.rs b/sdk/src/core/cleanup.rs index 22b2ac31..ac314dcb 100644 --- a/sdk/src/core/cleanup.rs +++ b/sdk/src/core/cleanup.rs @@ -6,10 +6,10 @@ use std::path::{Component, Path, PathBuf}; use globset::{Glob, GlobBuilder, GlobSet, GlobSetBuilder}; use serde::{Deserialize, Serialize}; use serde_json::json; -use tnmsc_logger::create_logger; use walkdir::WalkDir; use crate::core::{config, desk_paths}; +use crate::logger::create_logger; const DEFAULT_CLEANUP_SCAN_EXCLUDE_GLOBS: [&str; 6] = [ "**/node_modules/**", @@ -538,7 +538,7 @@ impl BatchedGlobPlanner { .count(); let glob_pattern_count = self.normalized_patterns.len() - literal_pattern_count; - tnmsc_logger::log_debug!( + crate::log_debug!( logger, "cleanup native glob execute started", json!({ @@ -599,7 +599,7 @@ impl BatchedGlobPlanner { literal_match_count += 1; } - tnmsc_logger::log_debug!( + crate::log_debug!( logger, "cleanup native glob literal processing complete", json!({ @@ -685,7 +685,7 @@ impl BatchedGlobPlanner { } } - tnmsc_logger::log_debug!( + crate::log_debug!( logger, "cleanup native glob group walks complete", json!({ @@ -697,7 +697,7 @@ impl BatchedGlobPlanner { ); // Convert HashMaps to sorted Vecs and deduplicate - tnmsc_logger::log_debug!( + crate::log_debug!( logger, "cleanup native glob result compaction started", json!({}) @@ -722,7 +722,7 @@ impl BatchedGlobPlanner { .collect(); delete_vec.sort_by_key(|(idx, _)| *idx); - tnmsc_logger::log_debug!( + crate::log_debug!( logger, "cleanup native glob result compaction complete", json!({ @@ -1485,7 +1485,7 @@ fn default_protection_mode_for_target(target: &CleanupTargetDto) -> ProtectionMo pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { let logger = create_logger("CleanupNative", None); - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native plan started", json!({ @@ -1577,7 +1577,7 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { } } - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native plan inventory collected", json!({ @@ -1614,7 +1614,7 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { } // Execute the batched glob expansion - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native glob expansion started", json!({ @@ -1632,7 +1632,7 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { .iter() .map(|(_, paths)| paths.len()) .sum::(); - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native glob expansion complete", json!({ @@ -1672,7 +1672,7 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { let guard = create_guard(&snapshot, &protected_rules)?; let conflicts = detect_cleanup_protection_conflicts(&output_path_owners, &guard); if !conflicts.is_empty() { - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native plan blocked", json!({ @@ -1692,7 +1692,7 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { let file_candidates = delete_files.into_iter().collect::>(); let dir_candidates = delete_dirs.into_iter().collect::>(); - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native file partition started", json!({ @@ -1702,7 +1702,7 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { ); let file_partition = partition_deletion_targets(&file_candidates, &guard, Some(&exact_safe_file_paths)); - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native file partition complete", json!({ @@ -1711,7 +1711,7 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { "violationCount": file_partition.violations.len(), }) ); - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native directory partition started", json!({ @@ -1720,7 +1720,7 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { }) ); let dir_partition = partition_deletion_targets(&dir_candidates, &guard, None); - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native directory partition complete", json!({ @@ -1729,14 +1729,14 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { "violationCount": dir_partition.violations.len(), }) ); - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native target compaction started", json!({}) ); let (files_to_delete, dirs_to_delete) = compact_deletion_targets(&file_partition.safe_paths, &dir_partition.safe_paths); - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native target compaction complete", json!({ @@ -1744,7 +1744,7 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { "compactedDirs": dirs_to_delete.len(), }) ); - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native target partition complete", json!({ @@ -1777,7 +1777,7 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { .map(|pattern| normalize_relative_glob_pattern(pattern)) .collect::>(), )?; - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native empty directory planning started", json!({ @@ -1805,7 +1805,7 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { .into_iter() .filter(|violation| !target_matches_project_root(&violation.target_path, &project_root_keys)) .collect::>(); - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native empty directory planning complete", json!({ @@ -1819,7 +1819,7 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { violations.extend(empty_dir_violations); violations.sort_by(|a, b| a.target_path.cmp(&b.target_path)); - tnmsc_logger::log_debug!( + crate::log_debug!( logger, "cleanup native plan complete", json!({ @@ -1843,10 +1843,10 @@ pub fn plan_cleanup(snapshot: CleanupSnapshot) -> Result { pub fn perform_cleanup(snapshot: CleanupSnapshot) -> Result { let logger = create_logger("CleanupNative", None); - tnmsc_logger::log_debug!(logger, "cleanup native perform started", json!({})); + crate::log_trace!(logger, "cleanup native perform started", json!({})); let plan = plan_cleanup(snapshot)?; if !plan.conflicts.is_empty() || !plan.violations.is_empty() { - tnmsc_logger::log_debug!( + crate::log_trace!( logger, "cleanup native perform blocked", json!({ @@ -1867,7 +1867,7 @@ pub fn perform_cleanup(snapshot: CleanupSnapshot) -> Result Result Result Result Result Result Result PathBuf { PathBuf::from(p) } +pub fn resolve_workspace_dir(p: &str) -> PathBuf { + let resolved = resolve_tilde(p); + resolved.canonicalize().unwrap_or(resolved) +} + /// Get the global config file path: `~/.aindex/.tnmsc.json` pub fn get_global_config_path() -> PathBuf { let runtime_environment = resolve_runtime_environment(); @@ -1243,6 +1248,13 @@ mod tests { assert_eq!(resolved, PathBuf::from("/absolute/path")); } + #[test] + fn test_resolve_workspace_dir_canonicalizes_existing_paths() { + let temp_dir = TempDir::new().unwrap(); + let resolved = resolve_workspace_dir(&temp_dir.path().to_string_lossy()); + assert_eq!(resolved, temp_dir.path().canonicalize().unwrap()); + } + #[test] fn test_user_config_file_default() { let config = UserConfigFile::default(); diff --git a/sdk/src/core/input_plugins/aindex.rs b/sdk/src/core/input_plugins/aindex.rs index 8f0914d3..7cb00991 100644 --- a/sdk/src/core/input_plugins/aindex.rs +++ b/sdk/src/core/input_plugins/aindex.rs @@ -4,6 +4,7 @@ use std::path::Path; use serde::Deserialize; use serde_json::Value; +use crate::core::config; use crate::core::plugin_shared::{Project, RelativePath, RootPath, Workspace}; #[derive(Debug, Clone, Default, Deserialize)] @@ -185,9 +186,7 @@ pub fn collect_aindex(options_json: &str) -> Result { let options: AindexInputOptions = serde_json::from_str(options_json).map_err(|e| crate::CliError::ConfigError(e.to_string()))?; - let workspace_dir = Path::new(&options.workspace_dir) - .canonicalize() - .unwrap_or_else(|_| Path::new(&options.workspace_dir).to_path_buf()); + let workspace_dir = config::resolve_workspace_dir(&options.workspace_dir); let workspace_dir_str = workspace_dir.to_string_lossy().into_owned(); let aindex_dir_name = options @@ -326,6 +325,7 @@ pub fn collect_aindex(options_json: &str) -> Result { mod tests { use super::*; use std::fs; + use std::path::PathBuf; use tempfile::TempDir; fn create_aindex_project(temp_workspace: &Path, project_name: &str, series: &str) { @@ -493,4 +493,42 @@ mod tests { .contains("Aindex project series name conflict") ); } + + #[test] + fn collect_aindex_expands_tilde_workspace_dir() { + let home_dir = crate::core::config::resolve_tilde("~"); + if home_dir == PathBuf::from("~") { + return; + } + let tmp = tempfile::Builder::new() + .prefix("tnmsc-aindex-tilde-") + .tempdir_in(&home_dir) + .unwrap(); + create_aindex_project(tmp.path(), "project-a", "app"); + let relative_workspace = tmp + .path() + .strip_prefix(&home_dir) + .unwrap_or(tmp.path()) + .to_string_lossy() + .replace('\\', "/"); + let tilde_workspace = format!( + "~{}{}", + std::path::MAIN_SEPARATOR, + relative_workspace.trim_start_matches(['/', '\\']) + ) + .replace('\\', "/"); + + let options = serde_json::json!({ + "workspaceDir": tilde_workspace, + }); + + let result = collect_aindex(&options.to_string()).unwrap(); + let parsed: serde_json::Value = serde_json::from_str(&result).unwrap(); + let workspace_dir = parsed["workspace"]["directory"]["path"] + .as_str() + .map(PathBuf::from) + .unwrap(); + + assert_eq!(workspace_dir, tmp.path().canonicalize().unwrap()); + } } diff --git a/sdk/src/core/input_plugins/command.rs b/sdk/src/core/input_plugins/command.rs index 86ef7c5b..24009d0b 100644 --- a/sdk/src/core/input_plugins/command.rs +++ b/sdk/src/core/input_plugins/command.rs @@ -3,6 +3,7 @@ use std::path::Path; use serde::Deserialize; use serde_json::Value; +use crate::core::config; use crate::core::input_plugins::localized_reader::read_flat_files; use crate::core::plugin_shared::{ FastCommandPrompt, FastCommandYAMLFrontMatter, PromptKind, RelativePath, @@ -140,9 +141,7 @@ pub fn collect_command(options_json: &str) -> Result { let options: CommandInputOptions = serde_json::from_str(options_json).map_err(|e| crate::CliError::ConfigError(e.to_string()))?; - let workspace_dir = Path::new(&options.workspace_dir) - .canonicalize() - .unwrap_or_else(|_| Path::new(&options.workspace_dir).to_path_buf()); + let workspace_dir = config::resolve_workspace_dir(&options.workspace_dir); let workspace_dir_str = workspace_dir.to_string_lossy().into_owned(); let aindex_dir_name = options diff --git a/sdk/src/core/input_plugins/global_memory.rs b/sdk/src/core/input_plugins/global_memory.rs index 14c0e954..69b5bd8b 100644 --- a/sdk/src/core/input_plugins/global_memory.rs +++ b/sdk/src/core/input_plugins/global_memory.rs @@ -2,6 +2,7 @@ use std::path::Path; use serde::Deserialize; +use crate::core::config; use crate::core::input_plugins::prompt_artifact::read_prompt_artifact; use crate::core::plugin_shared::{FilePathKind, GlobalMemoryPrompt, PromptKind, RelativePath}; @@ -36,9 +37,7 @@ pub fn collect_global_memory(options_json: &str) -> Result Result bool { + let bytes = content.as_bytes(); + let mut index = 0; + + while index + 1 < bytes.len() { + if bytes[index] == b'<' { + let next = bytes[index + 1]; + if next.is_ascii_alphabetic() || next == b'/' || next == b'_' || next == b'$' { + return true; + } + } + index += 1; + } + + false +} + +fn has_expression_like_mdx(content: &str) -> bool { + let bytes = content.as_bytes(); + let mut index = 0; + + while index + 1 < bytes.len() { + if bytes[index] == b'{' { + let next = bytes[index + 1]; + if next.is_ascii_alphabetic() || next == b'_' || next == b'$' { + return true; + } + } + index += 1; + } + + false +} + +fn should_compile_dist_artifact(content: &str) -> bool { + let trimmed = content.trim_start(); + trimmed.starts_with("---") + || trimmed.starts_with("export default") + || content + .lines() + .any(|line| line.trim_start().starts_with("export const ")) + || has_tag_like_mdx(content) + || has_expression_like_mdx(content) +} + pub fn read_prompt_artifact( file_path: &str, mode: &str, @@ -28,6 +73,15 @@ pub fn read_prompt_artifact( global_scope_json.and_then(|s| serde_json::from_str(s).ok()); if mode == "dist" { + if !should_compile_dist_artifact(&raw_mdx) { + return Ok(PromptArtifact { + raw_mdx: raw_mdx.clone(), + content: raw_mdx, + metadata: serde_json::Map::new(), + last_modified, + }); + } + let opts = MdxToMdOptions { global_scope, extract_metadata: true, @@ -50,3 +104,24 @@ pub fn read_prompt_artifact( }) } } + +#[cfg(test)] +mod tests { + use super::should_compile_dist_artifact; + + #[test] + fn plain_markdown_dist_prompt_skips_compilation() { + assert!(!should_compile_dist_artifact( + "- **Small projects (<100,000 RMB)**: Sign directly as natural person\n" + )); + } + + #[test] + fn dist_prompt_with_mdx_metadata_still_compiles() { + assert!(should_compile_dist_artifact( + "export default { scope: 'project' }\n\n# Title\n" + )); + assert!(should_compile_dist_artifact("Platform: {os.platform}\n")); + assert!(should_compile_dist_artifact("ok\n")); + } +} diff --git a/sdk/src/core/input_plugins/readme.rs b/sdk/src/core/input_plugins/readme.rs index a5087311..2b7bc900 100644 --- a/sdk/src/core/input_plugins/readme.rs +++ b/sdk/src/core/input_plugins/readme.rs @@ -3,6 +3,7 @@ use std::path::Path; use serde::Deserialize; +use crate::core::config; use crate::core::input_plugins::prompt_artifact::read_prompt_artifact; use crate::core::plugin_shared::{PromptKind, ReadmePrompt, RelativePath}; @@ -240,9 +241,7 @@ pub fn collect_readme(options_json: &str) -> Result { let options: ReadmeInputOptions = serde_json::from_str(options_json).map_err(|e| crate::CliError::ConfigError(e.to_string()))?; - let workspace_dir = Path::new(&options.workspace_dir) - .canonicalize() - .unwrap_or_else(|_| Path::new(&options.workspace_dir).to_path_buf()); + let workspace_dir = config::resolve_workspace_dir(&options.workspace_dir); let workspace_dir_str = workspace_dir.to_string_lossy().into_owned(); let aindex_dir_name = options diff --git a/sdk/src/core/input_plugins/rule.rs b/sdk/src/core/input_plugins/rule.rs index 2aad5948..5011c726 100644 --- a/sdk/src/core/input_plugins/rule.rs +++ b/sdk/src/core/input_plugins/rule.rs @@ -3,6 +3,7 @@ use std::path::Path; use serde::Deserialize; use serde_json::Value; +use crate::core::config; use crate::core::input_plugins::localized_reader::read_flat_files; use crate::core::plugin_shared::{ PromptKind, RelativePath, RulePrompt, RuleScope, RuleYAMLFrontMatter, @@ -177,9 +178,7 @@ pub fn collect_rule(options_json: &str) -> Result { let options: RuleInputOptions = serde_json::from_str(options_json).map_err(|e| crate::CliError::ConfigError(e.to_string()))?; - let workspace_dir = Path::new(&options.workspace_dir) - .canonicalize() - .unwrap_or_else(|_| Path::new(&options.workspace_dir).to_path_buf()); + let workspace_dir = config::resolve_workspace_dir(&options.workspace_dir); let workspace_dir_str = workspace_dir.to_string_lossy().into_owned(); let aindex_dir_name = options diff --git a/sdk/src/core/input_plugins/skill.rs b/sdk/src/core/input_plugins/skill.rs index 5551652b..79ab7e4d 100644 --- a/sdk/src/core/input_plugins/skill.rs +++ b/sdk/src/core/input_plugins/skill.rs @@ -4,6 +4,7 @@ use std::path::Path; use serde::Deserialize; use serde_json::Value; +use crate::core::config; use crate::core::input_plugins::prompt_artifact::read_prompt_artifact; use crate::core::plugin_shared::{ FilePathKind, McpServerConfig, PromptKind, RelativePath, SkillChildDoc, SkillMcpConfig, @@ -668,9 +669,7 @@ pub fn collect_skill(options_json: &str) -> Result { let options: SkillInputOptions = serde_json::from_str(options_json).map_err(|e| crate::CliError::ConfigError(e.to_string()))?; - let workspace_dir = Path::new(&options.workspace_dir) - .canonicalize() - .unwrap_or_else(|_| Path::new(&options.workspace_dir).to_path_buf()); + let workspace_dir = config::resolve_workspace_dir(&options.workspace_dir); let workspace_dir_str = workspace_dir.to_string_lossy().into_owned(); let aindex_dir_name = options diff --git a/sdk/src/core/input_plugins/subagent.rs b/sdk/src/core/input_plugins/subagent.rs index 9d38ebe1..95a33f5c 100644 --- a/sdk/src/core/input_plugins/subagent.rs +++ b/sdk/src/core/input_plugins/subagent.rs @@ -3,6 +3,7 @@ use std::path::Path; use serde::Deserialize; use serde_json::Value; +use crate::core::config; use crate::core::input_plugins::localized_reader::read_flat_files; use crate::core::plugin_shared::{ PromptKind, RelativePath, SubAgentPrompt, SubAgentYAMLFrontMatter, @@ -159,9 +160,7 @@ pub fn collect_subagent(options_json: &str) -> Result { let options: SubAgentInputOptions = serde_json::from_str(options_json).map_err(|e| crate::CliError::ConfigError(e.to_string()))?; - let workspace_dir = Path::new(&options.workspace_dir) - .canonicalize() - .unwrap_or_else(|_| Path::new(&options.workspace_dir).to_path_buf()); + let workspace_dir = config::resolve_workspace_dir(&options.workspace_dir); let workspace_dir_str = workspace_dir.to_string_lossy().into_owned(); let aindex_dir_name = options diff --git a/sdk/src/core/input_plugins/workspace.rs b/sdk/src/core/input_plugins/workspace.rs index a6ebdd8e..b8f1d68e 100644 --- a/sdk/src/core/input_plugins/workspace.rs +++ b/sdk/src/core/input_plugins/workspace.rs @@ -31,11 +31,7 @@ pub fn collect_workspace(options_json: &str) -> Result let options: WorkspaceInputOptions = serde_json::from_str(options_json).map_err(|e| crate::CliError::ConfigError(e.to_string()))?; - let workspace_dir_raw = options.workspace_dir; - let expanded_workspace_dir = config::resolve_tilde(&workspace_dir_raw); - let workspace_dir = expanded_workspace_dir - .canonicalize() - .unwrap_or(expanded_workspace_dir); + let workspace_dir = config::resolve_workspace_dir(&options.workspace_dir); let workspace_dir_str = workspace_dir.to_string_lossy().into_owned(); let aindex_dir_name = options diff --git a/sdk/src/core/native-binding-loader.test.ts b/sdk/src/core/native-binding-loader.test.ts index ead1734c..20203413 100644 --- a/sdk/src/core/native-binding-loader.test.ts +++ b/sdk/src/core/native-binding-loader.test.ts @@ -437,8 +437,9 @@ describe('integration scenarios', () => { } const loggerOptions: NativeBindingLoaderOptions = { - packageName: '@truenine/logger', - binaryName: 'napi-logger', + packageName: '@truenine/memory-sync-sdk', + binaryName: 'napi-memory-sync-cli', + cliExportName: 'logger', bindingValidator: (value): value is LoggerBinding => value != null && typeof value === 'object' @@ -469,8 +470,8 @@ describe('integration scenarios', () => { } const scriptRuntimeOptions: NativeBindingLoaderOptions = { - packageName: '@truenine/script-runtime', - binaryName: 'napi-script-runtime', + packageName: '@truenine/memory-sync-sdk', + binaryName: 'napi-memory-sync-cli', cliExportName: 'scriptRuntime', optionalMethods: { validatePublicPath: ['validate_public_path'], diff --git a/sdk/src/core/native-binding-loader.ts b/sdk/src/core/native-binding-loader.ts index 317c2c64..6b2a504d 100644 --- a/sdk/src/core/native-binding-loader.ts +++ b/sdk/src/core/native-binding-loader.ts @@ -30,6 +30,7 @@ const DEFAULT_LOCAL_CANDIDATE_RELATIVE_PATHS = [ '../dist/', '../npm/', '../../npm/', + '../../cli/npm/', '../../../cli/npm/', '../../../../cli/npm/' ] as const @@ -37,6 +38,7 @@ const DEFAULT_LOCAL_CANDIDATE_RELATIVE_PATHS = [ const DEFAULT_PACKAGE_DIR_CANDIDATE_RELATIVE_PATHS = [ '../npm/', '../../npm/', + '../../cli/npm/', '../../../cli/npm/', '../../../../cli/npm/' ] as const diff --git a/sdk/src/diagnostic_helpers.rs b/sdk/src/diagnostic_helpers.rs index 216c881e..1783c0e6 100644 --- a/sdk/src/diagnostic_helpers.rs +++ b/sdk/src/diagnostic_helpers.rs @@ -1,5 +1,5 @@ use serde_json::{Map, Value}; -use tnmsc_logger::LoggerDiagnosticInput; +use crate::logger::LoggerDiagnosticInput; pub(crate) fn line(value: impl Into) -> Vec { vec![value.into()] diff --git a/sdk/src/globals.ts b/sdk/src/globals.ts index 4622248d..c7b1eeb0 100644 --- a/sdk/src/globals.ts +++ b/sdk/src/globals.ts @@ -1 +1 @@ -export * from '@truenine/md-compiler/globals' +export * from './md-compiler/globals' diff --git a/sdk/src/index.ts b/sdk/src/index.ts index 24fa15a7..3e0b9880 100644 --- a/sdk/src/index.ts +++ b/sdk/src/index.ts @@ -181,6 +181,70 @@ export type { LoggerDiagnosticRecord, LogLevel } from './libraries/logger' +export { + buildPromptTomlArtifact, + buildTomlDocument, + mdxToMd +} from './md-compiler' +export { + buildFrontMatter, + buildMarkdownWithFrontMatter, + buildMarkdownWithRawFrontMatter, + buildRawFrontMatter, + doubleQuoted, + parseMarkdown, + transformMdxReferencesToMd, + wrapRawFrontMatter +} from './md-compiler/markdown' +export { + CompilerDiagnosticError, + ExportParseError, + ScopeError, + UndefinedNamespaceError, + UndefinedVariableError, + createCompilerDiagnostic, + formatCompilerDiagnostic +} from './md-compiler/errors' +export { + OsKind, + ShellKind, + ToolPresets +} from './md-compiler/globals' +export type { + BuildPromptTomlArtifactOptions, + BuildTomlDocumentOptions, + EvaluationScope, + ExportMetadata, + MdxFlowExpression, + MdxGlobalScope, + MdxJsxFlowElement, + MdxJsxTextElement, + MdxTextExpression, + MdxToMdOptions, + MdxToMdResult, + MdxjsEsm, + Root, + RootContent +} from './md-compiler' +export type { + CodeStylePreferences, + EnvironmentContext, + MdComponent, + OsInfo, + ToolReferences, + UserProfile +} from './md-compiler/globals' +export type { + CompilerDiagnostic, + CompilerDiagnosticContext, + CompilerDiagnosticPoint, + CompilerDiagnosticPosition, + FormatCompilerDiagnosticOptions +} from './md-compiler/errors' +export type { + BuildMarkdownOptions, + ParsedMarkdown +} from './md-compiler/markdown' export { defineProxy, getProxyModuleConfig, diff --git a/sdk/src/inputs/AbstractInputCapability.ts b/sdk/src/inputs/AbstractInputCapability.ts index fafceed5..b600179c 100644 --- a/sdk/src/inputs/AbstractInputCapability.ts +++ b/sdk/src/inputs/AbstractInputCapability.ts @@ -1,4 +1,4 @@ -import type {ParsedMarkdown} from '@truenine/md-compiler/markdown' +import type {ParsedMarkdown} from '@/md-compiler/markdown' import type { AdaptorOptions, AdaptorScopeRegistration, @@ -15,7 +15,7 @@ import type { import {spawn} from 'node:child_process' import * as path from 'node:path' -import {parseMarkdown} from '@truenine/md-compiler/markdown' +import {parseMarkdown} from '@/md-compiler/markdown' import {PathPlaceholders} from '@/adaptors/adaptor-core' import {buildDiagnostic, diagnosticLines} from '@/diagnostics' import {createLogger} from '@/libraries/logger' diff --git a/sdk/src/inputs/input-agentskills-export-fallback.test.ts b/sdk/src/inputs/input-agentskills-export-fallback.test.ts index d3b56b7e..22582418 100644 --- a/sdk/src/inputs/input-agentskills-export-fallback.test.ts +++ b/sdk/src/inputs/input-agentskills-export-fallback.test.ts @@ -6,7 +6,7 @@ import glob from 'fast-glob' import {afterEach, describe, expect, it, vi} from 'vitest' import {mergeConfig} from '../config' -vi.mock('@truenine/md-compiler', () => ({ +vi.mock('@/md-compiler', () => ({ mdxToMd: async (content: string) => ({ content: content.replace(/export default\s*\{[\s\S]*?\}\s*/u, '').trim(), metadata: { diff --git a/sdk/src/inputs/runtime.ts b/sdk/src/inputs/runtime.ts index 0a087a70..0f5562f8 100644 --- a/sdk/src/inputs/runtime.ts +++ b/sdk/src/inputs/runtime.ts @@ -1,4 +1,4 @@ -import type {MdxGlobalScope} from '@truenine/md-compiler/globals' +import type {MdxGlobalScope} from '@/md-compiler/globals' import type {AdaptorOptions, InputCapability, InputCapabilityContext, InputCollectedContext, UserConfigFile} from '@/adaptors/adaptor-core' import type {RuntimeCommand} from '@/runtime-command' diff --git a/sdk/src/internal/prompts-legacy.ts b/sdk/src/internal/prompts-legacy.ts index 43e386f8..890d6816 100644 --- a/sdk/src/internal/prompts-legacy.ts +++ b/sdk/src/internal/prompts-legacy.ts @@ -16,7 +16,7 @@ import type {YAMLFrontMatter} from '@/adaptors/adaptor-core/PromptTypes' import * as fs from 'node:fs' import * as path from 'node:path' import process from 'node:process' -import {parseMarkdown} from '@truenine/md-compiler/markdown' +import {parseMarkdown} from '@/md-compiler/markdown' import glob from 'fast-glob' import { isAindexProjectSeriesName, diff --git a/sdk/src/internal/sdk-binding.ts b/sdk/src/internal/sdk-binding.ts index 51066f3c..2a5f8a05 100644 --- a/sdk/src/internal/sdk-binding.ts +++ b/sdk/src/internal/sdk-binding.ts @@ -140,6 +140,61 @@ function logProjectSummary( }) } +function logInstallCompletion( + logger: RuntimeExecutionContext['logger'], + summary: { + readonly deletedFiles: number + readonly deletedDirs: number + readonly writtenFiles: number + readonly writtenDirs: number + } +): void { + const totalFiles = summary.deletedFiles + summary.writtenFiles + const totalDirs = summary.deletedDirs + summary.writtenDirs + + if (totalFiles === 0 && totalDirs === 0) { + logger.info('Sync complete\n\nNo changes were needed.') + return + } + + logger.info('Sync complete', { + files: totalFiles, + directories: totalDirs + }) +} + +function logDryRunCompletion( + logger: RuntimeExecutionContext['logger'], + filesAffected: number, + dirsAffected: number +): void { + if (filesAffected === 0 && dirsAffected === 0) { + logger.info('Dry run complete\n\nNo changes would be made.') + return + } + + logger.info('Dry run complete', { + files: filesAffected, + directories: dirsAffected + }) +} + +function logCleanCompletion( + logger: RuntimeExecutionContext['logger'], + filesAffected: number, + dirsAffected: number +): void { + if (filesAffected === 0 && dirsAffected === 0) { + logger.info('Cleanup complete\n\nNothing needed to be removed.') + return + } + + logger.info('Cleanup complete', { + files: filesAffected, + directories: dirsAffected + }) +} + function runExecutionPreflight( ctx: RuntimeExecutionContext, commandName: string @@ -149,19 +204,8 @@ function runExecutionPreflight( ctx.logger.warn(buildDiagnostic({ code: 'EXECUTION_SCOPE_WORKSPACE', title: 'Running from the workspace root', - rootCause: diagnosticLines( - 'This run will only touch workspace-level outputs and global outputs.', - `Current directory: ${ctx.executionPlan.cwd}` - ), - exactFix: diagnosticLines( - 'Run tnmsc from a managed project directory to target one project, or from outside the workspace to include every managed project.' - ), - details: { - command: commandName, - scope: 'workspace', - cwd: ctx.executionPlan.cwd, - workspaceDir: ctx.executionPlan.workspaceDir - } + rootCause: diagnosticLines(`tnmsc will only sync workspace-level outputs in "${ctx.executionPlan.workspaceDir}".`), + exactFix: diagnosticLines('Run tnmsc inside a managed project to sync one project, or outside the workspace to sync everything.') })) return void 0 case 'project': @@ -171,19 +215,8 @@ function runExecutionPreflight( ctx.logger.warn(buildDiagnostic({ code: 'EXECUTION_SCOPE_EXTERNAL', title: 'Running outside the workspace', - rootCause: diagnosticLines( - 'This run will process the workspace, every managed project, and global outputs.', - `Current directory: ${ctx.executionPlan.cwd}` - ), - exactFix: diagnosticLines( - `Run tnmsc from "${ctx.executionPlan.workspaceDir}" for workspace-only execution, or from a managed project directory for project-only execution.` - ), - details: { - command: commandName, - scope: 'external', - cwd: ctx.executionPlan.cwd, - workspaceDir: ctx.executionPlan.workspaceDir - } + rootCause: diagnosticLines(`tnmsc will sync "${ctx.executionPlan.workspaceDir}" and every managed project from the current directory.`), + exactFix: diagnosticLines(`Run tnmsc in "${ctx.executionPlan.workspaceDir}" for workspace-only sync, or inside a managed project for project-only sync.`) })) logExternalProjectGroups(ctx) return void 0 @@ -283,17 +316,10 @@ async function runInstall(options: MemorySyncCommandOptions = {}): Promise total + declarations.length, 0) - ctx.logger.info('Prepared output plan', { + const declarationCount = [...predeclaredOutputs.values()].reduce((total, declarations) => total + declarations.length, 0) + ctx.logger.debug('Prepared output plan', { adaptors: predeclaredOutputs.size, declarations: declarationCount }) @@ -314,10 +340,12 @@ async function runInstall(options: MemorySyncCommandOptions = {}): Promise 0 || cleanupResult.deletedDirs > 0) { + ctx.logger.info('Removed stale outputs', { + files: cleanupResult.deletedFiles, + directories: cleanupResult.deletedDirs + }) + } const writeResults = await executeDeclarativeWriteOutputs( ctx.outputPlugins, @@ -336,11 +364,12 @@ async function runInstall(options: MemorySyncCommandOptions = {}): Promise 0 || totalDirs > 0) { + ctx.logger.info('Wrote outputs', { + files: totalFiles, + directories: totalDirs + }) + } if (writeErrors.length > 0) { return buildCommandResult({ @@ -374,9 +403,11 @@ async function runInstall(options: MemorySyncCommandOptions = {}): Promise ({ describe('logger bindings', () => { beforeEach(() => { + vi.resetModules() vi.clearAllMocks() nativeModule.createLogger.mockReturnValue(nativeLogger) nativeModule.getGlobalLogLevel.mockReturnValue('info') @@ -48,7 +49,7 @@ describe('logger bindings', () => { }) it('routes warn diagnostics through the native diagnostic path without JS serialization', async () => { - const {createLogger} = await import('./index') + const {createLogger} = await import('./logger') const logger = createLogger('logger-test') logger.warn({ @@ -72,7 +73,7 @@ describe('logger bindings', () => { }) it('forwards plain log arguments to the native emit path', async () => { - const {createLogger} = await import('./index') + const {createLogger} = await import('./logger') const logger = createLogger('logger-test') logger.info('hello', {count: 1}) @@ -87,7 +88,7 @@ describe('logger bindings', () => { }) it('keeps metadata undefined when no extra fields are provided', async () => { - const {createLogger} = await import('./index') + const {createLogger} = await import('./logger') const logger = createLogger('logger-test') logger.info('hello') @@ -96,7 +97,7 @@ describe('logger bindings', () => { }) it('passes the explicit log level through to native logger creation', async () => { - const {createLogger} = await import('./index') + const {createLogger} = await import('./logger') const logger = createLogger('logger-test', 'info') logger.debug('visible-to-native', {count: 1}) @@ -106,7 +107,7 @@ describe('logger bindings', () => { }) it('keeps silent diagnostics flowing to native buffering', async () => { - const {createLogger} = await import('./index') + const {createLogger} = await import('./logger') const logger = createLogger('logger-test', 'silent') logger.warn({ @@ -119,7 +120,7 @@ describe('logger bindings', () => { }) it('exposes buffered diagnostics helpers', async () => { - const {clearBufferedDiagnostics, drainBufferedDiagnostics, flushOutput} = await import('./index') + const {clearBufferedDiagnostics, drainBufferedDiagnostics, flushOutput} = await import('./logger') clearBufferedDiagnostics() const diagnostics = drainBufferedDiagnostics() diff --git a/sdk/src/libraries/logger.ts b/sdk/src/libraries/logger.ts index 2d4e8c9d..d7ba2e5a 100644 --- a/sdk/src/libraries/logger.ts +++ b/sdk/src/libraries/logger.ts @@ -62,8 +62,8 @@ function isNapiLoggerModule(value: unknown): value is NapiLoggerModule { } const getNapiBinding = createNativeBindingLoader({ - packageName: '@truenine/logger', - binaryName: 'napi-logger', + packageName: '@truenine/memory-sync-sdk', + binaryName: 'napi-memory-sync-cli', bindingValidator: isNapiLoggerModule, cliExportName: 'logger' }) diff --git a/sdk/src/libraries/script-runtime/index.ts b/sdk/src/libraries/script-runtime/index.ts index 5fddd365..cddee355 100644 --- a/sdk/src/libraries/script-runtime/index.ts +++ b/sdk/src/libraries/script-runtime/index.ts @@ -46,8 +46,8 @@ function isScriptRuntimeBinding(value: unknown): value is ScriptRuntimeBinding { } const getBinding = createNativeBindingLoader({ - packageName: '@truenine/script-runtime', - binaryName: 'napi-script-runtime', + packageName: '@truenine/memory-sync-sdk', + binaryName: 'napi-memory-sync-cli', bindingValidator: isScriptRuntimeBinding, cliExportName: 'scriptRuntime', optionalMethods: { @@ -79,7 +79,7 @@ function callResolvePublicPathBinding(filePath: string, ctxJson: string, logical function getPackageWorkerPaths(): string[] { try { - const packageJsonPath = runtimeRequire.resolve('@truenine/script-runtime/package.json') + const packageJsonPath = runtimeRequire.resolve('@truenine/memory-sync-sdk/package.json') const packageDir = dirname(packageJsonPath) return [ @@ -103,13 +103,8 @@ function getWorkerPath(): string { fileURLToPath(new URL('../script-runtime-worker.mjs', import.meta.url)), fileURLToPath(new URL('../../resolve-proxy-worker.mjs', import.meta.url)), fileURLToPath(new URL('../../script-runtime-worker.mjs', import.meta.url)), - fileURLToPath(new URL('../../libraries/script-runtime/dist/resolve-proxy-worker.mjs', import.meta.url)), - fileURLToPath(new URL('../../libraries/script-runtime/dist/script-runtime-worker.mjs', import.meta.url)), fileURLToPath(new URL('../../../cli/dist/script-runtime-worker.mjs', import.meta.url)), - fileURLToPath(new URL('../../../../cli/dist/script-runtime-worker.mjs', import.meta.url)), - fileURLToPath(new URL('../../../libraries/script-runtime/dist/resolve-proxy-worker.mjs', import.meta.url)), - fileURLToPath(new URL('../../../../libraries/script-runtime/dist/resolve-proxy-worker.mjs', import.meta.url)), - fileURLToPath(new URL('../../../../../libraries/script-runtime/dist/resolve-proxy-worker.mjs', import.meta.url)) + fileURLToPath(new URL('../../../../cli/dist/script-runtime-worker.mjs', import.meta.url)) ] for (const candidatePath of candidatePaths) { diff --git a/libraries/script-runtime/src/native-binding.test.ts b/sdk/src/libraries/script-runtime/native-binding.test.ts similarity index 80% rename from libraries/script-runtime/src/native-binding.test.ts rename to sdk/src/libraries/script-runtime/native-binding.test.ts index 0a8f67b4..ddb99b7f 100644 --- a/libraries/script-runtime/src/native-binding.test.ts +++ b/sdk/src/libraries/script-runtime/native-binding.test.ts @@ -7,11 +7,11 @@ interface PlatformBinding { } const PLATFORM_BINDINGS: Record = { - 'win32-x64': {local: 'napi-script-runtime.win32-x64-msvc', suffix: 'win32-x64-msvc'}, - 'linux-x64': {local: 'napi-script-runtime.linux-x64-gnu', suffix: 'linux-x64-gnu'}, - 'linux-arm64': {local: 'napi-script-runtime.linux-arm64-gnu', suffix: 'linux-arm64-gnu'}, - 'darwin-arm64': {local: 'napi-script-runtime.darwin-arm64', suffix: 'darwin-arm64'}, - 'darwin-x64': {local: 'napi-script-runtime.darwin-x64', suffix: 'darwin-x64'} + 'win32-x64': {local: 'napi-memory-sync-cli.win32-x64-msvc', suffix: 'win32-x64-msvc'}, + 'linux-x64': {local: 'napi-memory-sync-cli.linux-x64-gnu', suffix: 'linux-x64-gnu'}, + 'linux-arm64': {local: 'napi-memory-sync-cli.linux-arm64-gnu', suffix: 'linux-arm64-gnu'}, + 'darwin-arm64': {local: 'napi-memory-sync-cli.darwin-arm64', suffix: 'darwin-arm64'}, + 'darwin-x64': {local: 'napi-memory-sync-cli.darwin-x64', suffix: 'darwin-x64'} } function getPlatformBinding(): PlatformBinding | undefined { diff --git a/libraries/md-compiler/src/compiler/backward-compat.test.ts b/sdk/src/md-compiler/compiler/backward-compat.test.ts similarity index 99% rename from libraries/md-compiler/src/compiler/backward-compat.test.ts rename to sdk/src/md-compiler/compiler/backward-compat.test.ts index bf969916..7cea46f2 100644 --- a/libraries/md-compiler/src/compiler/backward-compat.test.ts +++ b/sdk/src/md-compiler/compiler/backward-compat.test.ts @@ -11,7 +11,7 @@ import type {MdxjsEsm} from './types' import {afterEach, beforeEach, describe, expect, it} from 'vitest' -import {registerBuiltInComponents} from '@/components' +import {registerBuiltInComponents} from '@/md-compiler/components' import {clearComponents} from './component-registry' import {parseExports} from './export-parser' import {mdxToMd} from './mdx-to-md' diff --git a/libraries/md-compiler/src/compiler/component-processor.property.test.ts b/sdk/src/md-compiler/compiler/component-processor.property.test.ts similarity index 100% rename from libraries/md-compiler/src/compiler/component-processor.property.test.ts rename to sdk/src/md-compiler/compiler/component-processor.property.test.ts diff --git a/libraries/md-compiler/src/compiler/component-processor.ts b/sdk/src/md-compiler/compiler/component-processor.ts similarity index 100% rename from libraries/md-compiler/src/compiler/component-processor.ts rename to sdk/src/md-compiler/compiler/component-processor.ts diff --git a/libraries/md-compiler/src/compiler/component-registry.property.test.ts b/sdk/src/md-compiler/compiler/component-registry.property.test.ts similarity index 100% rename from libraries/md-compiler/src/compiler/component-registry.property.test.ts rename to sdk/src/md-compiler/compiler/component-registry.property.test.ts diff --git a/libraries/md-compiler/src/compiler/component-registry.test.ts b/sdk/src/md-compiler/compiler/component-registry.test.ts similarity index 100% rename from libraries/md-compiler/src/compiler/component-registry.test.ts rename to sdk/src/md-compiler/compiler/component-registry.test.ts diff --git a/libraries/md-compiler/src/compiler/component-registry.ts b/sdk/src/md-compiler/compiler/component-registry.ts similarity index 100% rename from libraries/md-compiler/src/compiler/component-registry.ts rename to sdk/src/md-compiler/compiler/component-registry.ts diff --git a/libraries/md-compiler/src/compiler/export-parser.test.ts b/sdk/src/md-compiler/compiler/export-parser.test.ts similarity index 97% rename from libraries/md-compiler/src/compiler/export-parser.test.ts rename to sdk/src/md-compiler/compiler/export-parser.test.ts index 2764fa4f..14d976d5 100644 --- a/libraries/md-compiler/src/compiler/export-parser.test.ts +++ b/sdk/src/md-compiler/compiler/export-parser.test.ts @@ -1,5 +1,5 @@ import {describe, expect, it} from 'vitest' -import {ExportParseError} from '@/errors' +import {ExportParseError} from '@/md-compiler/errors' import {parseExports} from './export-parser' import {parseMdx} from './parser' diff --git a/libraries/md-compiler/src/compiler/export-parser.ts b/sdk/src/md-compiler/compiler/export-parser.ts similarity index 99% rename from libraries/md-compiler/src/compiler/export-parser.ts rename to sdk/src/md-compiler/compiler/export-parser.ts index e66fdd60..20415b66 100644 --- a/libraries/md-compiler/src/compiler/export-parser.ts +++ b/sdk/src/md-compiler/compiler/export-parser.ts @@ -1,5 +1,5 @@ import type {EvaluationScope, MdxjsEsm} from './types' // Extracts metadata from MDX export statements // export-parser.ts -import {ExportParseError} from '@/errors' +import {ExportParseError} from '@/md-compiler/errors' /** * Metadata source type diff --git a/libraries/md-compiler/src/compiler/expression-eval.property.test.ts b/sdk/src/md-compiler/compiler/expression-eval.property.test.ts similarity index 100% rename from libraries/md-compiler/src/compiler/expression-eval.property.test.ts rename to sdk/src/md-compiler/compiler/expression-eval.property.test.ts diff --git a/libraries/md-compiler/src/compiler/expression-eval.test.ts b/sdk/src/md-compiler/compiler/expression-eval.test.ts similarity index 99% rename from libraries/md-compiler/src/compiler/expression-eval.test.ts rename to sdk/src/md-compiler/compiler/expression-eval.test.ts index cbd91a7f..edf4fa84 100644 --- a/libraries/md-compiler/src/compiler/expression-eval.test.ts +++ b/sdk/src/md-compiler/compiler/expression-eval.test.ts @@ -6,7 +6,7 @@ */ import {describe, expect, it} from 'vitest' -import {UndefinedNamespaceError, UndefinedVariableError} from '@/errors' +import {UndefinedNamespaceError, UndefinedVariableError} from '@/md-compiler/errors' import {evaluateExpression} from './expression-eval' describe('expression-eval', () => { diff --git a/libraries/md-compiler/src/compiler/expression-eval.ts b/sdk/src/md-compiler/compiler/expression-eval.ts similarity index 99% rename from libraries/md-compiler/src/compiler/expression-eval.ts rename to sdk/src/md-compiler/compiler/expression-eval.ts index 4be0fe19..60b5e9df 100644 --- a/libraries/md-compiler/src/compiler/expression-eval.ts +++ b/sdk/src/md-compiler/compiler/expression-eval.ts @@ -1,5 +1,5 @@ import type {EvaluationScope, ExpressionDiagnosticContext} from './types.js' // JavaScript expression evaluation module for MDX // expression-eval.ts -import {UndefinedNamespaceError, UndefinedVariableError} from '@/errors' +import {UndefinedNamespaceError, UndefinedVariableError} from '@/md-compiler/errors' /** * Options for expression evaluation diff --git a/libraries/md-compiler/src/compiler/index.ts b/sdk/src/md-compiler/compiler/index.ts similarity index 97% rename from libraries/md-compiler/src/compiler/index.ts rename to sdk/src/md-compiler/compiler/index.ts index 939fdeb2..3d2b4b84 100644 --- a/libraries/md-compiler/src/compiler/index.ts +++ b/sdk/src/md-compiler/compiler/index.ts @@ -57,4 +57,4 @@ export type { MdxGlobalScope, ToolReferences, UserProfile -} from '@/globals' +} from '@/md-compiler/globals' diff --git a/libraries/md-compiler/src/compiler/jsx-converter.ts b/sdk/src/md-compiler/compiler/jsx-converter.ts similarity index 100% rename from libraries/md-compiler/src/compiler/jsx-converter.ts rename to sdk/src/md-compiler/compiler/jsx-converter.ts diff --git a/libraries/md-compiler/src/compiler/jsx-expression-eval.ts b/sdk/src/md-compiler/compiler/jsx-expression-eval.ts similarity index 100% rename from libraries/md-compiler/src/compiler/jsx-expression-eval.ts rename to sdk/src/md-compiler/compiler/jsx-expression-eval.ts diff --git a/libraries/md-compiler/src/compiler/mdx-to-md.property.test.ts b/sdk/src/md-compiler/compiler/mdx-to-md.property.test.ts similarity index 98% rename from libraries/md-compiler/src/compiler/mdx-to-md.property.test.ts rename to sdk/src/md-compiler/compiler/mdx-to-md.property.test.ts index e3ded35b..9a8fa019 100644 --- a/libraries/md-compiler/src/compiler/mdx-to-md.property.test.ts +++ b/sdk/src/md-compiler/compiler/mdx-to-md.property.test.ts @@ -9,7 +9,7 @@ import * as fc from 'fast-check' import {afterEach, beforeEach, describe, expect, it} from 'vitest' -import {registerBuiltInComponents} from '@/components' +import {registerBuiltInComponents} from '@/md-compiler/components' import {clearComponents} from './component-registry' import {mdxToMd} from './mdx-to-md' diff --git a/libraries/md-compiler/src/compiler/mdx-to-md.test.ts b/sdk/src/md-compiler/compiler/mdx-to-md.test.ts similarity index 99% rename from libraries/md-compiler/src/compiler/mdx-to-md.test.ts rename to sdk/src/md-compiler/compiler/mdx-to-md.test.ts index 1d877975..65075017 100644 --- a/libraries/md-compiler/src/compiler/mdx-to-md.test.ts +++ b/sdk/src/md-compiler/compiler/mdx-to-md.test.ts @@ -5,9 +5,9 @@ * as specified in Requirements 1, 4, 5, and 6. */ -import type {UndefinedNamespaceError} from '@/errors' +import type {UndefinedNamespaceError} from '@/md-compiler/errors' import {afterEach, beforeEach, describe, expect, it} from 'vitest' -import {registerBuiltInComponents} from '@/components' +import {registerBuiltInComponents} from '@/md-compiler/components' import {clearComponents} from './component-registry' import {mdxToMd} from './mdx-to-md' diff --git a/libraries/md-compiler/src/compiler/mdx-to-md.ts b/sdk/src/md-compiler/compiler/mdx-to-md.ts similarity index 98% rename from libraries/md-compiler/src/compiler/mdx-to-md.ts rename to sdk/src/md-compiler/compiler/mdx-to-md.ts index fe678e47..7897d379 100644 --- a/libraries/md-compiler/src/compiler/mdx-to-md.ts +++ b/sdk/src/md-compiler/compiler/mdx-to-md.ts @@ -5,7 +5,7 @@ import remarkGfm from 'remark-gfm' import remarkStringify from 'remark-stringify' import {unified} from 'unified' import * as YAML_LIB from 'yaml' -import {registerBuiltInComponents} from '@/components' +import {registerBuiltInComponents} from '@/md-compiler/components' import {getComponents} from './component-registry' import {parseExports} from './export-parser' import {parseMdx} from './parser' diff --git a/libraries/md-compiler/src/compiler/parser.property.test.ts b/sdk/src/md-compiler/compiler/parser.property.test.ts similarity index 100% rename from libraries/md-compiler/src/compiler/parser.property.test.ts rename to sdk/src/md-compiler/compiler/parser.property.test.ts diff --git a/libraries/md-compiler/src/compiler/parser.ts b/sdk/src/md-compiler/compiler/parser.ts similarity index 100% rename from libraries/md-compiler/src/compiler/parser.ts rename to sdk/src/md-compiler/compiler/parser.ts diff --git a/libraries/md-compiler/src/compiler/transformer.ts b/sdk/src/md-compiler/compiler/transformer.ts similarity index 100% rename from libraries/md-compiler/src/compiler/transformer.ts rename to sdk/src/md-compiler/compiler/transformer.ts diff --git a/libraries/md-compiler/src/compiler/types.ts b/sdk/src/md-compiler/compiler/types.ts similarity index 94% rename from libraries/md-compiler/src/compiler/types.ts rename to sdk/src/md-compiler/compiler/types.ts index 2bce16d6..541eef60 100644 --- a/libraries/md-compiler/src/compiler/types.ts +++ b/sdk/src/md-compiler/compiler/types.ts @@ -4,8 +4,8 @@ import type { MdxJsxTextElement } from 'mdast-util-mdx' import type {ExportMetadata} from './export-parser' -import type {CompilerDiagnosticPosition} from '@/errors' -import type {MdxGlobalScope} from '@/globals' +import type {CompilerDiagnosticPosition} from '@/md-compiler/errors' +import type {MdxGlobalScope} from '@/md-compiler/globals' /** Scope containing values available for expression evaluation */ export interface EvaluationScope { diff --git a/libraries/md-compiler/src/components/Md.test.ts b/sdk/src/md-compiler/components/Md.test.ts similarity index 98% rename from libraries/md-compiler/src/components/Md.test.ts rename to sdk/src/md-compiler/components/Md.test.ts index bd9e2c70..14bc2037 100644 --- a/libraries/md-compiler/src/components/Md.test.ts +++ b/sdk/src/md-compiler/components/Md.test.ts @@ -7,7 +7,7 @@ import type {Paragraph, RootContent, Text} from 'mdast' import type {MdxJsxFlowElement} from 'mdast-util-mdx' -import type {ProcessingContext} from '@/compiler/types' +import type {ProcessingContext} from '@/md-compiler/compiler/types' import {describe, expect, it} from 'vitest' import {MdHandler} from './Md' diff --git a/libraries/md-compiler/src/components/Md.ts b/sdk/src/md-compiler/components/Md.ts similarity index 94% rename from libraries/md-compiler/src/components/Md.ts rename to sdk/src/md-compiler/components/Md.ts index 597e0840..5720025c 100644 --- a/libraries/md-compiler/src/components/Md.ts +++ b/sdk/src/md-compiler/components/Md.ts @@ -1,8 +1,8 @@ import type {RootContent, Text} from 'mdast' // Md component handler - wrapper for conditional Markdown content // src/components/Md.ts import type {MdxJsxFlowElement, MdxJsxTextElement} from 'mdast-util-mdx' -import type {EvaluateExpressionOptions} from '@/compiler/expression-eval' -import type {ExpressionDiagnosticContext, ProcessingContext} from '@/compiler/types' -import {evaluateExpression} from '@/compiler/expression-eval' +import type {EvaluateExpressionOptions} from '@/md-compiler/compiler/expression-eval' +import type {ExpressionDiagnosticContext, ProcessingContext} from '@/md-compiler/compiler/types' +import {evaluateExpression} from '@/md-compiler/compiler/expression-eval' function createExpressionOptions( ctx: ProcessingContext, diff --git a/libraries/md-compiler/src/components/index.ts b/sdk/src/md-compiler/components/index.ts similarity index 66% rename from libraries/md-compiler/src/components/index.ts rename to sdk/src/md-compiler/components/index.ts index eb515a05..29412e2f 100644 --- a/libraries/md-compiler/src/components/index.ts +++ b/sdk/src/md-compiler/components/index.ts @@ -1,4 +1,4 @@ -import {registerComponent} from '@/compiler/component-registry' // Entry point for built-in MDX components // src/components/index.ts +import {registerComponent} from '@/md-compiler/compiler/component-registry' // Entry point for built-in MDX components // src/components/index.ts import {MdHandler, MdLineHandler} from './Md' export { @@ -18,4 +18,4 @@ export function registerBuiltInComponents(): void { export { registerComponent -} from '@/compiler/component-registry' // Re-export component registration helper for convenience +} from '@/md-compiler/compiler/component-registry' // Re-export component registration helper for convenience diff --git a/libraries/md-compiler/src/errors/index.ts b/sdk/src/md-compiler/errors/index.ts similarity index 100% rename from libraries/md-compiler/src/errors/index.ts rename to sdk/src/md-compiler/errors/index.ts diff --git a/libraries/md-compiler/src/globals/index.ts b/sdk/src/md-compiler/globals/index.ts similarity index 100% rename from libraries/md-compiler/src/globals/index.ts rename to sdk/src/md-compiler/globals/index.ts diff --git a/libraries/md-compiler/src/index.ts b/sdk/src/md-compiler/index.ts similarity index 76% rename from libraries/md-compiler/src/index.ts rename to sdk/src/md-compiler/index.ts index ed02297a..547d7690 100644 --- a/libraries/md-compiler/src/index.ts +++ b/sdk/src/md-compiler/index.ts @@ -25,3 +25,12 @@ export type { BuildPromptTomlArtifactOptions, BuildTomlDocumentOptions } from './toml' +export type { + CodeStylePreferences, + EnvironmentContext, + MdComponent, + MdxGlobalScope, + OsInfo, + ToolReferences, + UserProfile +} from './globals' diff --git a/libraries/md-compiler/src/markdown/index.ts b/sdk/src/md-compiler/markdown/index.ts similarity index 98% rename from libraries/md-compiler/src/markdown/index.ts rename to sdk/src/md-compiler/markdown/index.ts index 081c0899..3363192c 100644 --- a/libraries/md-compiler/src/markdown/index.ts +++ b/sdk/src/md-compiler/markdown/index.ts @@ -1,7 +1,7 @@ import type {Root, RootContent} from 'mdast' import * as YAML from 'yaml' -import {parseMdx} from '@/compiler' +import {parseMdx} from '@/md-compiler/compiler' import {getNapiMdCompilerBinding} from '../native-binding' export interface ParsedMarkdown> { diff --git a/libraries/md-compiler/src/markdown/markdown.test.ts b/sdk/src/md-compiler/markdown/markdown.test.ts similarity index 100% rename from libraries/md-compiler/src/markdown/markdown.test.ts rename to sdk/src/md-compiler/markdown/markdown.test.ts diff --git a/libraries/md-compiler/src/markdown/native-binding.test.ts b/sdk/src/md-compiler/markdown/native-binding.test.ts similarity index 82% rename from libraries/md-compiler/src/markdown/native-binding.test.ts rename to sdk/src/md-compiler/markdown/native-binding.test.ts index 31bc8a8e..1a4f6426 100644 --- a/libraries/md-compiler/src/markdown/native-binding.test.ts +++ b/sdk/src/md-compiler/markdown/native-binding.test.ts @@ -7,11 +7,11 @@ interface PlatformBinding { } const PLATFORM_BINDINGS: Record = { - 'win32-x64': {local: 'napi-md-compiler.win32-x64-msvc', suffix: 'win32-x64-msvc'}, - 'linux-x64': {local: 'napi-md-compiler.linux-x64-gnu', suffix: 'linux-x64-gnu'}, - 'linux-arm64': {local: 'napi-md-compiler.linux-arm64-gnu', suffix: 'linux-arm64-gnu'}, - 'darwin-arm64': {local: 'napi-md-compiler.darwin-arm64', suffix: 'darwin-arm64'}, - 'darwin-x64': {local: 'napi-md-compiler.darwin-x64', suffix: 'darwin-x64'} + 'win32-x64': {local: 'napi-memory-sync-cli.win32-x64-msvc', suffix: 'win32-x64-msvc'}, + 'linux-x64': {local: 'napi-memory-sync-cli.linux-x64-gnu', suffix: 'linux-x64-gnu'}, + 'linux-arm64': {local: 'napi-memory-sync-cli.linux-arm64-gnu', suffix: 'linux-arm64-gnu'}, + 'darwin-arm64': {local: 'napi-memory-sync-cli.darwin-arm64', suffix: 'darwin-arm64'}, + 'darwin-x64': {local: 'napi-memory-sync-cli.darwin-x64', suffix: 'darwin-x64'} } function getPlatformBinding(): PlatformBinding | undefined { diff --git a/libraries/md-compiler/src/mdx-to-md.test.ts b/sdk/src/md-compiler/mdx-to-md.test.ts similarity index 100% rename from libraries/md-compiler/src/mdx-to-md.test.ts rename to sdk/src/md-compiler/mdx-to-md.test.ts diff --git a/libraries/md-compiler/src/mdx-to-md.ts b/sdk/src/md-compiler/mdx-to-md.ts similarity index 97% rename from libraries/md-compiler/src/mdx-to-md.ts rename to sdk/src/md-compiler/mdx-to-md.ts index fbc5ca24..0c7ede3d 100644 --- a/libraries/md-compiler/src/mdx-to-md.ts +++ b/sdk/src/md-compiler/mdx-to-md.ts @@ -1,4 +1,4 @@ -import type {ExportMetadata, MdxToMdOptions, MdxToMdResult, MetadataSource} from '@/compiler' +import type {ExportMetadata, MdxToMdOptions, MdxToMdResult, MetadataSource} from '@/md-compiler/compiler' import {getNapiMdCompilerBinding} from './native-binding' type NativeCompileMetadata = ExportMetadata & { diff --git a/libraries/md-compiler/src/native-binding.ts b/sdk/src/md-compiler/native-binding.ts similarity index 92% rename from libraries/md-compiler/src/native-binding.ts rename to sdk/src/md-compiler/native-binding.ts index c4ae9ad3..973a0c03 100644 --- a/libraries/md-compiler/src/native-binding.ts +++ b/sdk/src/md-compiler/native-binding.ts @@ -1,5 +1,5 @@ import process from 'node:process' -import {createNativeBindingLoader} from '../../../sdk/src/core/native-binding-loader' +import {createNativeBindingLoader} from '@/core/native-binding-loader' export interface NativeParseMarkdownResult { readonly yamlFrontMatterJson?: string @@ -34,8 +34,8 @@ function isNapiMdCompilerModule(value: unknown): value is NapiMdCompilerModule { } const loadNativeBinding = createNativeBindingLoader({ - packageName: '@truenine/md-compiler', - binaryName: 'napi-md-compiler', + packageName: '@truenine/memory-sync-sdk', + binaryName: 'napi-memory-sync-cli', bindingValidator: isNapiMdCompilerModule, cliExportName: 'mdCompiler' }) diff --git a/libraries/md-compiler/src/toml.test.ts b/sdk/src/md-compiler/toml.test.ts similarity index 100% rename from libraries/md-compiler/src/toml.test.ts rename to sdk/src/md-compiler/toml.test.ts diff --git a/libraries/md-compiler/src/toml.ts b/sdk/src/md-compiler/toml.ts similarity index 100% rename from libraries/md-compiler/src/toml.ts rename to sdk/src/md-compiler/toml.ts diff --git a/libraries/logger/src/lib.rs b/sdk/src/native_logger.rs similarity index 99% rename from libraries/logger/src/lib.rs rename to sdk/src/native_logger.rs index 64720318..b30d0e19 100644 --- a/libraries/logger/src/lib.rs +++ b/sdk/src/native_logger.rs @@ -902,6 +902,16 @@ macro_rules! log_debug { }; } +#[macro_export] +macro_rules! log_trace { + ($logger:expr, $msg:expr) => { + $logger.trace(serde_json::Value::String($msg.to_string()), None) + }; + ($logger:expr, $msg:expr, $meta:expr) => { + $logger.trace(serde_json::Value::String($msg.to_string()), Some($meta)) + }; +} + // =========================================================================== // NAPI binding layer (only compiled with --features napi) // =========================================================================== diff --git a/libraries/md-compiler/src/expression_eval.rs b/sdk/src/native_md_compiler/expression_eval.rs similarity index 100% rename from libraries/md-compiler/src/expression_eval.rs rename to sdk/src/native_md_compiler/expression_eval.rs diff --git a/libraries/md-compiler/src/lib.rs b/sdk/src/native_md_compiler/lib.rs similarity index 99% rename from libraries/md-compiler/src/lib.rs rename to sdk/src/native_md_compiler/lib.rs index c49ea6fc..7028f9d2 100644 --- a/libraries/md-compiler/src/lib.rs +++ b/sdk/src/native_md_compiler/lib.rs @@ -15,7 +15,8 @@ pub mod transformer; pub use expression_eval::EvaluationScope; pub use mdx_to_md::{ - ExportMetadata, MdxGlobalScope, MdxToMdOptions, MdxToMdResult, mdx_to_md, mdx_to_md_with_metadata, + ExportMetadata, MdxGlobalScope, MdxToMdOptions, MdxToMdResult, MetadataSource, mdx_to_md, + mdx_to_md_with_metadata, }; pub use parser::parse_mdx; pub use serializer::serialize; diff --git a/libraries/md-compiler/src/mdx_to_md.rs b/sdk/src/native_md_compiler/mdx_to_md.rs similarity index 99% rename from libraries/md-compiler/src/mdx_to_md.rs rename to sdk/src/native_md_compiler/mdx_to_md.rs index 5c671e30..8b2e5ed5 100644 --- a/libraries/md-compiler/src/mdx_to_md.rs +++ b/sdk/src/native_md_compiler/mdx_to_md.rs @@ -7,10 +7,10 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; -use crate::expression_eval::EvaluationScope; -use crate::parser::parse_mdx; -use crate::serializer::serialize; -use crate::transformer::{ProcessingContext, transform_ast}; +use super::expression_eval::EvaluationScope; +use super::parser::parse_mdx; +use super::serializer::serialize; +use super::transformer::{ProcessingContext, transform_ast}; /// Global scope for MDX compilation (os, env, profile, code style, tool info). #[derive(Debug, Clone, Default, Serialize, Deserialize)] diff --git a/libraries/md-compiler/src/parser.rs b/sdk/src/native_md_compiler/parser.rs similarity index 100% rename from libraries/md-compiler/src/parser.rs rename to sdk/src/native_md_compiler/parser.rs diff --git a/libraries/md-compiler/src/serializer.rs b/sdk/src/native_md_compiler/serializer.rs similarity index 99% rename from libraries/md-compiler/src/serializer.rs rename to sdk/src/native_md_compiler/serializer.rs index 203b7e04..18b6865b 100644 --- a/libraries/md-compiler/src/serializer.rs +++ b/sdk/src/native_md_compiler/serializer.rs @@ -422,7 +422,7 @@ fn collect_node_plain_text(node: &Node, out: &mut String) { #[cfg(test)] mod tests { use super::*; - use crate::parser::parse_mdx; + use super::super::parser::parse_mdx; fn roundtrip(input: &str) -> String { let ast = parse_mdx(input).unwrap(); diff --git a/libraries/md-compiler/src/toml_artifact.rs b/sdk/src/native_md_compiler/toml_artifact.rs similarity index 100% rename from libraries/md-compiler/src/toml_artifact.rs rename to sdk/src/native_md_compiler/toml_artifact.rs diff --git a/libraries/md-compiler/src/transformer.rs b/sdk/src/native_md_compiler/transformer.rs similarity index 99% rename from libraries/md-compiler/src/transformer.rs rename to sdk/src/native_md_compiler/transformer.rs index 5594c8cc..ece2e85f 100644 --- a/libraries/md-compiler/src/transformer.rs +++ b/sdk/src/native_md_compiler/transformer.rs @@ -3,8 +3,8 @@ //! Walks the mdast AST, evaluating expressions, expanding components, //! and converting JSX elements to Markdown equivalents. -use crate::expression_eval::{EvaluationScope, evaluate_expression}; -use crate::serializer::serialize; +use super::expression_eval::{EvaluationScope, evaluate_expression}; +use super::serializer::serialize; use markdown::mdast::*; use serde_json::{Number, Value}; use std::collections::HashMap; @@ -1140,8 +1140,8 @@ fn get_children(node: &Node) -> Option<&Vec> { #[cfg(test)] mod tests { use super::*; - use crate::parser::parse_mdx; - use crate::serializer::serialize; + use super::super::parser::parse_mdx; + use super::super::serializer::serialize; use serde_json::json; fn make_scope() -> EvaluationScope { diff --git a/libraries/script-runtime/src/lib.rs b/sdk/src/native_script_runtime.rs similarity index 100% rename from libraries/script-runtime/src/lib.rs rename to sdk/src/native_script_runtime.rs diff --git a/sdk/tsconfig.eslint.json b/sdk/tsconfig.eslint.json index 0d1598a0..27e4b332 100644 --- a/sdk/tsconfig.eslint.json +++ b/sdk/tsconfig.eslint.json @@ -7,11 +7,6 @@ "@/*": ["./src/*"], "@truenine/desk-paths": ["./src/core/desk-paths.ts"], "@truenine/desk-paths/*": ["./src/core/desk-paths/*"], - "@truenine/logger": ["./src/libraries/logger.ts"], - "@truenine/md-compiler": ["../libraries/md-compiler/src/index.ts"], - "@truenine/md-compiler/errors": ["../libraries/md-compiler/src/errors/index.ts"], - "@truenine/md-compiler/globals": ["../libraries/md-compiler/src/globals/index.ts"], - "@truenine/md-compiler/markdown": ["../libraries/md-compiler/src/markdown/index.ts"], "@truenine/plugin-output-shared": ["./src/plugins/plugin-output-shared/index.ts"], "@truenine/plugin-output-shared/*": ["./src/plugins/plugin-output-shared/*"], "@truenine/plugin-input-shared": ["./src/plugins/plugin-input-shared/index.ts"], @@ -34,8 +29,7 @@ "@truenine/plugin-vscode": ["./src/plugins/plugin-vscode.ts"], "@truenine/plugin-warp-ide": ["./src/plugins/WarpIDEOutputPlugin.ts"], "@truenine/plugin-windsurf": ["./src/plugins/plugin-windsurf.ts"], - "@truenine/plugin-zed": ["./src/plugins/plugin-zed.ts"], - "@truenine/script-runtime": ["./src/libraries/script-runtime/index.ts"] + "@truenine/plugin-zed": ["./src/plugins/plugin-zed.ts"] }, "noEmit": true, "skipLibCheck": true diff --git a/sdk/tsdown.config.ts b/sdk/tsdown.config.ts index 92b6b666..4b02f3fe 100644 --- a/sdk/tsdown.config.ts +++ b/sdk/tsdown.config.ts @@ -10,11 +10,8 @@ const pluginAliases: Record = { } const alwaysBundleDeps = [ - '@truenine/logger', - '@truenine/script-runtime', 'fast-glob', 'jiti', - '@truenine/md-compiler', ...Object.keys(pluginAliases) ] @@ -41,5 +38,22 @@ export default defineConfig([ __CLI_PACKAGE_NAME__: JSON.stringify(pkg.name), __KIRO_GLOBAL_POWERS_REGISTRY__: kiroGlobalPowersRegistry } + }, + { + entry: ['./src/libraries/script-runtime/resolve-proxy-worker.ts'], + platform: 'node', + sourcemap: false, + unbundle: false, + deps: { + neverBundle: ['jiti'], + onlyBundle: false + }, + alias: { + '@': resolve('src'), + ...pluginAliases + }, + format: ['esm'], + minify: true, + dts: false } ]) diff --git a/sdk/vite.config.ts b/sdk/vite.config.ts index d6bc518a..b738ee9f 100644 --- a/sdk/vite.config.ts +++ b/sdk/vite.config.ts @@ -5,12 +5,6 @@ import {defineConfig} from 'vite' const pkg = JSON.parse(readFileSync('./package.json', 'utf8')) as {version: string, name: string} const kiroGlobalPowersRegistry = '{"version":"1.0.0","powers":{},"repoSources":{}}' -const workspacePackageAliases: Record = { - '@truenine/md-compiler/errors': resolve('../libraries/md-compiler/dist/errors/index.mjs'), - '@truenine/md-compiler/globals': resolve('../libraries/md-compiler/dist/globals/index.mjs'), - '@truenine/md-compiler/markdown': resolve('../libraries/md-compiler/dist/markdown/index.mjs'), - '@truenine/md-compiler': resolve('../libraries/md-compiler/dist/index.mjs') -} const pluginAliases: Record = { '@truenine/plugin-warp-ide': resolve('src/plugins/WarpIDEOutputPlugin.ts') @@ -20,7 +14,6 @@ export default defineConfig({ resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)), - ...workspacePackageAliases, ...pluginAliases } }, From cf8031ad905bb78992f79072be75e80835c11ab3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=97=A5=E5=A4=A9?= Date: Sun, 12 Apr 2026 20:26:46 +0800 Subject: [PATCH 3/3] Enhance SDK core functionality with integration test coverage and diagnostics - Add cli-integration-test artifact and container modules - Add runtime test coverage in cli module - Add adaptor-core improvements for AbstractOutputAdaptor, GlobalScopeCollector, LocalizedPromptReader - Add PromptArtifactCache, PromptCompilerDiagnostics, and PromptTypes improvements - Update native bindings: prompt_artifact.rs, native_md_compiler transformer and serializer - Add diagnostic_helpers and update lib exports --- cli-integration-test/src/artifacts.ts | 30 +++--- cli-integration-test/src/container.ts | 8 +- cli/src/cli-runtime.test.ts | 17 ++- sdk/package.json | 2 +- .../adaptor-core/AbstractOutputAdaptor.ts | 4 +- .../adaptor-core/GlobalScopeCollector.ts | 2 +- .../adaptor-core/LocalizedPromptReader.ts | 2 +- .../adaptor-core/PromptArtifactCache.ts | 2 +- .../PromptCompilerDiagnostics.test.ts | 2 +- sdk/src/adaptors/adaptor-core/PromptTypes.ts | 2 +- sdk/src/adaptors/adaptor-core/plugin.ts | 2 +- sdk/src/core/input_plugins/prompt_artifact.rs | 2 +- sdk/src/diagnostic_helpers.rs | 2 +- sdk/src/index.ts | 100 +++++++++--------- sdk/src/inputs/AbstractInputCapability.ts | 4 +- sdk/src/inputs/runtime.ts | 2 +- sdk/src/internal/prompts-legacy.ts | 2 +- sdk/src/lib.rs | 4 +- sdk/src/md-compiler/index.ts | 18 ++-- sdk/src/native_md_compiler/serializer.rs | 2 +- sdk/src/native_md_compiler/transformer.rs | 2 +- 21 files changed, 111 insertions(+), 100 deletions(-) diff --git a/cli-integration-test/src/artifacts.ts b/cli-integration-test/src/artifacts.ts index 5c74fa3e..10218c55 100644 --- a/cli-integration-test/src/artifacts.ts +++ b/cli-integration-test/src/artifacts.ts @@ -6,16 +6,16 @@ import {fileURLToPath} from 'node:url' const REPO_ROOT = fileURLToPath(new URL('../../', import.meta.url)) const CLI_DIR = path.join(REPO_ROOT, 'cli') -const SCRIPT_RUNTIME_DIR = path.join(REPO_ROOT, 'libraries', 'script-runtime') +const SDK_DIR = path.join(REPO_ROOT, 'sdk') const CLI_LINUX_PACKAGE_DIR = path.join(CLI_DIR, 'npm', 'linux-x64-gnu') -const EXPECTED_LINUX_NODE_FILES = 4 +const REQUIRED_LINUX_NODE_FILE = 'napi-memory-sync-cli.linux-x64-gnu.node' const MAX_BUFFER = 16 * 1024 * 1024 export interface CliIntegrationArtifacts { readonly tempDir: string readonly cliTarballPath: string readonly linuxTarballPath: string - readonly scriptRuntimeTarballPath: string + readonly sdkTarballPath: string readonly latestPnpmVersion: string } @@ -93,20 +93,20 @@ function packWorkspacePackage(packageDir: string, targetDir: string): string { } function ensureLinuxPlatformPackageReady(): void { - const nodeFiles = existsSync(CLI_LINUX_PACKAGE_DIR) - ? readdirSync(CLI_LINUX_PACKAGE_DIR).filter(fileName => fileName.endsWith('.node')) - : [] + const hasRequiredNodeFile = existsSync(CLI_LINUX_PACKAGE_DIR) + && readdirSync(CLI_LINUX_PACKAGE_DIR).includes(REQUIRED_LINUX_NODE_FILE) - if (nodeFiles.length >= EXPECTED_LINUX_NODE_FILES) return + if (hasRequiredNodeFile) return runCommand('pnpm', ['-C', CLI_DIR, 'run', 'build:napi:copy']) - const copiedNodeFiles = readdirSync(CLI_LINUX_PACKAGE_DIR) - .filter(fileName => fileName.endsWith('.node')) + const copiedNodeFiles = existsSync(CLI_LINUX_PACKAGE_DIR) + ? readdirSync(CLI_LINUX_PACKAGE_DIR).filter(fileName => fileName.endsWith('.node')) + : [] - if (copiedNodeFiles.length < EXPECTED_LINUX_NODE_FILES) { + if (!copiedNodeFiles.includes(REQUIRED_LINUX_NODE_FILE)) { throw new Error( - `Expected ${EXPECTED_LINUX_NODE_FILES} Linux x64 NAPI artifacts in "${CLI_LINUX_PACKAGE_DIR}", found ${copiedNodeFiles.length}.` + `Expected the Linux x64 NAPI artifact "${REQUIRED_LINUX_NODE_FILE}" in "${CLI_LINUX_PACKAGE_DIR}", found ${copiedNodeFiles.length} .node file(s): ${copiedNodeFiles.join(', ') || '(none)'}.` ) } } @@ -133,9 +133,9 @@ export function prepareCliIntegrationArtifacts(): CliIntegrationArtifacts { CLI_LINUX_PACKAGE_DIR, path.join(tempDir, 'cli-linux-x64') ) - const scriptRuntimeTarballPath = packWorkspacePackage( - SCRIPT_RUNTIME_DIR, - path.join(tempDir, 'script-runtime') + const sdkTarballPath = packWorkspacePackage( + SDK_DIR, + path.join(tempDir, 'sdk') ) const latestPnpmVersion = resolveLatestPackageVersion('pnpm') @@ -143,7 +143,7 @@ export function prepareCliIntegrationArtifacts(): CliIntegrationArtifacts { tempDir, cliTarballPath, linuxTarballPath, - scriptRuntimeTarballPath, + sdkTarballPath, latestPnpmVersion } diff --git a/cli-integration-test/src/container.ts b/cli-integration-test/src/container.ts index d1be988a..a646fe93 100644 --- a/cli-integration-test/src/container.ts +++ b/cli-integration-test/src/container.ts @@ -243,22 +243,22 @@ export class PreparedCliIntegrationContainer { this.copyPathToContainer(artifacts.cliTarballPath, containerTarballPath(artifacts.cliTarballPath)) this.copyPathToContainer(artifacts.linuxTarballPath, containerTarballPath(artifacts.linuxTarballPath)) this.copyPathToContainer( - artifacts.scriptRuntimeTarballPath, - containerTarballPath(artifacts.scriptRuntimeTarballPath) + artifacts.sdkTarballPath, + containerTarballPath(artifacts.sdkTarballPath) ) } bootstrapLatestPnpmAndInstallCli(artifacts: CliIntegrationArtifacts): void { const cliTarball = containerTarballPath(artifacts.cliTarballPath) const linuxTarball = containerTarballPath(artifacts.linuxTarballPath) - const scriptRuntimeTarball = containerTarballPath(artifacts.scriptRuntimeTarballPath) + const sdkTarball = containerTarballPath(artifacts.sdkTarballPath) this.assertExecSuccess( [ 'corepack enable', `corepack prepare pnpm@${quoteShell(artifacts.latestPnpmVersion)} --activate`, 'pnpm --version', - `pnpm add -g ${quoteShell(cliTarball)} ${quoteShell(linuxTarball)} ${quoteShell(scriptRuntimeTarball)}`, + `pnpm add -g ${quoteShell(cliTarball)} ${quoteShell(linuxTarball)} ${quoteShell(sdkTarball)}`, buildPinnedGlobalCliPlatformLinkScript(), 'command -v tnmsc >/dev/null' ].join(' && ') diff --git a/cli/src/cli-runtime.test.ts b/cli/src/cli-runtime.test.ts index 93d5438f..fa9519c1 100644 --- a/cli/src/cli-runtime.test.ts +++ b/cli/src/cli-runtime.test.ts @@ -1,13 +1,23 @@ import {afterEach, describe, expect, it, vi} from 'vitest' -const {cleanMock, dryRunMock, installMock, listAdaptorsMock} = vi.hoisted(() => ({ +const { + cleanMock, + dryRunMock, + flushOutputMock, + installMock, + listAdaptorsMock, + setGlobalLogLevelMock +} = vi.hoisted(() => ({ cleanMock: vi.fn(), dryRunMock: vi.fn(), + flushOutputMock: vi.fn(), installMock: vi.fn(), - listAdaptorsMock: vi.fn() + listAdaptorsMock: vi.fn(), + setGlobalLogLevelMock: vi.fn() })) vi.mock('@truenine/memory-sync-sdk', () => ({ + flushOutput: flushOutputMock, getMemorySyncSdkBinding() { return { install: installMock, @@ -15,7 +25,8 @@ vi.mock('@truenine/memory-sync-sdk', () => ({ clean: cleanMock, listAdaptors: listAdaptorsMock } - } + }, + setGlobalLogLevel: setGlobalLogLevelMock })) afterEach(() => { diff --git a/sdk/package.json b/sdk/package.json index b02bab07..7e2e13e5 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -67,9 +67,9 @@ }, "devDependencies": { "@clack/prompts": "catalog:", - "@types/fs-extra": "catalog:", "@types/estree": "catalog:", "@types/estree-jsx": "catalog:", + "@types/fs-extra": "catalog:", "@types/mdast": "catalog:", "@types/picomatch": "catalog:", "@vitest/coverage-v8": "catalog:", diff --git a/sdk/src/adaptors/adaptor-core/AbstractOutputAdaptor.ts b/sdk/src/adaptors/adaptor-core/AbstractOutputAdaptor.ts index 85882056..a8027ed0 100644 --- a/sdk/src/adaptors/adaptor-core/AbstractOutputAdaptor.ts +++ b/sdk/src/adaptors/adaptor-core/AbstractOutputAdaptor.ts @@ -1,4 +1,3 @@ -import type {BuildPromptTomlArtifactOptions} from '@/md-compiler' import type {ToolPresetName} from './GlobalScopeCollector' import type {RegistryWriter} from './RegistryWriter' import type { @@ -32,13 +31,14 @@ import type { SubAgentYAMLFrontMatter, WslMirrorFileDeclaration } from './types' +import type {BuildPromptTomlArtifactOptions} from '@/md-compiler' import {Buffer} from 'node:buffer' import * as path from 'node:path' import process from 'node:process' +import {buildConfigDiagnostic, diagnosticLines} from '@/diagnostics' import {buildPromptTomlArtifact} from '@/md-compiler' import {buildMarkdownWithFrontMatter, buildMarkdownWithRawFrontMatter} from '@/md-compiler/markdown' -import {buildConfigDiagnostic, diagnosticLines} from '@/diagnostics' import {getEffectiveHomeDir} from '@/runtime-environment' import {AbstractAdaptor} from './AbstractAdaptor' import {AdaptorKind, FilePathKind} from './enums' diff --git a/sdk/src/adaptors/adaptor-core/GlobalScopeCollector.ts b/sdk/src/adaptors/adaptor-core/GlobalScopeCollector.ts index d6573be3..5b7e6cb0 100644 --- a/sdk/src/adaptors/adaptor-core/GlobalScopeCollector.ts +++ b/sdk/src/adaptors/adaptor-core/GlobalScopeCollector.ts @@ -1,6 +1,6 @@ +import type {AdaptorOptions, UserConfigFile} from './types' import type {EvaluationScope} from '@/md-compiler' import type {CodeStylePreferences, EnvironmentContext, MdComponent, MdxGlobalScope, OsInfo, ToolReferences, UserProfile} from '@/md-compiler/globals' // Collects and manages global scope variables for MDX expression evaluation. -import type {AdaptorOptions, UserConfigFile} from './types' import * as os from 'node:os' import process from 'node:process' import {OsKind, ShellKind, ToolPresets} from '@/md-compiler/globals' diff --git a/sdk/src/adaptors/adaptor-core/LocalizedPromptReader.ts b/sdk/src/adaptors/adaptor-core/LocalizedPromptReader.ts index 45c5d822..7f5ac3c0 100644 --- a/sdk/src/adaptors/adaptor-core/LocalizedPromptReader.ts +++ b/sdk/src/adaptors/adaptor-core/LocalizedPromptReader.ts @@ -1,4 +1,3 @@ -import type {MdxGlobalScope} from '@/md-compiler/globals' import type {PromptCompilerDiagnosticContext} from './PromptCompilerDiagnostics' import type { DirectoryReadResult, @@ -13,6 +12,7 @@ import type { PromptKind, ReadError } from './types' +import type {MdxGlobalScope} from '@/md-compiler/globals' import { buildDiagnostic, buildFileOperationDiagnostic, diff --git a/sdk/src/adaptors/adaptor-core/PromptArtifactCache.ts b/sdk/src/adaptors/adaptor-core/PromptArtifactCache.ts index c283d82e..8e125054 100644 --- a/sdk/src/adaptors/adaptor-core/PromptArtifactCache.ts +++ b/sdk/src/adaptors/adaptor-core/PromptArtifactCache.ts @@ -2,9 +2,9 @@ import type {MdxGlobalScope} from '@/md-compiler/globals' import type {ParsedMarkdown} from '@/md-compiler/markdown' import * as fs from 'node:fs' import * as path from 'node:path' +import JSON5 from 'json5' import {mdxToMd} from '@/md-compiler' import {parseMarkdown} from '@/md-compiler/markdown' -import JSON5 from 'json5' export interface PromptArtifact { readonly rawMdx: string diff --git a/sdk/src/adaptors/adaptor-core/PromptCompilerDiagnostics.test.ts b/sdk/src/adaptors/adaptor-core/PromptCompilerDiagnostics.test.ts index 872543d0..2eceadec 100644 --- a/sdk/src/adaptors/adaptor-core/PromptCompilerDiagnostics.test.ts +++ b/sdk/src/adaptors/adaptor-core/PromptCompilerDiagnostics.test.ts @@ -1,6 +1,6 @@ import * as path from 'node:path' -import {UndefinedNamespaceError} from '@/md-compiler/errors' import {describe, expect, it} from 'vitest' +import {UndefinedNamespaceError} from '@/md-compiler/errors' import { formatPromptCompilerDiagnostic, resolveSourcePathForDistFile diff --git a/sdk/src/adaptors/adaptor-core/PromptTypes.ts b/sdk/src/adaptors/adaptor-core/PromptTypes.ts index 7ac4ec8c..18c83eb4 100644 --- a/sdk/src/adaptors/adaptor-core/PromptTypes.ts +++ b/sdk/src/adaptors/adaptor-core/PromptTypes.ts @@ -1,6 +1,6 @@ -import type {Root, RootContent} from '@/md-compiler' import type {ClaudeCodeCLISubAgentColors, CodingAgentTools, FilePathKind, NamingCaseKind, PromptKind, RuleScope} from './enums' import type {GlobalConfigDirectory} from './OutputTypes' +import type {Root, RootContent} from '@/md-compiler' /** Common directory representation */ export interface Path { diff --git a/sdk/src/adaptors/adaptor-core/plugin.ts b/sdk/src/adaptors/adaptor-core/plugin.ts index 11547fa6..af484c59 100644 --- a/sdk/src/adaptors/adaptor-core/plugin.ts +++ b/sdk/src/adaptors/adaptor-core/plugin.ts @@ -1,4 +1,3 @@ -import type {MdxGlobalScope} from '@/md-compiler/globals' import type { AindexConfig, CodeStylesOptions, @@ -13,6 +12,7 @@ import type {InputCollectedContext, OutputCollectedContext} from './InputTypes' import type {NativeDeskPathsBinding} from '@/core/desk-paths-types' import type {ExecutionPlan} from '@/execution-plan' import type {ILogger} from '@/libraries/logger' +import type {MdxGlobalScope} from '@/md-compiler/globals' import type {RuntimeCommand} from '@/runtime-command' import {Buffer} from 'node:buffer' import * as fs from 'node:fs' diff --git a/sdk/src/core/input_plugins/prompt_artifact.rs b/sdk/src/core/input_plugins/prompt_artifact.rs index 98e8a3fb..e385cfcb 100644 --- a/sdk/src/core/input_plugins/prompt_artifact.rs +++ b/sdk/src/core/input_plugins/prompt_artifact.rs @@ -1,5 +1,5 @@ -use serde_json::Value; use crate::md_compiler::{MdxGlobalScope, MdxToMdOptions, mdx_to_md_with_metadata}; +use serde_json::Value; #[derive(Debug, Clone)] pub struct PromptArtifact { diff --git a/sdk/src/diagnostic_helpers.rs b/sdk/src/diagnostic_helpers.rs index 1783c0e6..a002d5ee 100644 --- a/sdk/src/diagnostic_helpers.rs +++ b/sdk/src/diagnostic_helpers.rs @@ -1,5 +1,5 @@ -use serde_json::{Map, Value}; use crate::logger::LoggerDiagnosticInput; +use serde_json::{Map, Value}; pub(crate) fn line(value: impl Into) -> Vec { vec![value.into()] diff --git a/sdk/src/index.ts b/sdk/src/index.ts index 3e0b9880..4b14d156 100644 --- a/sdk/src/index.ts +++ b/sdk/src/index.ts @@ -181,35 +181,29 @@ export type { LoggerDiagnosticRecord, LogLevel } from './libraries/logger' +export { + defineProxy, + getProxyModuleConfig, + loadProxyModule, + resolvePublicPath, + resolvePublicPathUnchecked, + validatePublicPath +} from './libraries/script-runtime' +export type { + ProxyCommand, + ProxyContext, + ProxyDefinition, + ProxyMatcherConfig, + ProxyModule, + ProxyModuleConfig, + ProxyRouteHandler, + ValidatePublicPathOptions +} from './libraries/script-runtime' export { buildPromptTomlArtifact, buildTomlDocument, mdxToMd } from './md-compiler' -export { - buildFrontMatter, - buildMarkdownWithFrontMatter, - buildMarkdownWithRawFrontMatter, - buildRawFrontMatter, - doubleQuoted, - parseMarkdown, - transformMdxReferencesToMd, - wrapRawFrontMatter -} from './md-compiler/markdown' -export { - CompilerDiagnosticError, - ExportParseError, - ScopeError, - UndefinedNamespaceError, - UndefinedVariableError, - createCompilerDiagnostic, - formatCompilerDiagnostic -} from './md-compiler/errors' -export { - OsKind, - ShellKind, - ToolPresets -} from './md-compiler/globals' export type { BuildPromptTomlArtifactOptions, BuildTomlDocumentOptions, @@ -217,15 +211,36 @@ export type { ExportMetadata, MdxFlowExpression, MdxGlobalScope, + MdxjsEsm, MdxJsxFlowElement, MdxJsxTextElement, MdxTextExpression, MdxToMdOptions, MdxToMdResult, - MdxjsEsm, Root, RootContent } from './md-compiler' +export { + CompilerDiagnosticError, + createCompilerDiagnostic, + ExportParseError, + formatCompilerDiagnostic, + ScopeError, + UndefinedNamespaceError, + UndefinedVariableError +} from './md-compiler/errors' +export type { + CompilerDiagnostic, + CompilerDiagnosticContext, + CompilerDiagnosticPoint, + CompilerDiagnosticPosition, + FormatCompilerDiagnosticOptions +} from './md-compiler/errors' +export { + OsKind, + ShellKind, + ToolPresets +} from './md-compiler/globals' export type { CodeStylePreferences, EnvironmentContext, @@ -234,35 +249,20 @@ export type { ToolReferences, UserProfile } from './md-compiler/globals' -export type { - CompilerDiagnostic, - CompilerDiagnosticContext, - CompilerDiagnosticPoint, - CompilerDiagnosticPosition, - FormatCompilerDiagnosticOptions -} from './md-compiler/errors' +export { + buildFrontMatter, + buildMarkdownWithFrontMatter, + buildMarkdownWithRawFrontMatter, + buildRawFrontMatter, + doubleQuoted, + parseMarkdown, + transformMdxReferencesToMd, + wrapRawFrontMatter +} from './md-compiler/markdown' export type { BuildMarkdownOptions, ParsedMarkdown } from './md-compiler/markdown' -export { - defineProxy, - getProxyModuleConfig, - loadProxyModule, - resolvePublicPath, - resolvePublicPathUnchecked, - validatePublicPath -} from './libraries/script-runtime' -export type { - ProxyCommand, - ProxyContext, - ProxyDefinition, - ProxyMatcherConfig, - ProxyModule, - ProxyModuleConfig, - ProxyRouteHandler, - ValidatePublicPathOptions -} from './libraries/script-runtime' export type { ListPromptsOptions, ManagedPromptKind, diff --git a/sdk/src/inputs/AbstractInputCapability.ts b/sdk/src/inputs/AbstractInputCapability.ts index b600179c..0d2c4a23 100644 --- a/sdk/src/inputs/AbstractInputCapability.ts +++ b/sdk/src/inputs/AbstractInputCapability.ts @@ -1,4 +1,3 @@ -import type {ParsedMarkdown} from '@/md-compiler/markdown' import type { AdaptorOptions, AdaptorScopeRegistration, @@ -12,13 +11,14 @@ import type { ResolvedBasePaths, YAMLFrontMatter } from '@/adaptors/adaptor-core' +import type {ParsedMarkdown} from '@/md-compiler/markdown' import {spawn} from 'node:child_process' import * as path from 'node:path' -import {parseMarkdown} from '@/md-compiler/markdown' import {PathPlaceholders} from '@/adaptors/adaptor-core' import {buildDiagnostic, diagnosticLines} from '@/diagnostics' import {createLogger} from '@/libraries/logger' +import {parseMarkdown} from '@/md-compiler/markdown' import {logProtectedDeletionGuardError, ProtectedDeletionGuardError} from '@/ProtectedDeletionGuard' import {resolveUserPath} from '@/runtime-environment' diff --git a/sdk/src/inputs/runtime.ts b/sdk/src/inputs/runtime.ts index 0f5562f8..7e274600 100644 --- a/sdk/src/inputs/runtime.ts +++ b/sdk/src/inputs/runtime.ts @@ -1,5 +1,5 @@ -import type {MdxGlobalScope} from '@/md-compiler/globals' import type {AdaptorOptions, InputCapability, InputCapabilityContext, InputCollectedContext, UserConfigFile} from '@/adaptors/adaptor-core' +import type {MdxGlobalScope} from '@/md-compiler/globals' import type {RuntimeCommand} from '@/runtime-command' import * as fs from 'node:fs' diff --git a/sdk/src/internal/prompts-legacy.ts b/sdk/src/internal/prompts-legacy.ts index 890d6816..be33b6ff 100644 --- a/sdk/src/internal/prompts-legacy.ts +++ b/sdk/src/internal/prompts-legacy.ts @@ -16,13 +16,13 @@ import type {YAMLFrontMatter} from '@/adaptors/adaptor-core/PromptTypes' import * as fs from 'node:fs' import * as path from 'node:path' import process from 'node:process' -import {parseMarkdown} from '@/md-compiler/markdown' import glob from 'fast-glob' import { isAindexProjectSeriesName, resolveAindexProjectSeriesConfig, resolveAindexProjectSeriesConfigs } from '@/aindex-project-series' +import {parseMarkdown} from '@/md-compiler/markdown' import {PathPlaceholders} from '../adaptors/adaptor-core/constants' import {mergeConfigForRuntime, userConfigToAdaptorOptions} from '../config' import {getConfigLoader} from '../ConfigLoader' diff --git a/sdk/src/lib.rs b/sdk/src/lib.rs index d6696aa3..0d56c524 100644 --- a/sdk/src/lib.rs +++ b/sdk/src/lib.rs @@ -28,8 +28,8 @@ pub mod script_runtime { pub use md_compiler::{ BuildPromptTomlArtifactOptions, BuildTomlDocumentOptions, EvaluationScope, ExportMetadata, MdxGlobalScope, MdxToMdOptions, MdxToMdResult, MetadataSource, ProcessingContext, - build_prompt_toml_artifact, build_toml_document, mdx_to_md, mdx_to_md_with_metadata, - parse_mdx, serialize, + build_prompt_toml_artifact, build_toml_document, mdx_to_md, mdx_to_md_with_metadata, parse_mdx, + serialize, }; pub use prompts::{ ListPromptsOptions, ManagedPromptKind, PromptArtifactRecord, PromptArtifactState, diff --git a/sdk/src/md-compiler/index.ts b/sdk/src/md-compiler/index.ts index 547d7690..450cf8e1 100644 --- a/sdk/src/md-compiler/index.ts +++ b/sdk/src/md-compiler/index.ts @@ -14,6 +14,15 @@ export type { Root, RootContent } from './compiler/types' +export type { + CodeStylePreferences, + EnvironmentContext, + MdComponent, + MdxGlobalScope, + OsInfo, + ToolReferences, + UserProfile +} from './globals' export { mdxToMd } from './mdx-to-md' @@ -25,12 +34,3 @@ export type { BuildPromptTomlArtifactOptions, BuildTomlDocumentOptions } from './toml' -export type { - CodeStylePreferences, - EnvironmentContext, - MdComponent, - MdxGlobalScope, - OsInfo, - ToolReferences, - UserProfile -} from './globals' diff --git a/sdk/src/native_md_compiler/serializer.rs b/sdk/src/native_md_compiler/serializer.rs index 18b6865b..6be81666 100644 --- a/sdk/src/native_md_compiler/serializer.rs +++ b/sdk/src/native_md_compiler/serializer.rs @@ -421,8 +421,8 @@ fn collect_node_plain_text(node: &Node, out: &mut String) { #[cfg(test)] mod tests { - use super::*; use super::super::parser::parse_mdx; + use super::*; fn roundtrip(input: &str) -> String { let ast = parse_mdx(input).unwrap(); diff --git a/sdk/src/native_md_compiler/transformer.rs b/sdk/src/native_md_compiler/transformer.rs index ece2e85f..37a873d2 100644 --- a/sdk/src/native_md_compiler/transformer.rs +++ b/sdk/src/native_md_compiler/transformer.rs @@ -1139,9 +1139,9 @@ fn get_children(node: &Node) -> Option<&Vec> { #[cfg(test)] mod tests { - use super::*; use super::super::parser::parse_mdx; use super::super::serializer::serialize; + use super::*; use serde_json::json; fn make_scope() -> EvaluationScope {