diff --git a/.agents/README.md b/.agents/agents.readme.md similarity index 99% rename from .agents/README.md rename to .agents/agents.readme.md index 222a11e..b1e8342 100644 --- a/.agents/README.md +++ b/.agents/agents.readme.md @@ -8,7 +8,7 @@ This directory (`.agents/`) maintains modular configuration, skills, and guideli ``` .agents/ -├── README.md # This document: architecture & trigger policy +├── agents.readme.md # This document: architecture & trigger policy ├── skills.json # Declarative skill path and exclusion filters ├── skills/ # Project-level skills │ └── repo-gh/ # GitHub CLI & Git Markdown-First operations diff --git a/.agents/rules/cli-protocol.md b/.agents/rules/cli-protocol.md index a5fb1b6..15bf60d 100644 --- a/.agents/rules/cli-protocol.md +++ b/.agents/rules/cli-protocol.md @@ -13,7 +13,7 @@ When developing or refactoring CLI commands under `src/cli/`: - **Machine Channel (`stdout`)**: - Data commands **MUST** output pure, parseable JSON on `stdout`. - **NEVER** output human text, logs, spinners, progress banners, or update notices to `stdout`. The Agent Harness parses `stdout` directly into typed payloads. - - **Documented exceptions**: `seal-use --help` / `seal-use help ` (`src/cli/printer.ts`), `seal-use doctor guide` (`src/cli/commands/doctor.ts`), and `seal-use skill dump` (`src/cli/commands/skill.ts`) intentionally output Markdown documents on `stdout` because their output *is* the requested document payload (e.g. `seal-use skill dump > SKILL.md`). Never add new stdout-prose commands outside this list. + - **Documented exceptions**: `seal-use --help` / `seal-use help ` (`src/cli/output/printer.ts`), `seal-use doctor guide` (`src/cli/commands/doctor.ts`), and `seal-use skill dump` (`src/cli/commands/skill.ts`) intentionally output Markdown documents on `stdout` because their output *is* the requested document payload (e.g. `seal-use skill dump > SKILL.md`). Never add new stdout-prose commands outside this list. - **Diagnostics & Guidance Channel (`stderr`)**: - Use `stderr` for runtime logs, network probing status, self-healing notifications, and human tips. - Explicit **Next-Step Command Suggestions** MUST follow the format: @@ -27,7 +27,7 @@ When developing or refactoring CLI commands under `src/cli/`: - **Sub-70ms Local Execution**: - Read-only discovery commands (e.g. `seal-use version`, `seal-use doctor paths`, `seal-use corps list`) MUST return in under 70ms wall clock (Bun interpreter startup is ~7ms on its own, so this leaves ~60ms for the module graph). - - Achieved by keeping `src/cli/runner.ts` free of static command-module imports: dispatch branches load their handler with `await import("./commands/.js")` on demand, so `seal-use version` never loads the Excel/zip tool chain. + - Achieved by keeping `src/cli/run/runner.ts` free of static command-module imports: dispatch branches load their handler with `await import("./commands/.js")` on demand, so `seal-use version` never loads the Excel/zip tool chain. - Never trigger synchronous external HTTP requests during routine discovery or inspection invocations. Measured on the maintainer's machine (2026-09): version 45ms, help 41ms, corps list 41ms, bare `bun -e` 7ms. - **Stale-While-Revalidate (SWR) Pattern**: 1. Synchronously read local cache from `~/.config/seal-use/*.json` (<0.2ms). @@ -74,13 +74,13 @@ When developing or refactoring CLI commands under `src/cli/`: | `13` | **Config / Input Validation** | Well-formed command with an unusable value: missing `--corp` in stateless mode, unparseable enterprise JSON, missing required parameter (Chinese-language usage wording), Zod/schema validation failure | | `14` | **Safety Guard Block** | Target environment forbids the action: replay into a production tenant, regression matrix outside a test tenant. Requires a different target or an explicit override flag | -**Rule**: Never call `process.exit()` deep in domain functions. Throw structured errors (`usageError` → 2, `validationError` → 13, `safetyBlocked` → 14, `confirmationRequired` → 10) and let `src/cli/runner.ts` handle error classification, stream routing, and exit code assignment. Domain failures and quality gates stay at `1`. +**Rule**: Never call `process.exit()` deep in domain functions. Throw structured errors (`usageError` → 2, `validationError` → 13, `safetyBlocked` → 14, `confirmationRequired` → 10) and let `src/cli/run/runner.ts` handle error classification, stream routing, and exit code assignment. Domain failures and quality gates stay at `1`. --- ## 5. Argument Parsing Conventions -- Use helpers from `src/cli/parser.ts`: +- Use helpers from `src/cli/parse/parser.ts`: - `booleanOption(args.options.flag)` - `stringOption(args.options.param)` - `numberOption(args.options.limit)` diff --git a/.agents/rules/testing.md b/.agents/rules/testing.md index 49d7ade..c8156f1 100644 --- a/.agents/rules/testing.md +++ b/.agents/rules/testing.md @@ -13,8 +13,8 @@ When writing or modifying automated tests in `src/`: - **Runner**: Use `bun:test` primitives (`describe`, `test`, `it`, `expect`, `beforeEach`, `afterEach`). - **Colocation**: Place test files directly next to the code they cover using the `*.test.ts` naming convention: ```text - src/core/update-cache.ts - src/core/update-cache.test.ts + src/core/update/update-cache.ts + src/core/update/update-cache.test.ts ``` - Do not create isolated `tests/` directories unless testing full external integration fixtures. diff --git a/.githooks/pre-commit b/.githooks/pre-commit index e90c38e..8ddf0a5 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -130,4 +130,8 @@ if printf '%s\n' "$staged" | grep -qE "^skills/seal-use/(SKILL\.md|references/[^ bun run verify:skill-md || exit 1 fi +if printf '%s\n' "$staged" | grep -qiE "(^|/)readme"; then + bun run verify:readme-naming || exit 1 +fi + exit 0 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d80197b..fd9e88a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,6 +53,9 @@ jobs: - name: Embedded Skill Sync run: bun run verify:embedded-skill + - name: README Naming Checks + run: bun run verify:readme-naming + - name: Colocated Unit Tests run: bun test diff --git a/.gitignore b/.gitignore index a282911..48c8207 100644 --- a/.gitignore +++ b/.gitignore @@ -1,37 +1,61 @@ -node_modules/ +# --------------------------------------------------------------------------- +# OS & editor noise +# --------------------------------------------------------------------------- .DS_Store +._* +Thumbs.db +Desktop.ini +*.swp +.idea/ +.vscode/ +*.tsbuildinfo +# --------------------------------------------------------------------------- +# Dependencies +# --------------------------------------------------------------------------- +node_modules/ + +# --------------------------------------------------------------------------- # Build outputs -dist/bin/ +# --------------------------------------------------------------------------- +dist/ build/ +coverage/ -# Local runtime caches and system noise (regenerate at any time) +# --------------------------------------------------------------------------- +# Local caches and tool state (regenerate at any time) +# --------------------------------------------------------------------------- .cache/ .mimosa/ .apifox/ tmp/ +*.log -# Local runtime state (rule snapshots, bridge, reports) — never committed +# --------------------------------------------------------------------------- +# Local runtime state (never committed) +# --------------------------------------------------------------------------- .local/ /reports/ - -# WorkBuddy workspace data (memory logs, project state) — keep on disk, never commit .workbuddy/ -# Developer-only build-time credentials for compile-time injection — never committed -.env.langfuse +# --------------------------------------------------------------------------- +# Secrets and build-time credentials (never committed) +# --------------------------------------------------------------------------- .env .env.* !.env.example *.pem *.key -# Local drafts for repo-gh & AI Agents +# --------------------------------------------------------------------------- +# Local drafts, one-off harnesses, and review notes +# --------------------------------------------------------------------------- .drafts/* !.drafts/.gitkeep - -# ZCode session plan artifacts (workspace-local, never committed) -.zcode/plans/ - -# One-off export harnesses dropped in scripts/ while exporting scripts/export-*.ts +*.local.md + +# --------------------------------------------------------------------------- +# ZCode session artifacts +# --------------------------------------------------------------------------- +.zcode/plans/ diff --git a/AGENTS.md b/AGENTS.md index d44497a..1d5d02a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ This is a Bun + TypeScript toolkit for the `seal-use` CLI and a local stdio MCP The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares a skills-only plugin manifest and the agent skill lives under `skills/seal-use/`. The plugin ships no MCP surface; the local MCP runs from the CLI (`seal-use mcp`, or the `mcp-config` snippet for Cursor/Claude Desktop). The in-repo `.agents/skills/seal-use` symlink has been dropped; workspace and Codex skill loading use the global `~/.agents/skills/seal-use` copy installed by `seal-use skill install`. -Engineering toolchain, code generators, build pipelines, and governance gate scripts live under `scripts/`. Scripts under `scripts/` are offline harnesses, not application runtime code — never import them into `src/`. Governance gates are grouped under `scripts/governance/` (`check-agents-md.ts`, `check-skill-md.ts`, `check-readme.ts`, `doc-md-common.ts`). Destructive release scripts (`scripts/release.ts`, `scripts/bump-version.ts`) must never be triggered autonomously by agents without explicit human instruction. +Engineering toolchain, code generators, build pipelines, and governance gate scripts live under `scripts/`. Scripts under `scripts/` are offline harnesses, not application runtime code — never import them into `src/`. Governance gates are grouped under `scripts/governance/` (`check-agents-md.ts`, `check-skill-md.ts`, `check-readme.ts`, `check-readme-naming.ts`, `doc-md-common.ts`). Destructive release scripts (`scripts/release.ts`, `scripts/bump-version.ts`) must never be triggered autonomously by agents without explicit human instruction. Within `src/domains/seal/`, the root contains only shared protocol boundaries (`api.ts`, `api.test.ts`, `types.ts`) and the public capability export (`capabilities.ts`). Business implementations belong in their feature directories: `rules/`, `approval-runs/`, `insight/`, `replay/`, `outbound/`, `enterprise/`, `search/`, and `testing/`; existing `reports/`, `linter/`, `material-pack/`, `doctor/`, and `regression/` retain their own boundaries. Put new Seal implementations and their tests in the matching feature directory (for example `rules/recode.ts` and `rules/recode.test.ts`), rather than adding business files or legacy forwarding stubs to the domain root. The registry-wide tests live in `capabilities/capabilities.test.ts`. @@ -25,6 +25,7 @@ Tests are colocated as `*.test.ts` files in `src/`. - `bun run verify:agents-md`: validate the root `AGENTS.md` developer contract (structure, required sections, `.agents/rules/` reference integrity and reverse coverage); wired into pre-commit (staged docs only) and CI. - `bun run verify:skill-md`: validate the `skills/seal-use/SKILL.md` routing hub (structure and bidirectional `references/` routing); wired into pre-commit (staged docs only) and CI. - `bun run verify:readme`: lightweight hygiene and structure checks for `README.md` (warnings only, never blocks). +- `bun run verify:readme-naming`: enforce the root `README.md` and subdirectory `.readme.md` naming rule (leading dots stripped, e.g. `src/src.readme.md`); wired into pre-commit (staged README files) and CI. - `bun run bump `: bump version across all manifest and skill files. - `bun run dev:override`: compile the host binary with Git dev version metadata, macOS sign, atomically override the existing global command found on PATH (falling back to a standalone bin directory), and sync the local Agent Skill. @@ -37,7 +38,7 @@ Prefer small domain functions over broad utility modules. ## CLI & Agent Harness Protocol Guidelines - **Machine Channel (`stdout`)**: Data commands MUST output clean, parseable JSON on `stdout`. Never dump human prose, raw logs, or progress banners into `stdout`. The Agent Harness parses `stdout` directly into typed payloads. - - **Documented exception — document-output commands**: `seal-use --help` / `seal-use help ` (`src/cli/printer.ts`), `seal-use doctor guide` (`src/cli/commands/doctor.ts`), and `seal-use skill dump` (`src/cli/commands/skill.ts`) intentionally write Markdown to `stdout`, because their output *is* the payload the caller redirects or reads (e.g. `seal-use doctor guide > guide.md`, `seal-use skill dump > SKILL.md`). Never add a new prose-on-stdout command outside this list: return structured JSON and put the readable rendering on `stderr` instead. `src/probe.ts` is a local developer probe script rather than a `bin` entry point, so its `[probe] …` lines are outside this contract. + - **Documented exception — document-output commands**: `seal-use --help` / `seal-use help ` (`src/cli/output/printer.ts`), `seal-use doctor guide` (`src/cli/commands/doctor.ts`), and `seal-use skill dump` (`src/cli/commands/skill.ts`) intentionally write Markdown to `stdout`, because their output *is* the payload the caller redirects or reads (e.g. `seal-use doctor guide > guide.md`, `seal-use skill dump > SKILL.md`). Never add a new prose-on-stdout command outside this list: return structured JSON and put the readable rendering on `stderr` instead. `src/probe.ts` is a local developer probe script rather than a `bin` entry point, so its `[probe] …` lines are outside this contract. - **Guidance & Diagnostic Channel (`stderr`)**: Use `stderr` for runtime logs, network probing status, self-healing notifications, and explicit **Next-Step Command Suggestions** (e.g. `👉 Next action: seal-use deploy hosecloud sync `). - **Performance Contract & SWR Architecture**: Read-only discovery and version commands (`seal-use version`, `seal-use doctor`, `seal-use corps list`) MUST execute in under 70ms wall clock (Bun startup alone is ~7ms; runner dispatch uses lazy `await import()` per command area, so the version path never loads the Excel/zip tool chain). Never block on external network I/O during routine invocations. Use the Stale-While-Revalidate (SWR) pattern: read local cache from `~/.config/seal-use/*.json` synchronously (<0.2ms), and refresh stale/missing data via detached, unref'd child processes (`triggerBackgroundUpdateCheck`, `unref()`). - **Safety Guardrail & Mutation Preview (`--dry-run`)**: All potentially destructive or state-mutating commands (e.g. `rules push/clear`, `corps sync-test`, `preference update`, `webhook create/update`) MUST support `--dry-run` returning structured JSON previews with `preview: true` and a clean diff, without executing mutations. Live execution requires explicit `--yes` or `--confirm`. @@ -50,7 +51,7 @@ Prefer small domain functions over broad utility modules. - `12`: Output protection — response exceeds the size limit; use `--summary`/`--fields`/`--count`/`--output-file` (or `--full` when the full payload is genuinely required). - `13`: Local configuration or input-data validation failure — well-formed command, but the value or config file is unusable (missing `--corp`, unparseable enterprise JSON, missing required parameter named in a Chinese-language error). - `14`: Safety guard block — the target environment forbids the action (replay into production, regression outside a test tenant); requires a different target or an explicit override. - - Never call `process.exit()` deep in domain functions; throw structured errors and let `src/cli/runner.ts` handle stream routing and exit code assignment. + - Never call `process.exit()` deep in domain functions; throw structured errors and let `src/cli/run/runner.ts` handle stream routing and exit code assignment. ## Testing Guidelines @@ -111,7 +112,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`, git push origin refs/tags/vX.Y.Z ``` - GitHub Actions (`release.yml`) is responsible only for cross-compiling all 5 target binaries and publishing the GitHub Release. - - **Gitea Pull-Based Promotion & Mirroring**: On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls GitHub every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), mirrors Git repository refs (branches and tags) and pulls release assets into Gitea (`wsl-infra/systemd/`). + - **Gitea Pull-Based Promotion & Mirroring**: On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls GitHub every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), mirrors Git repository refs (branches and tags) and pulls release assets into Gitea (`host-infra/systemd/`). - The workflow enforces the merge-before-tag rule rather than trusting the operator: `release.yml` refuses to publish unless the tagged commit is an ancestor of `origin/main`. Actions in both workflows are pinned to commit SHAs rather than moving tags for supply-chain integrity. ## Security & Configuration Tips diff --git a/README.md b/README.md index b2953ba..2c257e9 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Bun + TypeScript CLI for pulling Seal enterprise approval context from provider credentials. -The first provider is Hose/合思: `key`, `password`, `corpId`, `staffId`, and an optional Hose domain. The provider exchanges those credentials for a Seal enterprise session, then the Seal domain tools can read and maintain approval rules, approval documents, and approval style preferences. +The first provider is Hose/合思: `appKey`, `appSecurity`, `corpId`, `staffId`, and an optional Hose domain. The provider exchanges those credentials for a Seal enterprise session, then the Seal domain tools can read and maintain approval rules, approval documents, and approval style preferences. Seal-native enterprise pages can be added with a Seal Bearer token. @@ -121,7 +121,7 @@ Import a Hose/合思 assistance link when you do not have OpenAPI app credential seal-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=&ekbCorpId=&pageType=home" [--name "企业名称"] ``` -The command accepts HTTPS links from the supported Hose domains, verifies the Seal tenant with `/api/v1/auth/me`, and writes a Hose source with `provider: "hosecloud"`, `closeToken`, and `staffId`. The incoming token is never printed. Use `--overwrite` to replace an existing config explicitly. +The command accepts HTTPS links from the supported Hose domains, verifies the Seal tenant with `/api/v1/auth/me`, and writes a Hose source with `closeToken` and `staffId`. The incoming token is never printed. Use `--overwrite` to replace an existing config explicitly. To generate a Seal delegation link directly from the same incoming Hose link without saving a config: @@ -154,6 +154,7 @@ Three layers of documentation serve distinct audiences and boundaries, each vali - **`README.md` — the user/evaluator entry point.** High-level overview, quick installation, architecture, and governance outline (`bun run verify:readme`). - **`AGENTS.md` — the developer contract.** How contributors (human or agent) change this codebase: module boundaries, CLI stream/exit-code protocol, testing, release rules (`bun run verify:agents-md`). - **`skills/seal-use/SKILL.md` — the user/agent routing hub.** How an agent session uses the shipped skill: bootstrap, credential boundaries, and the terminal `## 参考文档路由` table that routes intents to `skills/seal-use/references/*.md`, which stay the single source of truth for operational detail (`bun run verify:skill-md`). +- **Subdirectory readmes — `.readme.md`.** The root keeps `README.md`; every other README carries its directory name as a prefix, such as `src/src.readme.md` and `host-infra/host-infra.readme.md` (`bun run verify:readme-naming`). Workflow rules live in `.agents/rules/*.md`; the root `AGENTS.md` indexes them and carries the enforced contract. Engineering and governance scripts live under `scripts/`, partitioned into `scripts/governance/` (automated gates) and root build/release pipelines. @@ -217,8 +218,8 @@ Use `seal-use auth diagnose --corp ` when login fails in stateless mode. "source": { "type": "hose", "domain": "https://app.ekuaibao.com", - "key": "hose-app-key", - "password": "hose-app-security", + "appKey": "hose-app-key", + "appSecurity": "hose-app-security", "staffId": "hose-staff-id", "corpId": "hose-corp-id" }, @@ -354,4 +355,4 @@ bun run bump 0.8.5 **CI & Promotion Pipeline:** - GitHub Actions triggers automatically upon pushing a `v*` tag to `origin`; - Cross-compiles standalone binaries for 5 target platforms (macOS Apple Silicon/Intel, Linux x86_64/ARM64, Windows x64) and publishes them to **[GitHub Releases](https://github.com/yunyingk/seal-use/releases)**; -- WSL `seal-use-release-sync.timer` polls the latest GitHub Release and promotes all assets to **[Gitea Releases](https://git.ying-qing.cn/gitea/seal-use/releases)** (`wsl-infra/README.md`). +- WSL `seal-use-release-sync.timer` polls the latest GitHub Release and promotes all assets to **[Gitea Releases](https://git.ying-qing.cn/gitea/seal-use/releases)** (`host-infra/host-infra.readme.md`). diff --git a/docs/proposals/enterprise-provider-cleanup/plan.md b/docs/proposals/enterprise-provider-cleanup/plan.md new file mode 100644 index 0000000..1bbc82e --- /dev/null +++ b/docs/proposals/enterprise-provider-cleanup/plan.md @@ -0,0 +1,69 @@ +# 企业 provider 字段清理方案 + +状态:已实施并验证(2026-11-19)。范围仅限企业 provider 元数据及其直接引用。 + +## 结论与证据 + +建议删除企业配置的 `source.provider`、`source.providerName`,同时删除本地认证会话的 `enterprise.provider` 及相关输入、展示、检索、赋值和测试负载。不新增替代分类字段。 + +- [配置定义](../../../src/core/config/types.ts:9):`provider` 在两种 source 上均为可选自由字符串,不是三值枚举;`providerName` 只有声明,没有业务读写。 +- [企业选择](../../../src/core/config/manager.ts:11):选择依据是企业 ID、名称、默认企业和 active 门禁;provider 不参与。 +- [搜索](../../../src/core/corp-search/corp.ts:26):provider 作为权重 0.8 的可选匹配文本。 +- [列表与当前企业](../../../src/cli/commands/corps/overview.ts:97) 使用 `provider ?? source.type`;[详情](../../../src/cli/commands/corps/shared.ts:26) 的 Hose 分支使用 `provider ?? "hosecloud"`。持久凭据企业未存 provider 时,两者输出不同值。 +- [Seal 接入](../../../src/domains/seal/enterprise/onboarding.ts:142) 从输入或远端身份中复制 provider;[Hose Web 接入](../../../src/domains/hose/onboarding.ts:278) 写死 hosecloud;Hose 持久凭据不写该字段。 +- [缓存类型](../../../src/core/auth/types.ts:9) 要求 enterprise.provider,由 [native](../../../src/core/auth/native.ts:18)、[seal](../../../src/core/auth/seal.ts:72)、[hose](../../../src/core/auth/hose.ts:498) 构造,但仓库内没有按它决策的消费者。 +- 三处企业密钥相关输出也含固定 `provider: "hose"`,见 [corps/onboarding.ts](../../../src/cli/commands/corps/onboarding.ts:342)。它们不是企业配置写入点,但属于同一冗余标签。 + +证据边界:以上为仓库内静态引用调查,不能据此断言没有外部脚本读取 CLI JSON 中的 provider。此前“三种分类”以及“只需改几处展示”的描述不准确;实际涉及配置、接入、缓存、输出和测试。 + +## 目标与涉及文件 + +| 模块 | 文件 | 具体修改 | +|---|---|---| +| 配置 | [types.ts](../../../src/core/config/types.ts) | 删除 Hose、Seal source 的 provider,以及 Seal source 的 providerName | +| 本地会话 | [auth/types.ts](../../../src/core/auth/types.ts)、[native.ts](../../../src/core/auth/native.ts)、[seal.ts](../../../src/core/auth/seal.ts)、[hose.ts](../../../src/core/auth/hose.ts) | 删除 enterprise.provider 的 schema 与三处构造赋值 | +| 接入 | [seal/enterprise/onboarding.ts](../../../src/domains/seal/enterprise/onboarding.ts)、[hose/onboarding.ts](../../../src/domains/hose/onboarding.ts) | 删除 SealBearerInput.provider、远端复制和固定值写入;保留其它身份与凭据数据 | +| CLI | [corps/onboarding.ts](../../../src/cli/commands/corps/onboarding.ts)、[overview.ts](../../../src/cli/commands/corps/overview.ts)、[shared.ts](../../../src/cli/commands/corps/shared.ts) | 停止解析 add-seal-bearer 的 provider;删除列表、当前企业、详情和三处密钥相关输出中的 provider | +| 检索 | [corp-search/corp.ts](../../../src/core/corp-search/corp.ts) | 删除 provider 匹配项 | +| 文档 | [README.md](../../../README.md:124) | 删除接入后保存 provider: hosecloud 的承诺,继续说明真实凭据字段 | + +测试同步范围: + +- [config/types.test.ts](../../../src/core/config/types.test.ts)、[cli/commands/corps.test.ts](../../../src/cli/commands/corps.test.ts):更新字段预期,覆盖旧字段兼容和输出不再带 provider。 +- [auth/native.test.ts](../../../src/core/auth/native.test.ts)、[auth/hose.test.ts](../../../src/core/auth/hose.test.ts)、[auth/seal-renew.test.ts](../../../src/core/auth/seal-renew.test.ts)、[auth/token-store.test.ts](../../../src/core/auth/token-store.test.ts):更新会话构造及断言,验证旧缓存仍可读。 +- [http/factory.test.ts](../../../src/core/http/factory.test.ts)、[cli/commands/report-review-cli.test.ts](../../../src/cli/commands/report-review-cli.test.ts)、[probe.test.ts](../../../src/probe.test.ts):仅清理本地会话 fixture 的冗余标签;保留模拟远端接口的真实字段。 + +## 边界与取舍 + +保留以下内容: + +1. `source.type: hose | seal`:仍决定认证实现。 +2. `closeToken`、`appKey/appSecurity`、Seal token 和委托 cookie:仍决定实际凭据与认证过程。 +3. `providerUserId`:接入和刷新元数据使用它,且 [onboarding.ts:141](../../../src/domains/seal/enterprise/onboarding.ts:141) 用它推导 staffId;不能因名字相似而连带删除。 +4. [Seal API 用户身份判断](../../../src/domains/seal/api.ts:1283) 与 [远端类型](../../../src/domains/seal/types.ts):这里的 provider 属于服务端协议,实际参与本地密码及合思身份判断,继续保留。 +5. 远端原始对象中的 provider、LLM provider 等同名概念。 +6. 企业启停、环境标签、生产测试绑定、默认企业选择等其它管理机制。 + +不扩展到企业管理整体重构;此次明确有证据的冗余字段可独立清理。 + +## 兼容与预期行为变化 + +- 旧企业 JSON 即使仍有 provider/providerName,也应正常加载;Zod 默认剥离未声明键,运行时对象不再包含它们。不会因加载而主动改写原文件。 +- 新建或经现有 schema 保存的企业配置不再写入这些键。不编写迁移脚本,也不扫描或批量重写真实企业目录。 +- 旧 tokens.json 带 enterprise.provider 时仍应解析成功,后续会话不再生成该键;现有 token、有效期和其它缓存条目保留。通过隔离测试验证,不操作真实 token 文件。 +- add-seal-bearer 的旧 JSON 中仍带 provider 时按无效元数据忽略,不因这一额外键报错,也不再检查或保存它。 +- corps list/current/get/show 及三处密钥相关输出不再有 provider;已有 sourceType、source.type 或 kind 等字段继续按现有命令输出,避免重新添加同义标签。 +- 依赖 JSON provider 字段的外部调用方需要调整;不能承诺输出结构完全兼容。 +- 仅凭 provider 匹配的检索结果会消失,例如 Seal source 中曾存 feishu、用户以 feishu 搜企业。企业 ID、名称等现有搜索字段继续工作,Hose 仍可由 source.type 匹配。 +- 认证与租户操作的分派依据不变,删除的是元数据链路。 + +## 验证方案 + +1. 隔离配置测试:旧 provider/providerName 存在时仍能加载,解析结果不再含键;Hose 持久凭据、Web 会话与 Seal source 仍通过校验。 +2. 隔离缓存测试:带 provider 的旧缓存及不带 provider 的新缓存均能读取,token、有效期和其它条目不丢失。 +3. 接入与 CLI 回归:两类 Hose 接入、Seal bearer、委托与续期既有测试;断言新配置、会话和相关 JSON 输出不再产生 provider。 +4. 检索回归:验证删除 provider 搜索项后 ID、名称、source.type 等正常匹配。 +5. 执行 `bun run check`、`bun run lint` 与上述受影响的 Bun 测试;测试禁用后台更新并使用临时配置路径,不访问真实企业数据。 +6. 最后复查 Diff 和全仓引用,确认剩余 provider 仅属于服务端协议、其它业务概念或明确的旧格式兼容测试;若有新增发现,报告实际差异。 + +实施结果:已按上表完成清理,`bun run check`、`bun run lint` 与全量 `bun test`(1180 通过)均通过。未改写本机企业配置或认证缓存;旧配置与旧缓存的兼容性由隔离测试覆盖。 diff --git a/wsl-infra/README.md b/host-infra/host-infra.readme.md similarity index 73% rename from wsl-infra/README.md rename to host-infra/host-infra.readme.md index 515bb49..cce9e94 100644 --- a/wsl-infra/README.md +++ b/host-infra/host-infra.readme.md @@ -42,26 +42,10 @@ Credentials are stored as `0600` files under From mac15, run: ```sh -./ops/infra-healthcheck.sh +./host-infra/infra-healthcheck.sh ``` It emits JSON checks for mac15, the Mac15-to-WSL Tailscale/SSH path, WSL, Windows, mac13, and Aliyun, including the release-sync timer state and the last successful Gitea promotion. The script is read-only; a failed check does not restart or mutate any service. - -## Workspace backups - -The repository is the source of truth. After the ops changes are committed to -`main`, back up the tracked `ops/` directory to each machine's global workspace: - -```sh -./ops/backup-workspace-scripts.sh -``` - -Each run creates a commit-named snapshot under -`~/Workspace/ops-backups/seal-use/` on mac15 and mac13, and under -`~/workspace/ops-backups/seal-use/` on WSL and Aliyun. Each snapshot includes a -manifest with its source commit and backup time. Only tracked `ops/` files are -copied; private runtime configuration and credentials are excluded. Run the -backup command again after changing operational scripts or service templates. diff --git a/wsl-infra/infra-healthcheck.sh b/host-infra/infra-healthcheck.sh similarity index 100% rename from wsl-infra/infra-healthcheck.sh rename to host-infra/infra-healthcheck.sh diff --git a/wsl-infra/release-sync.sh b/host-infra/release-sync.sh similarity index 100% rename from wsl-infra/release-sync.sh rename to host-infra/release-sync.sh diff --git a/wsl-infra/systemd/mihomo.service b/host-infra/systemd/mihomo.service similarity index 100% rename from wsl-infra/systemd/mihomo.service rename to host-infra/systemd/mihomo.service diff --git a/wsl-infra/systemd/seal-use-release-sync.service b/host-infra/systemd/seal-use-release-sync.service similarity index 100% rename from wsl-infra/systemd/seal-use-release-sync.service rename to host-infra/systemd/seal-use-release-sync.service diff --git a/wsl-infra/systemd/seal-use-release-sync.timer b/host-infra/systemd/seal-use-release-sync.timer similarity index 100% rename from wsl-infra/systemd/seal-use-release-sync.timer rename to host-infra/systemd/seal-use-release-sync.timer diff --git a/package.json b/package.json index 83fa0b6..485e608 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,8 @@ "verify:cli-md": "bun run scripts/check-cli-md.mjs", "verify:agents-md": "bun run scripts/governance/check-agents-md.ts", "verify:skill-md": "bun run scripts/governance/check-skill-md.ts", - "verify:readme": "bun run scripts/governance/check-readme.ts" + "verify:readme": "bun run scripts/governance/check-readme.ts", + "verify:readme-naming": "bun run scripts/governance/check-readme-naming.ts" }, "dependencies": { "@modelcontextprotocol/server": "^2.0.0", diff --git a/pkg/example-report.md b/pkg/example-report.md deleted file mode 100644 index cb260f3..0000000 --- a/pkg/example-report.md +++ /dev/null @@ -1,190 +0,0 @@ -# 【模板企业】8月AI审核准确率报告 - -| 报告信息 | 内容 | -| --- | --- | -| 报告编号 | RPT-202608-A3F8C2 | -| 客户名称 | 模板企业 | -| 统计期间 | 2026-08-01 ~ 2026-08-31 | -| 报告状态 | 草稿 | -| 生成日期 | 2026-09-23 | - -> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。 - ---- - -## 1. 审核测试结果 - -### 1.1 数据来源与范围 - -| 项目 | 内容 | -| --- | --- | -| 数据来源 | 客户授权的已完成历史审批单据 | -| 统计期间 | 2026-08-01 ~ 2026-08-31 期间单据 | -| 单据模板 | 涵盖一般费用报销单【发票】-个人报销、一般费用报销单【发票】-对外支付、一般费用报销单【收据】-个人报销、差旅报销单-定额、采购付款单等 **16 类**业务单据模板 | -| 样本总量 | **240 张**(100 张同意 + 100 张驳回 + 40 张建议复核) | - -### 1.2 核心准确率结论 - -基于已经给定的规则库: - -| 审核方式 | 准确率 | -| --- | --- | -| AI 审核 | **92.08%** | -| 人工审核 | **83.33%** | - -AI 审核准确率的计算方式: - -$$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样本总量}} = \frac{221}{240} = 92.08\% $$ - -![AI 与人工审核准确率对比](assets/图1-准确率对比.svg) - -*图 1 · AI 与人工审核准确率对比* - ---- - -## 2. AI 失准分析(学习优化空间) - -在全量 **240 单**的深度稽核中,AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。 - -### 2.1 失准构成总览 - -| 维度 | 失准类型 | 占比 | 单数 | -| --- | --- | --- | --- | -| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 | -| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 | -| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 | -| 合计 | — | 100% | 19 张 | - -### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%) - -**解决方案**:严格校准规则触发后动作,按规则执行。 - -| 单号 | 问题描述 | -| --- | --- | -| FP260001 | 规则仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 | -| CD260002 | 连续三日均为工作日(周一至周三),AI 误认为有周末未扣减问题 | -| FP260003 | 费用承担主体命中豁免白名单,AI 未执行豁免逻辑导致驳回 | - -*(节选 3 例,全量 9 张)* - -### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%) - -**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。 - -| 单号 | 问题描述 | -| --- | --- | -| SJ260004 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 | -| FP260005 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 | -| SG260006 | 已完整包含福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 | - -*(节选 3 例,全量 5 张)* - -### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%) - -**解决方案**:已去掉跨批次相似费用冲突的默认判定,可按需配置此功能。 - -| 单号 | 问题描述 | -| --- | --- | -| CGD260007 | 跨批次存在历史同类辅料费用,提示疑似冲突转人工 | -| FP260008 | 跨批次云产品疑似同类费用冲突转人工 | -| FP260009 | 发票金额 180 元(1% 普票),远未达到 500 元专票强制门槛,AI 过度怀疑是否存在专票协议转人工 | - -*(节选 3 例,全量 5 张)* - ---- - -## 3. AI 发现的潜在风险 - -在人工审核同意的单据中,有部分单据被 AI 发现存在风险,问题 TOP 3 如下。 - -### 3.1 风险构成总览 - -| 维度 | 风险类型 | 占比 | 单数 | -| --- | --- | --- | --- | -| TOP 1 | 缺失要求凭证 | 57.5% | 23 张 | -| TOP 2 | 大额预付与采购口径偏差 | 22.5% | 9 张 | -| TOP 3 | 票据合规与专票强制违规 | 20.0% | 8 张 | -| 合计 | — | 100% | 40 张 | - -### 3.2 TOP 1 · 缺失要求凭证(23 张 / 57.5%) - -| 单号 | 问题描述 | -| --- | --- | -| FP260011 | 改衣费未附改衣明细表 | -| FP260012 | 咨询费报销资料不全 | -| FP260013 | 专利代理费未列明发明名称且缺少缴费通知书 | - -*(节选 3 例,全量 23 张)* - -### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%) - -| 单号 | 问题描述 | -| --- | --- | -| YF260014 | 大额预付款单未关联申购单 / 申请单 | -| CGA260015 | 采购预付款单明细采购订单号与合同号不一致 | -| CGD260016 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 | - -*(节选 3 例,全量 9 张)* - -### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%) - -| 单号 | 问题描述 | -| --- | --- | -| FP260017 / FP260018 / FP260019 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 | -| FP260020 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 | -| FP260021 | 完税证明纳税人名称与费用承担公司主体不一致 | - -*(节选 3 条,全量 8 张)* - ---- - -## 4. 综合效益 - -| 维度 | 结论 | 关键数据 | -| --- | --- | --- | -| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** | -| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** | -| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 | -| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — | - ---- - -## 5. 审核分歧与复核归因 - -在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下: - -| 原因分类 | 占比 | 单数 | 核心说明 | -| --- | --- | --- | --- | -| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 | -| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 | -| 合计 | 100% | 3 张 | — | - -**分歧分析与后续建议**: - -1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。 -2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。 - -> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。 - ---- - -## 6. 支撑数据与交付材料 - -### 6.1 分模板准确率与自动审批率 - -全量 N = 240: - -| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 | -| --- | --- | --- | --- | --- | --- | -| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% | -| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% | -| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% | -| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% | -| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% | -| **全量样本总体(N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** | - -*(其余 10 类模板从略,实际报告列出全量 16 类)* - -### 6.2 跑批原始数据与交付台账 - -见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。 diff --git a/pkg/report/README.md b/pkg/report/README.md deleted file mode 100644 index 1ca58ea..0000000 --- a/pkg/report/README.md +++ /dev/null @@ -1,64 +0,0 @@ -# AI 审核报告编制与校验规范 - -本目录提供标准的 AI 审核报告 Markdown 模板与配套的离线校验脚本。 - ---- - -## 一、标准模板与章节规范 - -报告应以 Markdown 格式编写(可参考同目录下的 [`example-report.md`](example-report.md))。 - -### 1. 核心必填章节(按大标题名称识别) -核心章节通过 `##` 大标题名称自动识别与归属,包含以下板块: - -| 核心大标题名称 | 说明与要求 | -| :--- | :--- | -| **开篇「报告信息」表** | 文档顶部表格,必填 5 项:`报告编号`、`客户名称`、`统计期间`、`报告状态`、`生成日期`,均不可为空。 | -| **`审核测试结果`** | 汇总效能指标、AI 与人工准确率结论、LaTeX 计算公式(`$$ \text{AI 审核准确率} = \frac{A}{B} = C\% $$`)与对比图表。 | -| **`AI 失准分析`** | 包含失准构成总览表、TOP 1~N 典型错判案例表格与调优方案。 | -| **`AI 发现的潜在风险`** | 包含潜在风险总览表、TOP 1~N 真实拦截案例表格(如凭证缺失、比价缺失、超期等)。 | -| **`综合效益`** | 时效、准确度、风险拦截笔数宏观总结表(纯内部核对时可按需裁剪)。 | -| **`审核分歧与复核归因`** | 人机分歧分类统计表(如“未在线配置规则”与“识别偏差”)与管理建议。 | -| **`支撑数据与交付材料`** | 分模板统计表与说明。 | - -### 2. 中间自定义插入章节 -* 如需针对特定部门、专项费用做深入穿透,允许在任意位置插入自定义章节(例如 `## 2. 营销业务线专项分析`)。 -* **规则**:大标题序号从 1 开始自然连续递增(1, 2, 3, 4, 5...);自定义插入的章节内容不受业务规则限制,写什么格式都直接放行。 - ---- - -## 二、核心格式规范 - -为保证文档严谨自洽,报告编写需满足以下格式守则: - -1. **纯净 Markdown 语法**: - * 严禁在开头使用 YAML Frontmatter(`---`),元数据请统一写在开篇「报告信息」表中; - * 严禁残留草稿占位标记(如 ``、`{{variable}}` 等); - * 代码块(```)必须成对闭合。 -2. **表格结构**: - * 表格每行单元格数量必须严格与表头对齐; - * 表头文字保持纯文本,禁止包含加粗符号(`**`); - * 案例表格推荐使用纯净紧凑的 2 列格式(`| 单号 | 问题描述 |`),无需手工填写长链接。 -3. **数学总账守恒**: - * 失准总览表与潜在风险总览表中,各 TOP 行的单数相加必须严格等于「合计」行单数,百分比相加必须等于 100%(误差 $\le 0.15\%$); - * 各子小节标题中声明的张数(如 `### 2.2 TOP 1 · xxx(9 张 / 47.4%)`)必须与总览表该行单数完全一致; - * LaTeX 公式中的算术计算必须成立(如 $\frac{221}{240} = 92.08\%$),且公式中的数字在正文中有对应出处。 - ---- - -## 三、校验脚本使用说明 - -同目录下已提供独立的 Python 校验脚本 [`validate.py`](validate.py)(纯 Python 标准库编写,无需安装任何第三方库)。 - -### 运行校验 -```bash -python3 validate.py example-report.md -``` - -* **校验通过**:终端输出绿色通过提示,退出码为 `0`; -* **校验未通过**:终端会明确打印出具体报错的行号、错误代码及修复指南,退出码为 `1`。 - -支持输出 JSON 格式供程序化调用: -```bash -python3 validate.py example-report.md --json -``` diff --git a/pkg/report/assets/图1-准确率对比.svg b/pkg/report/assets/图1-准确率对比.svg deleted file mode 100644 index 3f170da..0000000 --- a/pkg/report/assets/图1-准确率对比.svg +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - AI审核准确 - (总准确率92.08%) - - - - - - 16.66% - - - 75.42% - - - 7.91% - - - - - - - 人工审核准确 - (总准确率83.33%) - - - - - - - AI与人工都准确 - diff --git a/pkg/report/example-report.md b/pkg/report/example-report.md deleted file mode 100644 index cb260f3..0000000 --- a/pkg/report/example-report.md +++ /dev/null @@ -1,190 +0,0 @@ -# 【模板企业】8月AI审核准确率报告 - -| 报告信息 | 内容 | -| --- | --- | -| 报告编号 | RPT-202608-A3F8C2 | -| 客户名称 | 模板企业 | -| 统计期间 | 2026-08-01 ~ 2026-08-31 | -| 报告状态 | 草稿 | -| 生成日期 | 2026-09-23 | - -> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。 - ---- - -## 1. 审核测试结果 - -### 1.1 数据来源与范围 - -| 项目 | 内容 | -| --- | --- | -| 数据来源 | 客户授权的已完成历史审批单据 | -| 统计期间 | 2026-08-01 ~ 2026-08-31 期间单据 | -| 单据模板 | 涵盖一般费用报销单【发票】-个人报销、一般费用报销单【发票】-对外支付、一般费用报销单【收据】-个人报销、差旅报销单-定额、采购付款单等 **16 类**业务单据模板 | -| 样本总量 | **240 张**(100 张同意 + 100 张驳回 + 40 张建议复核) | - -### 1.2 核心准确率结论 - -基于已经给定的规则库: - -| 审核方式 | 准确率 | -| --- | --- | -| AI 审核 | **92.08%** | -| 人工审核 | **83.33%** | - -AI 审核准确率的计算方式: - -$$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样本总量}} = \frac{221}{240} = 92.08\% $$ - -![AI 与人工审核准确率对比](assets/图1-准确率对比.svg) - -*图 1 · AI 与人工审核准确率对比* - ---- - -## 2. AI 失准分析(学习优化空间) - -在全量 **240 单**的深度稽核中,AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。 - -### 2.1 失准构成总览 - -| 维度 | 失准类型 | 占比 | 单数 | -| --- | --- | --- | --- | -| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 | -| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 | -| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 | -| 合计 | — | 100% | 19 张 | - -### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%) - -**解决方案**:严格校准规则触发后动作,按规则执行。 - -| 单号 | 问题描述 | -| --- | --- | -| FP260001 | 规则仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 | -| CD260002 | 连续三日均为工作日(周一至周三),AI 误认为有周末未扣减问题 | -| FP260003 | 费用承担主体命中豁免白名单,AI 未执行豁免逻辑导致驳回 | - -*(节选 3 例,全量 9 张)* - -### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%) - -**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。 - -| 单号 | 问题描述 | -| --- | --- | -| SJ260004 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 | -| FP260005 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 | -| SG260006 | 已完整包含福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 | - -*(节选 3 例,全量 5 张)* - -### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%) - -**解决方案**:已去掉跨批次相似费用冲突的默认判定,可按需配置此功能。 - -| 单号 | 问题描述 | -| --- | --- | -| CGD260007 | 跨批次存在历史同类辅料费用,提示疑似冲突转人工 | -| FP260008 | 跨批次云产品疑似同类费用冲突转人工 | -| FP260009 | 发票金额 180 元(1% 普票),远未达到 500 元专票强制门槛,AI 过度怀疑是否存在专票协议转人工 | - -*(节选 3 例,全量 5 张)* - ---- - -## 3. AI 发现的潜在风险 - -在人工审核同意的单据中,有部分单据被 AI 发现存在风险,问题 TOP 3 如下。 - -### 3.1 风险构成总览 - -| 维度 | 风险类型 | 占比 | 单数 | -| --- | --- | --- | --- | -| TOP 1 | 缺失要求凭证 | 57.5% | 23 张 | -| TOP 2 | 大额预付与采购口径偏差 | 22.5% | 9 张 | -| TOP 3 | 票据合规与专票强制违规 | 20.0% | 8 张 | -| 合计 | — | 100% | 40 张 | - -### 3.2 TOP 1 · 缺失要求凭证(23 张 / 57.5%) - -| 单号 | 问题描述 | -| --- | --- | -| FP260011 | 改衣费未附改衣明细表 | -| FP260012 | 咨询费报销资料不全 | -| FP260013 | 专利代理费未列明发明名称且缺少缴费通知书 | - -*(节选 3 例,全量 23 张)* - -### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%) - -| 单号 | 问题描述 | -| --- | --- | -| YF260014 | 大额预付款单未关联申购单 / 申请单 | -| CGA260015 | 采购预付款单明细采购订单号与合同号不一致 | -| CGD260016 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 | - -*(节选 3 例,全量 9 张)* - -### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%) - -| 单号 | 问题描述 | -| --- | --- | -| FP260017 / FP260018 / FP260019 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 | -| FP260020 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 | -| FP260021 | 完税证明纳税人名称与费用承担公司主体不一致 | - -*(节选 3 条,全量 8 张)* - ---- - -## 4. 综合效益 - -| 维度 | 结论 | 关键数据 | -| --- | --- | --- | -| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** | -| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** | -| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 | -| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — | - ---- - -## 5. 审核分歧与复核归因 - -在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下: - -| 原因分类 | 占比 | 单数 | 核心说明 | -| --- | --- | --- | --- | -| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 | -| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 | -| 合计 | 100% | 3 张 | — | - -**分歧分析与后续建议**: - -1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。 -2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。 - -> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。 - ---- - -## 6. 支撑数据与交付材料 - -### 6.1 分模板准确率与自动审批率 - -全量 N = 240: - -| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 | -| --- | --- | --- | --- | --- | --- | -| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% | -| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% | -| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% | -| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% | -| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% | -| **全量样本总体(N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** | - -*(其余 10 类模板从略,实际报告列出全量 16 类)* - -### 6.2 跑批原始数据与交付台账 - -见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。 diff --git a/pkg/report/validate.py b/pkg/report/validate.py deleted file mode 100755 index dc6c1dc..0000000 --- a/pkg/report/validate.py +++ /dev/null @@ -1,374 +0,0 @@ -#!/usr/bin/env python3 -""" -AI 审核报告(Markdown)独立校验器 -Independent Markdown Validator for AI Audit Reports - -特点: -- 零外部依赖:纯 Python 标准库(Python 3.8+),跨平台开箱即用 -- 核心章节按大标题名称硬匹配,中间插入的自定义章节直接放行 -- 严格守护格式合规与数学总账守恒 - -用法: - python3 validate.py - python3 validate.py --json -""" - -import os -import sys -import re -import json -from pathlib import Path -from typing import List, Dict, Any, Optional, Tuple - -REQUIRED_INFO_ROWS = ["报告编号", "客户名称", "统计期间", "报告状态", "生成日期"] -FORBIDDEN_MARKS = [ - (re.compile(r""; diff --git a/scripts/generate-embedded-skill.mjs b/scripts/generate-embedded-skill.mjs index 0f9381d..53c7791 100644 --- a/scripts/generate-embedded-skill.mjs +++ b/scripts/generate-embedded-skill.mjs @@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url"; const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const skillRoot = resolve(root, "skills", "seal-use"); -export const embeddedSkillOutput = resolve(root, "src", "core", "embedded-skill.generated.ts"); +export const embeddedSkillOutput = resolve(root, "src", "core", "skill", "embedded-skill.generated.ts"); const textExtensions = new Set([".md", ".yaml", ".yml", ".json", ".txt"]); function walk(dir) { @@ -20,7 +20,7 @@ function walk(dir) { return files; } -export function renderEmbeddedSkill(sourceDir = skillRoot, coreDir = resolve(root, "src", "core")) { +export function renderEmbeddedSkill(sourceDir = skillRoot, coreDir = resolve(root, "src", "core", "skill")) { const files = walk(sourceDir).map((fullPath) => ({ relativePath: relative(sourceDir, fullPath).split("\\").join("/"), importPath: relative(coreDir, fullPath).split("\\").join("/"), diff --git a/scripts/generators.test.ts b/scripts/generators.test.ts index bc3abad..4c30fd0 100644 --- a/scripts/generators.test.ts +++ b/scripts/generators.test.ts @@ -50,15 +50,17 @@ describe("generated documentation contracts", () => { tempDirs.push(dir) const scripts = join(dir, "scripts") const core = join(dir, "src/core") + const coreSkill = join(core, "skill") const cli = join(dir, "src/cli") + const cliHelp = join(cli, "help") const skill = join(dir, "skills/seal-use") - for (const path of [scripts, core, cli, join(skill, "references")]) mkdirSync(path, { recursive: true }) + for (const path of [scripts, core, coreSkill, cli, cliHelp, join(skill, "references")]) mkdirSync(path, { recursive: true }) for (const name of ["generate-embedded-skill.mjs", "check-embedded-skill.mjs", "generate-cli-md.mjs", "check-cli-md.mjs"]) { copyFileSync(join(import.meta.dir, name), join(scripts, name)) } - writeFileSync(join(cli, "help.ts"), 'export const HELP_REGISTRY = [{ commands: [{ usage: ["seal-use fixture list"] }] }];') + writeFileSync(join(cliHelp, "help.ts"), 'export const HELP_REGISTRY = [{ commands: [{ usage: ["seal-use fixture list"] }] }];') writeFileSync(join(skill, "SKILL.md"), "fixture skill") - const embeddedPath = join(core, "embedded-skill.generated.ts") + const embeddedPath = join(coreSkill, "embedded-skill.generated.ts") const markdownPath = join(skill, "references/cli.md") writeFileSync(embeddedPath, "stale embedded fixture") const markdown = renderCliCommandBlock().replace("seal-use version", "seal-use stale-command") diff --git a/scripts/governance/check-readme-naming.test.ts b/scripts/governance/check-readme-naming.test.ts new file mode 100644 index 0000000..ab1d835 --- /dev/null +++ b/scripts/governance/check-readme-naming.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, test } from "bun:test" +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { + checkReadmeNaming, + expectedReadmeName, + isReadmeLike, + validateReadmePaths +} from "./check-readme-naming.js" + +describe("isReadmeLike", () => { + test("matches README variants", () => { + for (const name of ["README.md", "readme.md", "README.txt", "src.readme.md"]) { + expect(isReadmeLike(name)).toBe(true) + } + }) + + test("ignores unrelated files", () => { + for (const name of ["index.md", "readme-assets.ts", "README_GUIDE.md"]) { + expect(isReadmeLike(name)).toBe(false) + } + }) +}) + +describe("expectedReadmeName", () => { + test("prefixes with the directory name", () => { + expect(expectedReadmeName("src")).toBe("src.readme.md") + expect(expectedReadmeName("host-infra")).toBe("host-infra.readme.md") + }) + + test("strips leading dots from dot-directories", () => { + expect(expectedReadmeName(".agents")).toBe("agents.readme.md") + }) +}) + +describe("validateReadmePaths", () => { + test("accepts the conventional layout", () => { + const issues = validateReadmePaths([ + "README.md", + "src/src.readme.md", + ".agents/agents.readme.md", + "host-infra/host-infra.readme.md", + "src/domains/seal/reports/reports.readme.md" + ]) + expect(issues).toEqual([]) + }) + + test("rejects a plain README.md in a subdirectory", () => { + const issues = validateReadmePaths(["README.md", "src/README.md"]) + expect(issues).toHaveLength(1) + expect(issues[0].file).toBe("src/README.md") + expect(issues[0].rule).toBe("subdir-readme-name") + }) + + test("rejects a subdirectory README with the wrong prefix", () => { + const issues = validateReadmePaths(["README.md", "src/docs.readme.md"]) + expect(issues).toHaveLength(1) + expect(issues[0].rule).toBe("subdir-readme-name") + expect(issues[0].message).toContain("src.readme.md") + }) + + test("rejects a lowercase root readme", () => { + const issues = validateReadmePaths(["readme.md"]) + expect(issues.some((issue) => issue.rule === "root-readme-name")).toBe(true) + expect(issues.some((issue) => issue.rule === "missing-root-readme")).toBe(true) + }) + + test("requires a root README", () => { + const issues = validateReadmePaths(["src/src.readme.md"]) + expect(issues.some((issue) => issue.rule === "missing-root-readme")).toBe(true) + }) + + test("accepts nested directories with matching prefixes", () => { + const issues = validateReadmePaths([ + "README.md", + "src/domains/seal/reports/reports.readme.md", + "src/domains/seal/reports/templates/templates.readme.md" + ]) + expect(issues).toEqual([]) + }) +}) + +describe("checkReadmeNaming", () => { + test("skips the local root reports directory but checks nested ones", () => { + const root = mkdtempSync(join(tmpdir(), "readme-naming-")) + try { + writeFileSync(join(root, "README.md"), "# Root") + mkdirSync(join(root, "reports")) + writeFileSync(join(root, "reports", "README.md"), "# Local-only") + mkdirSync(join(root, "src")) + writeFileSync(join(root, "src", "README.md"), "# Wrong") + + const issues = checkReadmeNaming(root) + expect(issues).toHaveLength(1) + expect(issues[0].file).toBe("src/README.md") + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + test("the committed repository passes the naming rule", () => { + const root = join(import.meta.dirname, "../..") + expect(checkReadmeNaming(root)).toEqual([]) + }) +}) diff --git a/scripts/governance/check-readme-naming.ts b/scripts/governance/check-readme-naming.ts new file mode 100644 index 0000000..af45fe0 --- /dev/null +++ b/scripts/governance/check-readme-naming.ts @@ -0,0 +1,149 @@ +#!/usr/bin/env bun +/** + * Governance check for README naming. + * + * Rule: the repository root keeps the conventional `README.md`; every + * subdirectory README must carry its directory name as a prefix, e.g. + * `src/src.readme.md`, `.agents/agents.readme.md` (leading dots are stripped + * so the file stays visible). + * + * Invoked as `bun run verify:readme-naming` (CI + pre-commit) and with + * `--soft` from the ZCode SessionStart hook. + */ +import { readdirSync } from "node:fs" +import { join, relative, sep } from "node:path" + +export const ROOT_README = "README.md" + +/** Directories whose contents are generated, vendored, or local-only. */ +export const SKIP_DIRS: ReadonlySet = new Set([ + "node_modules", + ".git", + "dist", + "build", + "coverage", + ".cache", + "tmp", + ".local", + ".drafts", + ".workbuddy", + ".mimosa", + ".apifox" +]) + +/** + * Only the repository-root copy is local-only; a nested `reports/` directory + * (e.g. `src/domains/seal/reports/`) is tracked and must still be checked. + */ +export const ROOT_ONLY_SKIP_DIRS: ReadonlySet = new Set(["reports"]) + +export type ReadmeNamingIssue = { + file: string + rule: string + message: string +} + +/** `README.md`, `readme.txt`, `src.readme.md` — any file named like a README. */ +export function isReadmeLike(name: string): boolean { + const lower = name.toLowerCase() + return lower === "readme" || lower.startsWith("readme.") || lower.endsWith(".readme.md") +} + +/** Directory name → required README prefix, stripping leading dots. */ +export function expectedReadmeName(dirName: string): string { + const prefix = dirName.replace(/^\.+/, "") || dirName + return `${prefix}.readme.md` +} + +/** + * Pure validation over repo-relative paths so tests do not need a temp tree. + */ +export function validateReadmePaths(paths: readonly string[]): ReadmeNamingIssue[] { + const issues: ReadmeNamingIssue[] = [] + const normalized = paths.map((path) => path.split(sep).join("/")) + + if (!normalized.includes(ROOT_README)) { + issues.push({ + file: ROOT_README, + rule: "missing-root-readme", + message: "repository root must keep README.md" + }) + } + + for (const path of normalized) { + const parts = path.split("/") + const name = parts.pop() ?? "" + if (!isReadmeLike(name)) continue + + if (parts.length === 0) { + if (name !== ROOT_README) { + issues.push({ + file: path, + rule: "root-readme-name", + message: `root README must be named ${ROOT_README}, found ${name}` + }) + } + continue + } + + const dirName = parts[parts.length - 1] + const expected = expectedReadmeName(dirName) + if (name !== expected) { + issues.push({ + file: path, + rule: "subdir-readme-name", + message: `subdirectory README must be named ${expected} (directory "${dirName}"), found ${name}` + }) + } + } + + return issues +} + +function collectFiles(rootDir: string, dir = rootDir, files: string[] = []): string[] { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.isDirectory()) { + if (SKIP_DIRS.has(entry.name)) continue + const relDir = relative(rootDir, join(dir, entry.name)).split(sep).join("/") + if (ROOT_ONLY_SKIP_DIRS.has(entry.name) && relDir === entry.name) continue + collectFiles(rootDir, join(dir, entry.name), files) + } else if (entry.isFile()) { + files.push(relative(rootDir, join(dir, entry.name)).split(sep).join("/")) + } + } + return files +} + +export function checkReadmeNaming(rootDir: string): ReadmeNamingIssue[] { + return validateReadmePaths(collectFiles(rootDir)) +} + +function main(): void { + const root = join(import.meta.dirname, "../..") + const issues = checkReadmeNaming(root) + + if (process.argv.includes("--soft")) { + if (issues.length > 0) { + const summary = issues.map((issue) => issue.message).join("; ") + console.log( + JSON.stringify({ + additionalContext: `README 命名检查发现 ${issues.length} 项问题:${summary}。本地运行 bun run verify:readme-naming 查看详情。` + }) + ) + } + return + } + + if (issues.length > 0) { + for (const issue of issues) { + console.error(`✗ ${issue.file}: ${issue.message} [${issue.rule}]`) + } + console.error(`README naming checks failed (${issues.length} issue(s)).`) + process.exitCode = 1 + return + } + + console.log("README naming checks passed.") +} + +if (import.meta.main) main() diff --git a/scripts/README.md b/scripts/scripts.readme.md similarity index 96% rename from scripts/README.md rename to scripts/scripts.readme.md index db0319e..a734783 100644 --- a/scripts/README.md +++ b/scripts/scripts.readme.md @@ -13,6 +13,7 @@ scripts/ │ ├── check-agents-md.ts # AGENTS.md 开发者契约校验器 │ ├── check-skill-md.ts # SKILL.md 路由中枢与 references 双向路由校验器 │ ├── check-readme.ts # README.md 结构与卫生巡检器(警告级别) +│ ├── check-readme-naming.ts # 子目录 README 命名规范校验器(目录名前缀) │ ├── doc-md-common.ts # 共享 fence 感知 Markdown 解析纯函数库 │ └── *.test.ts # 逻辑 fixture 与真实文档现状双覆盖测试 │ diff --git a/skills/seal-use/references/staging-simulation-workflow.md b/skills/seal-use/references/staging-simulation-workflow.md index f6c95fb..4ad748e 100644 --- a/skills/seal-use/references/staging-simulation-workflow.md +++ b/skills/seal-use/references/staging-simulation-workflow.md @@ -154,7 +154,7 @@ flowchart TD - 对账知识库文档(覆盖更新已有文档、创建新文档、删除测试环境多余文档); - 清空测试环境旧草稿规则,灌入生产企业当前草稿规则并重算 code; - **自动同步合思集成**: - - 从本地 source 读入 `appKey`/`appSecurity`(兼容 `key`/`password`); + - 从本地 source 读入 `appKey`/`appSecurity`; - 截取企业名前缀并附加 `(Seal测)`(严格受控于 13 字符限制,例如 `钰泰半导体(Seal测)`); - 强制将审批模式设为 `assisted`; - 自动去重:若生产有多个相同 `corporationId` 的集成(如全自动与辅助),在测试环境自动合并为单条辅助集成; diff --git a/src/cli.ts b/src/cli.ts index bb57f60..1c0cd7f 100755 --- a/src/cli.ts +++ b/src/cli.ts @@ -1,8 +1,8 @@ #!/usr/bin/env bun import { fileURLToPath } from "node:url"; -import { runCli } from "./cli/runner.js"; -import { isCompiledBinary, performRuntimeSelfHealing, resolveAppRoot, resolveDefaultLauncher } from "./core/runtime.js"; +import { runCli } from "./cli/run/runner.js"; +import { isCompiledBinary, performRuntimeSelfHealing, resolveAppRoot, resolveDefaultLauncher } from "./core/util/runtime.js"; process.stdout.on("error", (err: any) => { if (err?.code === "EPIPE") process.exit(0); diff --git a/src/cli/commands/analytics.ts b/src/cli/commands/analytics.ts index 6aed4c0..796708b 100644 --- a/src/cli/commands/analytics.ts +++ b/src/cli/commands/analytics.ts @@ -3,8 +3,8 @@ import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { exportInsightReportToExcel } from "../../domains/seal/insight/export.js"; import { runCapability } from "../helpers.js"; -import { booleanOption, dryRunOption, numberOption, stringOption } from "../parser.js"; -import { outputOptions, printJson } from "../printer.js"; +import { booleanOption, dryRunOption, numberOption, stringOption } from "../parse/parser.js"; +import { outputOptions, printJson } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; export async function handleAnalyticsCommand( diff --git a/src/cli/commands/approval-runs-export.test.ts b/src/cli/commands/approval-runs-export.test.ts index 6d82a95..d654fa2 100644 --- a/src/cli/commands/approval-runs-export.test.ts +++ b/src/cli/commands/approval-runs-export.test.ts @@ -4,9 +4,9 @@ import { tmpdir } from "node:os" import { fileURLToPath } from "node:url" import { join } from "node:path" import ExcelJS from "exceljs" -import { parseArgs } from "../parser.js" -import { runCli } from "../runner.js" -import { isReadOnlyCliCommand } from "../read-only.js" +import { parseArgs } from "../parse/parser.js" +import { runCli } from "../run/runner.js" +import { isReadOnlyCliCommand } from "../run/read-only.js" import { getExportTask, startExportTask, waitForExportTask, writeExportTask } from "../../domains/seal/approval-runs/export-task.js" import { resolveExportOptions } from "./approval-runs-export.js" import type { CorpConfig } from "../../core/config/types.js" diff --git a/src/cli/commands/approval-runs-export.ts b/src/cli/commands/approval-runs-export.ts index 39a2a38..100e09d 100644 --- a/src/cli/commands/approval-runs-export.ts +++ b/src/cli/commands/approval-runs-export.ts @@ -1,9 +1,9 @@ import { appendFileSync, rmSync, writeFileSync } from "node:fs" import { extname, join, resolve } from "node:path" -import { durationSeconds, tokenizeDuration } from "../../core/duration.js" +import { durationSeconds, tokenizeDuration } from "../../core/util/duration.js" import { classifyCliError, CliError, usageError } from "../../core/errors.js" import { formatBeijingIso } from "../../core/config/timestamps.js" -import { resolveDefaultLauncher } from "../../core/runtime.js" +import { resolveDefaultLauncher } from "../../core/util/runtime.js" import { createSealClient } from "../../core/http/factory.js" import { exportApprovalRunsToExcel, normalizeManualApprovalStatus, resolveExportDateRange } from "../../domains/seal/approval-runs/export.js" import { @@ -12,8 +12,8 @@ import { type ExportTaskOptions } from "../../domains/seal/approval-runs/export-task.js" import { selectCorp } from "../helpers.js" -import { booleanOption, dryRunOption, numberOption, stringOption } from "../parser.js" -import { formatConsoleOutput, printJson, redactSensitiveText } from "../printer.js" +import { booleanOption, dryRunOption, numberOption, stringOption } from "../parse/parser.js" +import { formatConsoleOutput, printJson, redactSensitiveText } from "../output/printer.js" import type { CliRuntime, ParsedArgs } from "../types.js" import { approvalRunsExportOptions } from "./approval-runs.js" import type { CorpConfig } from "../../core/config/types.js" diff --git a/src/cli/commands/approval-runs.test.ts b/src/cli/commands/approval-runs.test.ts index 6fdb8d8..8584f0d 100644 --- a/src/cli/commands/approval-runs.test.ts +++ b/src/cli/commands/approval-runs.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test" import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" -import { runCli } from "../runner.js" +import { runCli } from "../run/runner.js" const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE", "SEAL_DISABLE_BG_UPDATE"] as const const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]])) diff --git a/src/cli/commands/approval-runs.ts b/src/cli/commands/approval-runs.ts index 952e1ce..da75494 100644 --- a/src/cli/commands/approval-runs.ts +++ b/src/cli/commands/approval-runs.ts @@ -8,8 +8,8 @@ import { extractApprovalRunAttachments } from "../../domains/seal/approval-runs/attachments.js"; import { runCapability, runCapabilityResult } from "../helpers.js"; -import { booleanOption, numberOption, stringOption } from "../parser.js"; -import { outputOptions, printJson } from "../printer.js"; +import { booleanOption, numberOption, stringOption } from "../parse/parser.js"; +import { outputOptions, printJson } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; import { handleWebhookCommand } from "./webhook.js"; diff --git a/src/cli/commands/auth.test.ts b/src/cli/commands/auth.test.ts index ef4e0d3..8f88e98 100644 --- a/src/cli/commands/auth.test.ts +++ b/src/cli/commands/auth.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { runCli } from "../runner.js"; +import { runCli } from "../run/runner.js"; const ORIGINAL_ENV = { enterprises: process.env.SEAL_USE_ENTERPRISES_DIR, diff --git a/src/cli/commands/auth.ts b/src/cli/commands/auth.ts index b9ae018..e832cc9 100644 --- a/src/cli/commands/auth.ts +++ b/src/cli/commands/auth.ts @@ -19,8 +19,8 @@ import { parseDelegationExpireHours, parseHoseExpireSeconds, stringOption -} from "../parser.js"; -import { outputOptions, printJson, redactSensitiveText } from "../printer.js"; +} from "../parse/parser.js"; +import { outputOptions, printJson, redactSensitiveText } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; import { runCapability, runCapabilityResult } from "../helpers.js"; import { extractKeysFromLinkAction, showCorpKeysAction } from "./corps.js"; @@ -175,11 +175,11 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo 2 ); } - const appKey = corp.source.appKey ?? corp.source.key; - const appSecurity = corp.source.appSecurity ?? corp.source.password; + const appKey = corp.source.appKey; + const appSecurity = corp.source.appSecurity; if (!appKey || !appSecurity) { throw validationError( - `缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity(或 key/password),无法向合思 OpenAPI 签发 accessToken。` + `缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity,无法向合思 OpenAPI 签发 accessToken。` ); } const force = @@ -237,8 +237,8 @@ async function diagnoseAuth(corp: CorpConfig) { clearCorpTokenCache(corp.id); const source = corp.source; - const appKey = source.appKey ?? source.key; - const appSecurity = source.appSecurity ?? source.password; + const appKey = source.appKey; + const appSecurity = source.appSecurity; const sealUrl = (corp.seal.url ?? source.sealUrl ?? `https://${source.corpId.toLowerCase()}.sealai.cc`).replace(/\/+$/, ""); const uid = source.staffId.includes(":") ? source.staffId : `${source.corpId}:${source.staffId}`; const stages: Array> = []; @@ -255,7 +255,7 @@ async function diagnoseAuth(corp: CorpConfig) { { name: "hose.openapi", ok: false, - error: "Hose source requires appKey/key and appSecurity/password" + error: "Hose source requires appKey and appSecurity" } ] }; diff --git a/src/cli/commands/billing.ts b/src/cli/commands/billing.ts index 312da16..1f63931 100644 --- a/src/cli/commands/billing.ts +++ b/src/cli/commands/billing.ts @@ -2,7 +2,7 @@ import { usageError } from "../../core/errors.js"; import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { runCapability } from "../helpers.js"; -import { outputOptions } from "../printer.js"; +import { outputOptions } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; export async function handleBillingCommand( diff --git a/src/cli/commands/config.ts b/src/cli/commands/config.ts index e2a1bd4..0e429c1 100644 --- a/src/cli/commands/config.ts +++ b/src/cli/commands/config.ts @@ -8,8 +8,8 @@ import { } from "../../core/config/loader.js"; import { resolveCorpConfig } from "../../core/config/manager.js"; import { globalConfigSummary } from "../helpers.js"; -import { parseStateMode, stringOption } from "../parser.js"; -import { printJson } from "../printer.js"; +import { parseStateMode, stringOption } from "../parse/parser.js"; +import { printJson } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; export function handleConfigCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) { diff --git a/src/cli/commands/contacts.ts b/src/cli/commands/contacts.ts index 836cf86..4814c90 100644 --- a/src/cli/commands/contacts.ts +++ b/src/cli/commands/contacts.ts @@ -2,7 +2,7 @@ import { usageError } from "../../core/errors.js"; import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { runCapability } from "../helpers.js"; -import { outputOptions } from "../printer.js"; +import { outputOptions } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; export async function handleContactsCommand( diff --git a/src/cli/commands/context.ts b/src/cli/commands/context.ts index 6785e12..c65058e 100644 --- a/src/cli/commands/context.ts +++ b/src/cli/commands/context.ts @@ -1,8 +1,8 @@ import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { runCapability } from "../helpers.js"; -import { numberOption, ruleVersionContextOptions, stringOption } from "../parser.js"; -import { outputOptions } from "../printer.js"; +import { numberOption, ruleVersionContextOptions, stringOption } from "../parse/parser.js"; +import { outputOptions } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; export async function handleContextCommand( diff --git a/src/cli/commands/corps-bind.test.ts b/src/cli/commands/corps-bind.test.ts index caf16b3..a024325 100644 --- a/src/cli/commands/corps-bind.test.ts +++ b/src/cli/commands/corps-bind.test.ts @@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod import { tmpdir } from "node:os"; import { join } from "node:path"; import type { CorpConfig } from "../../core/config/types.js"; -import { runCli } from "../runner.js"; +import { runCli } from "../run/runner.js"; const ORIGINAL_ENV = { enterprises: process.env.SEAL_USE_ENTERPRISES_DIR, @@ -739,9 +739,10 @@ describe("sync-test hosecloud integration auto-sync", () => { expect(writtenIntegrations[0].apiOrigin).toBe("wechat"); }); - test("supports key/password fallback in source config when appKey/appSecurity are omitted", async () => { + test("rejects legacy key/password source config instead of falling back", async () => { const { enterprises } = setupHoseTestEnv(); - // Overwrite hose-prod.json to use key / password instead of appKey / appSecurity + // Legacy key/password aliases are no longer part of the schema; the file + // must be skipped on load rather than silently used for sync. const prodCorpWithKeyPassword = JSON.parse(readFileSync(join(enterprises, "hose-prod.json"), "utf-8")); delete prodCorpWithKeyPassword.source.appKey; delete prodCorpWithKeyPassword.source.appSecurity; @@ -749,25 +750,8 @@ describe("sync-test hosecloud integration auto-sync", () => { prodCorpWithKeyPassword.source.password = "fallback-secret-012"; writeFileSync(join(enterprises, "hose-prod.json"), JSON.stringify(prodCorpWithKeyPassword, null, 2)); - await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]); - - let capturedBody: any; - mockHoseSyncRequests({ - onConfigWrite: (isProd, body) => { - if (!isProd) capturedBody = body; - } - }); - - const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]); - expect(result.isError).toBe(false); - - const parsed = JSON.parse(result.stdout); - expect(parsed.hosecloudSync.skipped).toBe(false); - expect(parsed.hosecloudSync.synced).toHaveLength(1); - - const writtenIntegration = capturedBody?.integrations?.find((i: any) => i.type === "hosecloud"); - expect(writtenIntegration?.apiKey).toBe("fallback-key-789"); - expect(writtenIntegration?.apiSecret).toBe("fallback-secret-012"); + const result = await runCli(["corps", "get", "hose-prod"]); + expect(result.isError).toBe(true); }); }); diff --git a/src/cli/commands/corps.test.ts b/src/cli/commands/corps.test.ts index cbb6ca1..b7bb498 100644 --- a/src/cli/commands/corps.test.ts +++ b/src/cli/commands/corps.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { runCli } from "../runner.js"; +import { runCli } from "../run/runner.js"; const ORIGINAL_ENV = { enterprises: process.env.SEAL_USE_ENTERPRISES_DIR, @@ -45,7 +45,6 @@ describe("corps link onboarding", () => { type: string; closeToken: string; staffId: string; - provider?: string; corpId?: string; }; }; @@ -60,7 +59,6 @@ describe("corps link onboarding", () => { type: "hose", closeToken: "hose-token", staffId: "acme-01:admin", - provider: "hosecloud", corpId: "acme-01" } }); @@ -117,7 +115,6 @@ describe("corps link onboarding", () => { source: { type: string; token: string; - provider?: string; }; }; expect(config).toMatchObject({ @@ -129,8 +126,7 @@ describe("corps link onboarding", () => { }, source: { type: "seal", - token: "mock-delegate-token", - provider: "seal" + token: "mock-delegate-token" } }); }); @@ -193,7 +189,7 @@ describe("corps link onboarding", () => { expect(result.exitCode).toBe(0); const config = JSON.parse(readFileSync(join(enterprises, "acme-01.json"), "utf-8")); expect(config.source.type).toBe("hose"); - expect(config.source.provider).toBe("hosecloud"); + expect(config.source).not.toHaveProperty("provider"); expect(config.source.closeToken).toBe("hose-token"); expect(config.source.staffId).toBe("staff-1"); }); @@ -331,8 +327,7 @@ describe("corps get and search", () => { token: "veryLongSecretBearerToken1234567890", expiresIn: 3600, tenantSlug: "native-slug", - tenantName: "原生租户", - provider: "feishu" + tenantName: "原生租户" }, auth: { refreshTtl: 300 } }) @@ -346,7 +341,7 @@ describe("corps get and search", () => { const data = JSON.parse(result.stdout); expect(data.id).toBe("native-seal"); expect(data.source.type).toBe("seal"); - expect(data.source.provider).toBe("feishu"); + expect(data.source).not.toHaveProperty("provider"); expect(data.source.hasToken).toBe(true); expect(data.source.tokenMasked).toContain("..."); }); @@ -1145,7 +1140,7 @@ describe("Hose OpenAPI key extraction from assistance link", () => { }); test("RULE_SUMMARY_FIELDS excludes raw internal UUID and prioritizes business fields", async () => { - const { RULE_SUMMARY_FIELDS } = await import("../printer.js"); + const { RULE_SUMMARY_FIELDS } = await import("../output/printer.js"); expect(RULE_SUMMARY_FIELDS).not.toContain("id"); expect(RULE_SUMMARY_FIELDS).toContain("code"); expect(RULE_SUMMARY_FIELDS).toContain("status"); diff --git a/src/cli/commands/corps/active.ts b/src/cli/commands/corps/active.ts index 998c3c1..1627164 100644 --- a/src/cli/commands/corps/active.ts +++ b/src/cli/commands/corps/active.ts @@ -1,7 +1,7 @@ import { updateCorpConfig } from "../../../core/config/loader.js"; import { confirmationRequired, usageError } from "../../../core/errors.js"; -import { booleanOption, dryRunOption, stringOption } from "../../parser.js"; -import { printJson } from "../../printer.js"; +import { booleanOption, dryRunOption, stringOption } from "../../parse/parser.js"; +import { printJson } from "../../output/printer.js"; import type { ParsedArgs } from "../../types.js"; /** diff --git a/src/cli/commands/corps/bindings.ts b/src/cli/commands/corps/bindings.ts index d9d31d5..6c464ad 100644 --- a/src/cli/commands/corps/bindings.ts +++ b/src/cli/commands/corps/bindings.ts @@ -1,8 +1,8 @@ import { updateCorpConfig } from "../../../core/config/loader.js"; import { selectCorp } from "../../helpers.js"; import { confirmationRequired, usageError } from "../../../core/errors.js"; -import { booleanOption, stringOption } from "../../parser.js"; -import { printJson } from "../../printer.js"; +import { booleanOption, stringOption } from "../../parse/parser.js"; +import { printJson } from "../../output/printer.js"; import type { ParsedArgs } from "../../types.js"; export async function handleCorpBindings( diff --git a/src/cli/commands/corps/onboarding.ts b/src/cli/commands/corps/onboarding.ts index cfe9c95..11e0efd 100644 --- a/src/cli/commands/corps/onboarding.ts +++ b/src/cli/commands/corps/onboarding.ts @@ -23,8 +23,8 @@ import { optionalString, requiredString, stringOption -} from "../../parser.js"; -import { printJson } from "../../printer.js"; +} from "../../parse/parser.js"; +import { printJson } from "../../output/printer.js"; import type { ParsedArgs } from "../../types.js"; import { maskCellphone } from "./shared.js"; @@ -264,7 +264,6 @@ async function addSealCorp(input: Record) { tenantName: optionalString(input, "tenantName"), corpId: optionalString(input, "corpId"), staffId: optionalString(input, "staffId"), - provider: optionalString(input, "provider"), force: input.force === true, verify: input.verify === false, overwrite: input.overwrite === true, @@ -339,7 +338,6 @@ async function addLinkAsHoseCorp(link: string, name: string | undefined, overwri printJson({ dryRun: true, kind: "hose", - provider: "hose", corpId: result.corpId, corpName: result.corpName, baseUrl: result.baseUrl, @@ -394,7 +392,6 @@ export async function extractKeysFromLinkAction(link: string, options: { reveal? if (!reveal) console.error("ℹ️ [合思子域提权] 成功提取合思 (Hose) OpenAPI 密钥。接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文;附加 --save 可将临时会话提权并持久化为标准合思企业。\n"); else console.error("⚠️ [合思子域提权] 正在以明文展示合思 (Hose) appSecurity 接入密码,请妥善保管敏感凭据。\n"); printJson({ - provider: "hose", capability: "privilege-elevation", corpId: result.corpId, corpName: result.corpName ?? result.corpId, @@ -412,12 +409,11 @@ export async function showCorpKeysAction(targetCorpId: string | undefined, optio throw new CliError(`【合思子域专享能力】当前企业「${corp.name}」(id: ${corp.id}) 为原生 Seal (${corp.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。\n` + "OpenAPI 密钥查询与提权能力专属于合思生态租户(用于从合思协助链接或合思凭据中提取开发者密钥提升权限等级),非合思渠道企业不支持此能力。", 2); } - const appKey = corp.source.appKey ?? corp.source.key; - const appSecurity = corp.source.appSecurity ?? corp.source.password; + const appKey = corp.source.appKey; + const appSecurity = corp.source.appSecurity; if (!reveal) console.error("💡 [合思子域] 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文。\n"); else console.error("⚠️ [合思子域] 正在以明文展示合思 appSecurity 接入密码,请妥善保管敏感凭据。\n"); printJson({ - provider: "hose", capability: "privilege-elevation", corpId: corp.id, corpName: corp.name, diff --git a/src/cli/commands/corps/overview.ts b/src/cli/commands/corps/overview.ts index dd3b687..5c93efb 100644 --- a/src/cli/commands/corps/overview.ts +++ b/src/cli/commands/corps/overview.ts @@ -11,8 +11,8 @@ import { } from "../../../core/stats/usage-tracker.js"; import type { CorpEnvironment } from "../../../core/config/types.js"; import { confirmationRequired, usageError } from "../../../core/errors.js"; -import { booleanOption, dryRunOption, numberOption, stringOption } from "../../parser.js"; -import { printJson } from "../../printer.js"; +import { booleanOption, dryRunOption, numberOption, stringOption } from "../../parse/parser.js"; +import { printJson } from "../../output/printer.js"; import type { ParsedArgs } from "../../types.js"; export async function handleCorpOverview( @@ -94,7 +94,6 @@ export async function handleCorpOverview( active: item.active ?? true, environment: item.environment ?? "production", sourceType: item.source.type, - provider: (item.source as any).provider ?? item.source.type, staffId: item.source.staffId, testCorpId: item.testCorpId, prodCorpId: item.prodCorpId, @@ -147,7 +146,6 @@ export async function handleCorpOverview( active: corp.active ?? true, environment: corp.environment ?? "production", sourceType: corp.source.type, - provider: (corp.source as any).provider ?? corp.source.type, staffId: corp.source.staffId, testCorpId: corp.testCorpId, prodCorpId: corp.prodCorpId diff --git a/src/cli/commands/corps/shared.ts b/src/cli/commands/corps/shared.ts index 403798a..3a74b79 100644 --- a/src/cli/commands/corps/shared.ts +++ b/src/cli/commands/corps/shared.ts @@ -20,15 +20,14 @@ export function resolveCorpSealUrl(corp: CorpConfig): string | undefined { export function formatSafeSourceDetail(source: SealSource) { if (source.type === "hose") { - const key = source.appKey ?? source.key; + const key = source.appKey; return { type: "hose", - provider: source.provider ?? "hosecloud", domain: source.domain, corpId: source.corpId, staffId: source.staffId, appKey: maskSecret(key), - hasAppSecurity: Boolean(source.appSecurity ?? source.password), + hasAppSecurity: Boolean(source.appSecurity), hasCloseToken: Boolean(source.closeToken), closeTokenExpiresIn: source.closeToken ? source.expiresIn : undefined, closeTokenExpiresAt: source.closeToken ? source.expiresAt : undefined, @@ -40,7 +39,6 @@ export function formatSafeSourceDetail(source: SealSource) { if (source.type === "seal") { return { type: "seal", - provider: source.provider ?? "seal", tenantId: source.tenantId, tenantSlug: source.tenantSlug, tenantName: source.tenantName, diff --git a/src/cli/commands/corps/sync.ts b/src/cli/commands/corps/sync.ts index 80c44de..22f7388 100644 --- a/src/cli/commands/corps/sync.ts +++ b/src/cli/commands/corps/sync.ts @@ -4,8 +4,8 @@ import { syncTestEnterprise } from "../../../domains/seal/testing/sync.js"; import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/replay/webhook.js"; import { selectCorp } from "../../helpers.js"; import { CliError, confirmationRequired, usageError } from "../../../core/errors.js"; -import { booleanOption, numberOption, stringOption } from "../../parser.js"; -import { outputOptions, printJson } from "../../printer.js"; +import { booleanOption, numberOption, stringOption } from "../../parse/parser.js"; +import { outputOptions, printJson } from "../../output/printer.js"; import type { ParsedArgs } from "../../types.js"; export { buildTestHosecloudOutboundName } from "../../../domains/seal/testing/sync.js"; diff --git a/src/cli/commands/corps/tenant-active.test.ts b/src/cli/commands/corps/tenant-active.test.ts index 353ea92..02ebbdf 100644 --- a/src/cli/commands/corps/tenant-active.test.ts +++ b/src/cli/commands/corps/tenant-active.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { runCli } from "../../runner.js"; +import { runCli } from "../../run/runner.js"; import { selectCorp } from "../../helpers.js"; import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from "../../../core/config/loader.js"; import { resolveCorpConfig } from "../../../core/config/manager.js"; diff --git a/src/cli/commands/deploy.test.ts b/src/cli/commands/deploy.test.ts index 43cd6ea..c595169 100644 --- a/src/cli/commands/deploy.test.ts +++ b/src/cli/commands/deploy.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import type { KyInstance } from "ky"; import { CorpConfigSchema } from "../../core/config/types.js"; -import { parseArgs } from "../parser.js"; +import { parseArgs } from "../parse/parser.js"; import { runCapabilityResult } from "../helpers.js"; import { handleDeployCommand } from "./deploy.js"; diff --git a/src/cli/commands/deploy.ts b/src/cli/commands/deploy.ts index f69b140..3ffe4f2 100644 --- a/src/cli/commands/deploy.ts +++ b/src/cli/commands/deploy.ts @@ -2,8 +2,8 @@ import { readFileSync } from "node:fs"; import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { runCapability } from "../helpers.js"; -import { booleanOption, jsonObject, numberOption, stringOption } from "../parser.js"; -import { outputOptions } from "../printer.js"; +import { booleanOption, jsonObject, numberOption, stringOption } from "../parse/parser.js"; +import { outputOptions } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; import * as api from "../../domains/seal/api.js"; import { listHoseIntegrations } from "../../domains/seal/outbound/push.js"; diff --git a/src/cli/commands/doctor.test.ts b/src/cli/commands/doctor.test.ts index 97ec26d..6cb4cdb 100644 --- a/src/cli/commands/doctor.test.ts +++ b/src/cli/commands/doctor.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { runCli } from "../runner.js"; +import { runCli } from "../run/runner.js"; describe("seal-use doctor CLI", () => { test("runs full system diagnosis and outputs JSON to stdout and dashboard to stderr", async () => { diff --git a/src/cli/commands/doctor.ts b/src/cli/commands/doctor.ts index e5114be..787f14b 100644 --- a/src/cli/commands/doctor.ts +++ b/src/cli/commands/doctor.ts @@ -1,7 +1,7 @@ import { diagnoseSystem, formatDoctorDashboard } from "../../core/doctor/diagnose.js"; import { getEmbeddedGuideMarkdown } from "../../core/doctor/knowledge.js"; -import { booleanOption } from "../parser.js"; -import { printJson } from "../printer.js"; +import { booleanOption } from "../parse/parser.js"; +import { printJson } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; export async function handleDoctorCommand( @@ -28,7 +28,7 @@ export async function handleDoctorCommand( // 2.5. Output auth session diagnostics (seal-use doctor auth) if (subAction === "auth") { const { selectCorp } = await import("../helpers.js"); - const { stringOption } = await import("../parser.js"); + const { stringOption } = await import("../parse/parser.js"); const { handleAuthCommand } = await import("./auth.js"); const corpSelector = stringOption(args.options.corp) ?? @@ -43,7 +43,7 @@ export async function handleDoctorCommand( if (subAction === "tenant" || subAction === "corp" || subAction === "enterprise") { const { selectCorp } = await import("../helpers.js"); const { createSealClient } = await import("../../core/http/factory.js"); - const { stringOption } = await import("../parser.js"); + const { stringOption } = await import("../parse/parser.js"); const { diagnoseTenantContract, formatTenantDoctorDashboard } = await import("../../domains/seal/doctor/tenant-diagnose.js"); const corpSelector = diff --git a/src/cli/commands/documents.test.ts b/src/cli/commands/documents.test.ts index f9f436b..0ba430f 100644 --- a/src/cli/commands/documents.test.ts +++ b/src/cli/commands/documents.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test" import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" -import { runCli } from "../runner.js" +import { runCli } from "../run/runner.js" const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]])) diff --git a/src/cli/commands/documents.ts b/src/cli/commands/documents.ts index d5d2174..8065b46 100644 --- a/src/cli/commands/documents.ts +++ b/src/cli/commands/documents.ts @@ -12,8 +12,8 @@ import { numberOption, splitOption, stringOption -} from "../parser.js"; -import { outputOptions, printJson } from "../printer.js"; +} from "../parse/parser.js"; +import { outputOptions, printJson } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; function contentFilePath(args: ParsedArgs): string | undefined { diff --git a/src/cli/commands/dry-run-gates.test.ts b/src/cli/commands/dry-run-gates.test.ts index 4e0857a..62ca209 100644 --- a/src/cli/commands/dry-run-gates.test.ts +++ b/src/cli/commands/dry-run-gates.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { runCli } from "../runner.js"; +import { runCli } from "../run/runner.js"; /** * Mutation-preview (`--dry-run`) gates for commands that previously mutated diff --git a/src/cli/commands/expenses.test.ts b/src/cli/commands/expenses.test.ts index 4ef964b..8aa27cf 100644 --- a/src/cli/commands/expenses.test.ts +++ b/src/cli/commands/expenses.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test" import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" -import { runCli } from "../runner.js" +import { runCli } from "../run/runner.js" const envKeys = ["SEAL_USE_CONFIG_FILE", "SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]])) diff --git a/src/cli/commands/expenses.ts b/src/cli/commands/expenses.ts index 25cdccd..ca57230 100644 --- a/src/cli/commands/expenses.ts +++ b/src/cli/commands/expenses.ts @@ -3,8 +3,8 @@ import type { createSealClient } from "../../core/http/factory.js" import { usageError } from "../../core/errors.js" import { ExpenseLookupError } from "../../domains/seal/expenses/lookup.js" import { runCapabilityResult } from "../helpers.js" -import { numberOption, stringOption } from "../parser.js" -import { outputOptions, printJson } from "../printer.js" +import { numberOption, stringOption } from "../parse/parser.js" +import { outputOptions, printJson } from "../output/printer.js" import type { ParsedArgs } from "../types.js" export async function handleExpensesCommand(action: string | undefined, client: Awaited>, corp: CorpConfig, args: ParsedArgs) { diff --git a/src/cli/commands/hose-ebot.test.ts b/src/cli/commands/hose-ebot.test.ts index 86e4733..0bbe8fe 100644 --- a/src/cli/commands/hose-ebot.test.ts +++ b/src/cli/commands/hose-ebot.test.ts @@ -5,7 +5,7 @@ import { join } from "node:path"; import type { KyInstance } from "ky"; import { CorpConfigSchema } from "../../core/config/types.js"; import { classifyCliError } from "../../core/errors.js"; -import { parseArgs } from "../parser.js"; +import { parseArgs } from "../parse/parser.js"; import { handleHoseEbotCommand } from "./hose-ebot.js"; const ORIGINAL_ENV = { diff --git a/src/cli/commands/hose-ebot.ts b/src/cli/commands/hose-ebot.ts index c76c9d5..98e8733 100644 --- a/src/cli/commands/hose-ebot.ts +++ b/src/cli/commands/hose-ebot.ts @@ -2,8 +2,8 @@ import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { CliError } from "../../core/errors.js"; import { runCapability } from "../helpers.js"; -import { booleanOption, numberOption, stringOption } from "../parser.js"; -import { outputOptions } from "../printer.js"; +import { booleanOption, numberOption, stringOption } from "../parse/parser.js"; +import { outputOptions } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; const USAGE = diff --git a/src/cli/commands/invoices.ts b/src/cli/commands/invoices.ts index f8e280b..2f48cac 100644 --- a/src/cli/commands/invoices.ts +++ b/src/cli/commands/invoices.ts @@ -2,8 +2,8 @@ import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { traceInvoice } from "../../domains/seal/approval-runs/invoices.js"; import { runCapability } from "../helpers.js"; -import { booleanOption, numberOption, stringOption } from "../parser.js"; -import { outputOptions, printJson } from "../printer.js"; +import { booleanOption, numberOption, stringOption } from "../parse/parser.js"; +import { outputOptions, printJson } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; export async function handleInvoicesCommand( diff --git a/src/cli/commands/langfuse.ts b/src/cli/commands/langfuse.ts index 77e184e..d7f7491 100644 --- a/src/cli/commands/langfuse.ts +++ b/src/cli/commands/langfuse.ts @@ -1,7 +1,7 @@ import { validationError, usageError } from "../../core/errors.js"; -import { booleanOption, numberOption, splitOption, stringOption } from "../parser.js"; +import { booleanOption, numberOption, splitOption, stringOption } from "../parse/parser.js"; import { runLangfuseCapability } from "../helpers.js"; -import { outputOptions } from "../printer.js"; +import { outputOptions } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; /** diff --git a/src/cli/commands/llm.ts b/src/cli/commands/llm.ts index 96eddc3..b8265b4 100644 --- a/src/cli/commands/llm.ts +++ b/src/cli/commands/llm.ts @@ -2,7 +2,7 @@ import { usageError } from "../../core/errors.js"; import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { runCapability } from "../helpers.js"; -import { outputOptions } from "../printer.js"; +import { outputOptions } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; export async function handleLlmCommand( diff --git a/src/cli/commands/mcp.ts b/src/cli/commands/mcp.ts index 789ec86..11b6979 100644 --- a/src/cli/commands/mcp.ts +++ b/src/cli/commands/mcp.ts @@ -1,4 +1,4 @@ -import { printJson } from "../printer.js"; +import { printJson } from "../output/printer.js"; export async function handleMcpCommand(action: string | undefined) { if (action === "config" || action === "json") { diff --git a/src/cli/commands/permissions.ts b/src/cli/commands/permissions.ts index 00ee8fa..bad054a 100644 --- a/src/cli/commands/permissions.ts +++ b/src/cli/commands/permissions.ts @@ -2,7 +2,7 @@ import { usageError } from "../../core/errors.js"; import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { runCapability } from "../helpers.js"; -import { outputOptions } from "../printer.js"; +import { outputOptions } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; export async function handlePermissionsCommand( diff --git a/src/cli/commands/preference.ts b/src/cli/commands/preference.ts index 15598f0..10cb493 100644 --- a/src/cli/commands/preference.ts +++ b/src/cli/commands/preference.ts @@ -3,8 +3,8 @@ import { readFileSync } from "node:fs"; import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { runCapability } from "../helpers.js"; -import { booleanOption, jsonObject, stringOption } from "../parser.js"; -import { outputOptions } from "../printer.js"; +import { booleanOption, jsonObject, stringOption } from "../parse/parser.js"; +import { outputOptions } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; export async function handlePreferenceCommand( diff --git a/src/cli/commands/probe.ts b/src/cli/commands/probe.ts index 4b2b3f8..a1536cd 100644 --- a/src/cli/commands/probe.ts +++ b/src/cli/commands/probe.ts @@ -1,6 +1,6 @@ import { runProbe } from "../../probe.js"; -import { stringOption } from "../parser.js"; -import { printJson } from "../printer.js"; +import { stringOption } from "../parse/parser.js"; +import { printJson } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; export async function handleProbeCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) { diff --git a/src/cli/commands/report-review-cli.test.ts b/src/cli/commands/report-review-cli.test.ts index 35ebb99..70803b7 100644 --- a/src/cli/commands/report-review-cli.test.ts +++ b/src/cli/commands/report-review-cli.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { runCli } from "../runner.js"; +import { runCli } from "../run/runner.js"; import { saveCorpConfig } from "../../core/config/repository.js"; import { closeReviewsDb, @@ -29,8 +29,7 @@ const testCorp: CorpConfig = { staffId: "u-triage", corpId: "corp-triage-test", tenantId: "t-triage", - tenantSlug: "triage", - provider: "seal" + tenantSlug: "triage" }, auth: { refreshTtl: 300 } }; diff --git a/src/cli/commands/report.ts b/src/cli/commands/report.ts index b8c1ec0..2a4fb90 100644 --- a/src/cli/commands/report.ts +++ b/src/cli/commands/report.ts @@ -3,8 +3,8 @@ import { resolve } from "node:path"; import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { runCapabilityResult } from "../helpers.js"; -import { booleanOption, numberOption, stringOption } from "../parser.js"; -import { outputOptions, printJson } from "../printer.js"; +import { booleanOption, numberOption, stringOption } from "../parse/parser.js"; +import { outputOptions, printJson } from "../output/printer.js"; import { CliError, usageError } from "../../core/errors.js"; import { isCorpDisabledError } from "../../core/config/active.js"; import { diff --git a/src/cli/commands/rules.ts b/src/cli/commands/rules.ts index 55136fa..33ffeb7 100644 --- a/src/cli/commands/rules.ts +++ b/src/cli/commands/rules.ts @@ -20,13 +20,13 @@ import { ruleVersionSearchOptions, splitOption, stringOption -} from "../parser.js"; +} from "../parse/parser.js"; import { outputOptions, printJson, protectLargeRuleListOutput, RULE_SUMMARY_FIELDS -} from "../printer.js"; +} from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; function readDescriptionInput(args: ParsedArgs, payload: Record): string | undefined { diff --git a/src/cli/commands/simulation.test.ts b/src/cli/commands/simulation.test.ts index c08509f..6804db2 100644 --- a/src/cli/commands/simulation.test.ts +++ b/src/cli/commands/simulation.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { runCli } from "../runner.js"; +import { runCli } from "../run/runner.js"; const ORIGINAL_ENV = { enterprises: process.env.SEAL_USE_ENTERPRISES_DIR, diff --git a/src/cli/commands/simulation.ts b/src/cli/commands/simulation.ts index 69e4350..9e23ef9 100644 --- a/src/cli/commands/simulation.ts +++ b/src/cli/commands/simulation.ts @@ -10,8 +10,8 @@ import { numberOption, splitOption, stringOption -} from "../parser.js"; -import { outputOptions, printJson } from "../printer.js"; +} from "../parse/parser.js"; +import { outputOptions, printJson } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; export async function handleSimulationCommand( diff --git a/src/cli/commands/skill.ts b/src/cli/commands/skill.ts index 73aa245..39c4093 100644 --- a/src/cli/commands/skill.ts +++ b/src/cli/commands/skill.ts @@ -10,11 +10,11 @@ import { getDefaultGlobalSkillDir, getSkillContent, installSkillFiles -} from "../../core/embedded-skill.js"; -import { booleanOption, stringOption } from "../parser.js"; -import { printJson } from "../printer.js"; +} from "../../core/skill/embedded-skill.js"; +import { booleanOption, stringOption } from "../parse/parser.js"; +import { printJson } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; -import { getSkillVersionStatus } from "../../core/skill-version.js"; +import { getSkillVersionStatus } from "../../core/skill/skill-version.js"; import { VERSION } from "../../version.js"; export function handleSkillCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) { diff --git a/src/cli/commands/source.ts b/src/cli/commands/source.ts index aa1ec86..befc448 100644 --- a/src/cli/commands/source.ts +++ b/src/cli/commands/source.ts @@ -1,7 +1,7 @@ import { usageError } from "../../core/errors.js"; import type { CorpConfig } from "../../core/config/types.js"; import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/enterprise/source.js"; -import { printJson } from "../printer.js"; +import { printJson } from "../output/printer.js"; export async function handleSourceCommand(action: string | undefined, corp: CorpConfig) { if (action === "config") { diff --git a/src/cli/commands/test.test.ts b/src/cli/commands/test.test.ts index 1681afe..947e65e 100644 --- a/src/cli/commands/test.test.ts +++ b/src/cli/commands/test.test.ts @@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { CorpConfig } from "../../core/config/types.js"; -import { runCli } from "../runner.js"; +import { runCli } from "../run/runner.js"; const ORIGINAL_ENV = { enterprises: process.env.SEAL_USE_ENTERPRISES_DIR, diff --git a/src/cli/commands/test.ts b/src/cli/commands/test.ts index 4ced3b5..1c162c8 100644 --- a/src/cli/commands/test.ts +++ b/src/cli/commands/test.ts @@ -1,7 +1,7 @@ import { CliError } from "../../core/errors.js"; import { selectCorp } from "../helpers.js"; -import { booleanOption, numberOption, stringOption } from "../parser.js"; -import { printJson } from "../printer.js"; +import { booleanOption, numberOption, stringOption } from "../parse/parser.js"; +import { printJson } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; import { createSealClient } from "../../core/http/factory.js"; import { diff --git a/src/cli/commands/update.test.ts b/src/cli/commands/update.test.ts index 337f919..52811b6 100644 --- a/src/cli/commands/update.test.ts +++ b/src/cli/commands/update.test.ts @@ -191,7 +191,7 @@ describe("update command bgSave and cache integration", () => { const { mkdtempSync, rmSync } = await import("node:fs"); const { tmpdir } = await import("node:os"); const { handleUpdateCommand } = await import("./update.js"); - const { loadUpdateCache, UPDATE_CACHE_FILE_ENV } = await import("../../core/update-cache.js"); + const { loadUpdateCache, UPDATE_CACHE_FILE_ENV } = await import("../../core/update/update-cache.js"); const tempDir = mkdtempSync(join(tmpdir(), "seal-use-bg-save-test-")); const tempCacheFile = join(tempDir, "update-cache.json"); diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.ts index 47d1dfb..5600bb8 100644 --- a/src/cli/commands/update.ts +++ b/src/cli/commands/update.ts @@ -2,12 +2,12 @@ import { accessSync, chmodSync, constants, existsSync, lstatSync, mkdirSync, rea import { homedir } from "node:os"; import { basename, dirname, join } from "node:path"; import { spawnSync } from "node:child_process"; -import { isCompiledBinary } from "../../core/runtime.js"; +import { isCompiledBinary } from "../../core/util/runtime.js"; import { normalizeBeijingIso } from "../../core/config/timestamps.js"; -import { readInstalledSkillVersion } from "../../core/embedded-skill.js"; -import { saveUpdateCache } from "../../core/update-cache.js"; +import { readInstalledSkillVersion } from "../../core/skill/embedded-skill.js"; +import { saveUpdateCache } from "../../core/update/update-cache.js"; import { VERSION, IS_RELEASE } from "../../version.js"; -import { printJson } from "../printer.js"; +import { printJson } from "../output/printer.js"; import { validationError } from "../../core/errors.js"; import type { CliRuntime } from "../types.js"; @@ -1043,7 +1043,7 @@ function extractZip(archivePath: string, targetDir: string, platform: string): s return resolveExtractedBinary(targetDir, platform, archivePath); } -import { compareSemVer, isNewerVersion } from "../../core/semver.js"; +import { compareSemVer, isNewerVersion } from "../../core/util/semver.js"; // Re-exported for tests and callers that historically imported from here. export { compareSemVer, isNewerVersion }; diff --git a/src/cli/commands/users.test.ts b/src/cli/commands/users.test.ts index 762294f..a40551c 100644 --- a/src/cli/commands/users.test.ts +++ b/src/cli/commands/users.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { runCli } from "../runner.js"; +import { runCli } from "../run/runner.js"; const ORIGINAL_ENV = { enterprises: process.env.SEAL_USE_ENTERPRISES_DIR, diff --git a/src/cli/commands/users.ts b/src/cli/commands/users.ts index e631f21..2b62d4e 100644 --- a/src/cli/commands/users.ts +++ b/src/cli/commands/users.ts @@ -2,8 +2,8 @@ import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { confirmationRequired, usageError } from "../../core/errors.js"; import { runCapability } from "../helpers.js"; -import { booleanOption, dryRunOption, parseDelegationExpireHours, stringOption } from "../parser.js"; -import { outputOptions } from "../printer.js"; +import { booleanOption, dryRunOption, parseDelegationExpireHours, stringOption } from "../parse/parser.js"; +import { outputOptions } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; export async function handleUsersCommand( diff --git a/src/cli/commands/webhook-replay.test.ts b/src/cli/commands/webhook-replay.test.ts index e089027..beaf871 100644 --- a/src/cli/commands/webhook-replay.test.ts +++ b/src/cli/commands/webhook-replay.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { runCli } from "../runner.js"; +import { runCli } from "../run/runner.js"; const ORIGINAL_ENV = { enterprises: process.env.SEAL_USE_ENTERPRISES_DIR, diff --git a/src/cli/commands/webhook-resource-pack.test.ts b/src/cli/commands/webhook-resource-pack.test.ts index a67fc3b..022ea92 100644 --- a/src/cli/commands/webhook-resource-pack.test.ts +++ b/src/cli/commands/webhook-resource-pack.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { runCli } from "../runner.js"; +import { runCli } from "../run/runner.js"; import { exportApprovalRunsToResourcePack } from "../../domains/seal/material-pack/export.js"; import { previewResourcePack } from "../../domains/seal/material-pack/service.js"; diff --git a/src/cli/commands/webhook.ts b/src/cli/commands/webhook.ts index 37d1d37..832c32a 100644 --- a/src/cli/commands/webhook.ts +++ b/src/cli/commands/webhook.ts @@ -28,8 +28,8 @@ import { stringOption, webhookRateOption, webhookShowSecretOption -} from "../parser.js"; -import { outputOptions, printJson } from "../printer.js"; +} from "../parse/parser.js"; +import { outputOptions, printJson } from "../output/printer.js"; import type { ParsedArgs } from "../types.js"; import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js"; import { CliError, confirmationRequired, usageError, validationError } from "../../core/errors.js"; diff --git a/src/cli/docs-commands.test.ts b/src/cli/help/docs-commands.test.ts similarity index 96% rename from src/cli/docs-commands.test.ts rename to src/cli/help/docs-commands.test.ts index 96fb31d..520f549 100644 --- a/src/cli/docs-commands.test.ts +++ b/src/cli/help/docs-commands.test.ts @@ -1,8 +1,8 @@ import { describe, expect, test } from "bun:test"; import { readFileSync, readdirSync } from "node:fs"; import { join } from "node:path"; -import { parseArgs } from "./parser.js"; -import { KNOWN_AREAS, UPDATE_ALIASES } from "./runner.js"; +import { parseArgs } from "../parse/parser.js"; +import { KNOWN_AREAS, UPDATE_ALIASES } from "../run/runner.js"; /** * Documentation cross-check: every command a maintained doc shows a reader must @@ -21,7 +21,7 @@ import { KNOWN_AREAS, UPDATE_ALIASES } from "./runner.js"; * like "the seal-use wrapped API" is not a command and is not matched. */ -const REPO_ROOT = join(import.meta.dir, "..", ".."); +const REPO_ROOT = join(import.meta.dir, "..", "..", ".."); const DOC_FILES = [ "README.md", diff --git a/src/cli/help.test.ts b/src/cli/help/help.test.ts similarity index 99% rename from src/cli/help.test.ts rename to src/cli/help/help.test.ts index 575ae33..337e7d1 100644 --- a/src/cli/help.test.ts +++ b/src/cli/help/help.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; import { extractHelpRequest, HELP_REGISTRY, renderHelp } from "./help.js"; -import { KNOWN_AREAS, runCli } from "./runner.js"; +import { KNOWN_AREAS, runCli } from "../run/runner.js"; describe("extractHelpRequest", () => { test("detects global help from empty command or help option", () => { diff --git a/src/cli/help.ts b/src/cli/help/help.ts similarity index 99% rename from src/cli/help.ts rename to src/cli/help/help.ts index cfaecb8..6891a3d 100644 --- a/src/cli/help.ts +++ b/src/cli/help/help.ts @@ -1,6 +1,6 @@ -import { normalizeCliArea } from "./area-aliases.js"; -import type { ParsedArgs } from "./types.js"; -import { usageError } from "../core/errors.js"; +import { normalizeCliArea } from "../parse/area-aliases.js"; +import type { ParsedArgs } from "../types.js"; +import { usageError } from "../../core/errors.js"; export interface CommandOptionHelp { flag: string; diff --git a/src/cli/naming-charter.test.ts b/src/cli/help/naming-charter.test.ts similarity index 96% rename from src/cli/naming-charter.test.ts rename to src/cli/help/naming-charter.test.ts index 123a391..fb7819c 100644 --- a/src/cli/naming-charter.test.ts +++ b/src/cli/help/naming-charter.test.ts @@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test"; import { readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { HELP_REGISTRY } from "./help.js"; -import { parseArgs } from "./parser.js"; +import { parseArgs } from "../parse/parser.js"; /** * Naming charter guard (.agents/rules/cli-protocol.md "Naming Charter"). @@ -110,20 +110,20 @@ describe("naming charter: canonical accept-sets are wired in commands", () => { const read = (path: string) => readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf8"); test("webhook resource-pack export reads --out and --downloads (no silent ignore)", () => { - const source = read("./commands/webhook.ts"); + const source = read("../commands/webhook.ts"); expect(source).toContain("stringOption(args.options.out) ??"); expect(source).toContain("booleanOption(args.options.downloads) ??"); expect(source).toContain("booleanOption(args.options.download) ??"); }); test("webhook secret reveal accepts --reveal alongside legacy --show-secret", () => { - const source = read("./parser.ts"); + const source = read("../parse/parser.ts"); expect(source).toContain("booleanOption(options.reveal)"); expect(source).toContain('booleanOption(options["show-secret"])'); }); test("approval-runs reads canonical --start-date/--end-date everywhere", () => { - const source = read("./commands/approval-runs.ts"); + const source = read("../commands/approval-runs.ts"); const startDateReads = source.match(/args\.options\["start-date"\]/g)?.length ?? 0; const endDateReads = source.match(/args\.options\["end-date"\]/g)?.length ?? 0; expect(startDateReads).toBeGreaterThanOrEqual(3); diff --git a/src/cli/helpers.ts b/src/cli/helpers.ts index 2e34d92..0927776 100644 --- a/src/cli/helpers.ts +++ b/src/cli/helpers.ts @@ -7,7 +7,7 @@ import { createLangfuseService, findLangfuseCapability } from "../domains/langfu import type { LangfuseService } from "../domains/langfuse/service.js"; import { validationError } from "../core/errors.js"; import type { CorpConfig, GlobalConfig } from "../core/config/types.js"; -import { printJson } from "./printer.js"; +import { printJson } from "./output/printer.js"; import type { OutputOptions } from "./types.js"; export function selectCorp(corpId?: string, options: { allowDisabled?: boolean } = {}): CorpConfig { diff --git a/src/cli/printer.ts b/src/cli/output/printer.ts similarity index 90% rename from src/cli/printer.ts rename to src/cli/output/printer.ts index 9f563b5..1ba4a20 100644 --- a/src/cli/printer.ts +++ b/src/cli/output/printer.ts @@ -1,8 +1,8 @@ import { writeFileSync } from "node:fs"; -import { booleanOption, stringOption } from "./parser.js"; -import { PayloadTooLargeError } from "../core/errors.js"; -import { redactSensitiveText } from "../core/redact.js"; -import type { OutputOptions } from "./types.js"; +import { booleanOption, stringOption } from "../parse/parser.js"; +import { PayloadTooLargeError } from "../../core/errors.js"; +import { redactSensitiveText } from "../../core/util/redact.js"; +import type { OutputOptions } from "../types.js"; export { redactSensitiveText }; @@ -68,7 +68,7 @@ export function outputOptions(options: Record): Output }; } -import { renderHelp } from "./help.js"; +import { renderHelp } from "../help/help.js"; export function printHelp(target: string[] = []) { console.log(renderHelp(target)); diff --git a/src/cli/area-aliases.test.ts b/src/cli/parse/area-aliases.test.ts similarity index 98% rename from src/cli/area-aliases.test.ts rename to src/cli/parse/area-aliases.test.ts index 904cb1c..9068a70 100644 --- a/src/cli/area-aliases.test.ts +++ b/src/cli/parse/area-aliases.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; import { AREA_ALIASES, UPDATE_ALIASES, normalizeCliArea } from "./area-aliases.js"; -import { KNOWN_AREAS } from "./runner.js"; +import { KNOWN_AREAS } from "../run/runner.js"; /** * Drift guard for the shared alias table. diff --git a/src/cli/area-aliases.ts b/src/cli/parse/area-aliases.ts similarity index 100% rename from src/cli/area-aliases.ts rename to src/cli/parse/area-aliases.ts diff --git a/src/cli/parser.test.ts b/src/cli/parse/parser.test.ts similarity index 99% rename from src/cli/parser.test.ts rename to src/cli/parse/parser.test.ts index ba039cf..bd5f601 100644 --- a/src/cli/parser.test.ts +++ b/src/cli/parse/parser.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { HELP_REGISTRY } from "./help.js"; +import { HELP_REGISTRY } from "../help/help.js"; import { booleanOption, BOOLEAN_FLAGS, diff --git a/src/cli/parser.ts b/src/cli/parse/parser.ts similarity index 98% rename from src/cli/parser.ts rename to src/cli/parse/parser.ts index 2e849da..a1cf947 100644 --- a/src/cli/parser.ts +++ b/src/cli/parse/parser.ts @@ -1,8 +1,8 @@ -import type { WebhookMode } from "../domains/seal/types.js"; -import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js"; -import type { ParsedArgs } from "./types.js"; -import { type DurationToken, EXPIRE_UNITS, expireSeconds, tokenizeDuration } from "../core/duration.js"; -import { usageError, validationError } from "../core/errors.js"; +import type { WebhookMode } from "../../domains/seal/types.js"; +import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js"; +import type { ParsedArgs } from "../types.js"; +import { type DurationToken, EXPIRE_UNITS, expireSeconds, tokenizeDuration } from "../../core/util/duration.js"; +import { usageError, validationError } from "../../core/errors.js"; /** * Flag metadata for argv parsing, derived from how the code reads each flag: diff --git a/src/cli/tokenize.ts b/src/cli/parse/tokenize.ts similarity index 97% rename from src/cli/tokenize.ts rename to src/cli/parse/tokenize.ts index f787e7b..7f3d12c 100644 --- a/src/cli/tokenize.ts +++ b/src/cli/parse/tokenize.ts @@ -3,7 +3,7 @@ * reach the CLI intact. Lives in its own module because both the MCP server and the HTTP routes * need it; importing it from the server entry would make the CLI graph circular. */ -import { usageError } from "../core/errors.js"; +import { usageError } from "../../core/errors.js"; export function tokenizeCommand(command: string): string[] { const tokens: string[] = []; let token = ""; diff --git a/src/cli/read-only.test.ts b/src/cli/run/read-only.test.ts similarity index 97% rename from src/cli/read-only.test.ts rename to src/cli/run/read-only.test.ts index 30be9e7..60f8990 100644 --- a/src/cli/read-only.test.ts +++ b/src/cli/run/read-only.test.ts @@ -1,9 +1,9 @@ import { describe, expect, test } from "bun:test"; import { readFileSync, readdirSync } from "node:fs"; import { join } from "node:path"; -import { HELP_REGISTRY } from "./help.js"; +import { HELP_REGISTRY } from "../help/help.js"; import { KNOWN_AREAS } from "./runner.js"; -import { SEAL_MUTATING_CAPABILITIES, SEAL_READ_ONLY_CAPABILITIES, sealCapabilities } from "../domains/seal/capabilities.js"; +import { SEAL_MUTATING_CAPABILITIES, SEAL_READ_ONLY_CAPABILITIES, sealCapabilities } from "../../domains/seal/capabilities.js"; import { isReadOnlyCliCommand, listReadOnlyCommands } from "./read-only.js"; describe("CLI read-only classification", () => { @@ -177,14 +177,14 @@ describe("CLI allow-list agrees with the tool registry", () => { ]); test("every CLI verb dispatching to a read-only tool is itself read-only, and mutating tools are not read-only", () => { - const files = readdirSync(join(import.meta.dir, "commands")).filter( + const files = readdirSync(join(import.meta.dir, "../commands")).filter( (f) => f.endsWith(".ts") && !f.endsWith(".test.ts") ); const pairs: Array<{ area: string; action: string; tool: string }> = []; for (const file of files) { const area = file.replace(/\.ts$/, ""); - const source = readFileSync(join(import.meta.dir, "commands", file), "utf8"); + const source = readFileSync(join(import.meta.dir, "../commands", file), "utf8"); const pattern = /if\s*\(\s*action === "([a-z0-9-]+)"(?:(?!\bif\s*\(\s*action\b)[\s\S]){0,600}?runCapability(?:Result)?\(\s*"(seal[A-Z][A-Za-z0-9]*)"/g; let match; diff --git a/src/cli/read-only.ts b/src/cli/run/read-only.ts similarity index 98% rename from src/cli/read-only.ts rename to src/cli/run/read-only.ts index bcb3c25..43d4643 100644 --- a/src/cli/read-only.ts +++ b/src/cli/run/read-only.ts @@ -1,5 +1,5 @@ -import { normalizeCliArea } from "./area-aliases.js"; -import { parseArgs } from "./parser.js"; +import { normalizeCliArea } from "../parse/area-aliases.js"; +import { parseArgs } from "../parse/parser.js"; /** * Read-only classification for CLI commands, used to decide whether a command may be executed diff --git a/src/cli/runner.test.ts b/src/cli/run/runner.test.ts similarity index 97% rename from src/cli/runner.test.ts rename to src/cli/run/runner.test.ts index aee4b79..170d50e 100644 --- a/src/cli/runner.test.ts +++ b/src/cli/run/runner.test.ts @@ -3,8 +3,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { runCli } from "./runner.js"; -import { saveUpdateCache, UPDATE_CACHE_FILE_ENV } from "../core/update-cache.js"; -import { GLOBAL_SKILL_DIR_ENV } from "../core/skill-version.js"; +import { saveUpdateCache, UPDATE_CACHE_FILE_ENV } from "../../core/update/update-cache.js"; +import { GLOBAL_SKILL_DIR_ENV } from "../../core/skill/skill-version.js"; describe("CLI runner", () => { let tempSkillDir: string; diff --git a/src/cli/runner.ts b/src/cli/run/runner.ts similarity index 64% rename from src/cli/runner.ts rename to src/cli/run/runner.ts index 3476419..be5cfb3 100755 --- a/src/cli/runner.ts +++ b/src/cli/run/runner.ts @@ -2,34 +2,34 @@ import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import type { CorpConfig } from "../core/config/types.js"; -import { VERSION_INFO } from "../version.js"; -import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../core/update-cache.js"; -import { classifyCliError, usageError, validationError } from "../core/errors.js"; -import { isCorpDisabledError } from "../core/config/active.js"; +import type { CorpConfig } from "../../core/config/types.js"; +import { VERSION_INFO } from "../../version.js"; +import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../../core/update/update-cache.js"; +import { classifyCliError, usageError, validationError } from "../../core/errors.js"; +import { isCorpDisabledError } from "../../core/config/active.js"; import { booleanOption, materialPackFilePolicyOptions, numberOption, parseArgs, stringOption -} from "./parser.js"; -import { extractHelpRequest } from "./help.js"; -import { isNewerVersion } from "../core/semver.js"; -import { getSkillVersionStatus } from "../core/skill-version.js"; +} from "../parse/parser.js"; +import { extractHelpRequest } from "../help/help.js"; +import { isNewerVersion } from "../../core/util/semver.js"; +import { getSkillVersionStatus } from "../../core/skill/skill-version.js"; import { formatConsoleOutput, joinOutput, printHelp, printJson, redactSensitiveText -} from "./printer.js"; +} from "../output/printer.js"; import type { KyInstance } from "ky"; -import type { ParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js"; +import type { ParsedArgs, CliResult, CliRunOptions, CliRuntime } from "../types.js"; -const DEFAULT_APP_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url)))); -export { UPDATE_ALIASES } from "./area-aliases.js"; -import { AREA_ALIASES, normalizeCliArea, UPDATE_ALIASES } from "./area-aliases.js"; +const DEFAULT_APP_ROOT = dirname(dirname(dirname(dirname(fileURLToPath(import.meta.url))))); +export { UPDATE_ALIASES } from "../parse/area-aliases.js"; +import { AREA_ALIASES, normalizeCliArea, UPDATE_ALIASES } from "../parse/area-aliases.js"; type LocalCommand = (args: ParsedArgs, runtime: CliRuntime) => Promise; type CorpCommand = (args: ParsedArgs, corp: CorpConfig) => Promise; @@ -38,56 +38,56 @@ type ClientCommand = (args: ParsedArgs, corp: CorpConfig, client: KyInstance) => // Handler tables also define the known command surface. Imports stay lazy so // local discovery never loads the tenant, Excel, or zip implementation graphs. const LOCAL_COMMANDS: Record = { - "mcp-config": async () => (await import("./commands/mcp.js")).printMcpConfig(), - skill: async (args) => (await import("./commands/skill.js")).handleSkillCommand(args.command[1], args.command[2], args), - mcp: async (args) => (await import("./commands/mcp.js")).handleMcpCommand(args.command[1]), - probe: async (args) => (await import("./commands/probe.js")).handleProbeCommand(args.command[1], args.command[2], args), - doctor: async (args) => (await import("./commands/doctor.js")).handleDoctorCommand(args.command[1], args.command[2], args), - langfuse: async (args) => (await import("./commands/langfuse.js")).handleLangfuseCommand(args.command[1], args.command[2], args), - test: async (args) => (await import("./commands/test.js")).handleTestCommand(args.command[1], args.command[2], args), - config: async (args) => (await import("./commands/config.js")).handleConfigCommand(args.command[1], args.command[2], args), + "mcp-config": async () => (await import("../commands/mcp.js")).printMcpConfig(), + skill: async (args) => (await import("../commands/skill.js")).handleSkillCommand(args.command[1], args.command[2], args), + mcp: async (args) => (await import("../commands/mcp.js")).handleMcpCommand(args.command[1]), + probe: async (args) => (await import("../commands/probe.js")).handleProbeCommand(args.command[1], args.command[2], args), + doctor: async (args) => (await import("../commands/doctor.js")).handleDoctorCommand(args.command[1], args.command[2], args), + langfuse: async (args) => (await import("../commands/langfuse.js")).handleLangfuseCommand(args.command[1], args.command[2], args), + test: async (args) => (await import("../commands/test.js")).handleTestCommand(args.command[1], args.command[2], args), + config: async (args) => (await import("../commands/config.js")).handleConfigCommand(args.command[1], args.command[2], args), update: dispatchUpdate, changelog: dispatchUpdate, corps: async (args) => { const action = args.command[1]; // Local discovery must not initialize onboarding, sync or the capability registry. if (!action || ["list", "search", "find"].includes(action)) { - await (await import("./commands/corps/overview.js")).handleCorpOverview(action, args.command[2], args); + await (await import("../commands/corps/overview.js")).handleCorpOverview(action, args.command[2], args); return; } if (action === "regression" || action === "test-regression") { - await (await import("./commands/test.js")).handleTestCommand("regression", args.command[2], args); + await (await import("../commands/test.js")).handleTestCommand("regression", args.command[2], args); return; } - await (await import("./commands/corps.js")).handleCorpsCommand(action, args.command[2], args); + await (await import("../commands/corps.js")).handleCorpsCommand(action, args.command[2], args); } }; const CORP_COMMANDS: Record = { - source: async (args, corp) => (await import("./commands/source.js")).handleSourceCommand(args.command[1], corp), - auth: async (args, corp) => (await import("./commands/auth.js")).handleAuthCommand(args.command[1], corp, args) + source: async (args, corp) => (await import("../commands/source.js")).handleSourceCommand(args.command[1], corp), + auth: async (args, corp) => (await import("../commands/auth.js")).handleAuthCommand(args.command[1], corp, args) }; const CLIENT_COMMANDS: Record = { - "users": async (args, corp, client) => (await import("./commands/users.js")).handleUsersCommand(args.command[1], args.command[2], client, corp, args), - "contacts": async (args, corp, client) => (await import("./commands/contacts.js")).handleContactsCommand(args.command[1], args.command[2], client, corp, args), - "data": async (args, corp, client) => (await import("./commands/data.js")).handleDataCommand(args.command[1], client, corp, args), - "invoices": async (args, corp, client) => (await import("./commands/invoices.js")).handleInvoicesCommand(args.command[1], args.command[2], client, corp, args), - "expenses": async (args, corp, client) => (await import("./commands/expenses.js")).handleExpensesCommand(args.command[1], client, corp, args), - "llm": async (args, corp, client) => (await import("./commands/llm.js")).handleLlmCommand(args.command[1], client, corp, args), - "permissions": async (args, corp, client) => (await import("./commands/permissions.js")).handlePermissionsCommand(args.command[1], client, corp, args), - "billing": async (args, corp, client) => (await import("./commands/billing.js")).handleBillingCommand(args.command[1], client, corp, args), - "webhook": async (args, corp, client) => (await import("./commands/webhook.js")).handleWebhookCommand(args.command[1], args.command[2], client, corp, args), - "context": async (args, corp, client) => (await import("./commands/context.js")).handleContextCommand(client, corp, args), - "documents": async (args, corp, client) => (await import("./commands/documents.js")).handleDocumentsCommand(args.command[1], args.command[2], client, corp, args), - "rules": async (args, corp, client) => (await import("./commands/rules.js")).handleRulesCommand(args.command[1], args.command[2], client, corp, args), - "approval-runs": async (args, corp, client) => (await import("./commands/approval-runs.js")).handleApprovalRunsCommand(args.command[1], args.command[2], client, corp, args), - "analytics": async (args, corp, client) => (await import("./commands/analytics.js")).handleAnalyticsCommand(args.command[1], args.command[2], client, corp, args), - "report": async (args, corp, client) => (await import("./commands/report.js")).handleReportCommand(args.command[1], client, corp, args), - "simulation": async (args, corp, client) => (await import("./commands/simulation.js")).handleSimulationCommand(args.command[1], args.command[2], client, corp, args), - "deploy": async (args, corp, client) => (await import("./commands/deploy.js")).handleDeployCommand(args.command[1], args.command[2], args.command[3], client, corp, args), - "hose-ebot": async (args, corp, client) => (await import("./commands/hose-ebot.js")).handleHoseEbotCommand(args.command[1], args.command[2], client, corp, args), - "preference": async (args, corp, client) => (await import("./commands/preference.js")).handlePreferenceCommand(args.command[1], args.command[2], args.command[3], args.command[4], client, corp, args), + "users": async (args, corp, client) => (await import("../commands/users.js")).handleUsersCommand(args.command[1], args.command[2], client, corp, args), + "contacts": async (args, corp, client) => (await import("../commands/contacts.js")).handleContactsCommand(args.command[1], args.command[2], client, corp, args), + "data": async (args, corp, client) => (await import("../commands/data.js")).handleDataCommand(args.command[1], client, corp, args), + "invoices": async (args, corp, client) => (await import("../commands/invoices.js")).handleInvoicesCommand(args.command[1], args.command[2], client, corp, args), + "expenses": async (args, corp, client) => (await import("../commands/expenses.js")).handleExpensesCommand(args.command[1], client, corp, args), + "llm": async (args, corp, client) => (await import("../commands/llm.js")).handleLlmCommand(args.command[1], client, corp, args), + "permissions": async (args, corp, client) => (await import("../commands/permissions.js")).handlePermissionsCommand(args.command[1], client, corp, args), + "billing": async (args, corp, client) => (await import("../commands/billing.js")).handleBillingCommand(args.command[1], client, corp, args), + "webhook": async (args, corp, client) => (await import("../commands/webhook.js")).handleWebhookCommand(args.command[1], args.command[2], client, corp, args), + "context": async (args, corp, client) => (await import("../commands/context.js")).handleContextCommand(client, corp, args), + "documents": async (args, corp, client) => (await import("../commands/documents.js")).handleDocumentsCommand(args.command[1], args.command[2], client, corp, args), + "rules": async (args, corp, client) => (await import("../commands/rules.js")).handleRulesCommand(args.command[1], args.command[2], client, corp, args), + "approval-runs": async (args, corp, client) => (await import("../commands/approval-runs.js")).handleApprovalRunsCommand(args.command[1], args.command[2], client, corp, args), + "analytics": async (args, corp, client) => (await import("../commands/analytics.js")).handleAnalyticsCommand(args.command[1], args.command[2], client, corp, args), + "report": async (args, corp, client) => (await import("../commands/report.js")).handleReportCommand(args.command[1], client, corp, args), + "simulation": async (args, corp, client) => (await import("../commands/simulation.js")).handleSimulationCommand(args.command[1], args.command[2], client, corp, args), + "deploy": async (args, corp, client) => (await import("../commands/deploy.js")).handleDeployCommand(args.command[1], args.command[2], args.command[3], client, corp, args), + "hose-ebot": async (args, corp, client) => (await import("../commands/hose-ebot.js")).handleHoseEbotCommand(args.command[1], args.command[2], client, corp, args), + "preference": async (args, corp, client) => (await import("../commands/preference.js")).handlePreferenceCommand(args.command[1], args.command[2], args.command[3], args.command[4], client, corp, args), }; export const KNOWN_AREAS = new Set([ @@ -97,7 +97,7 @@ export const KNOWN_AREAS = new Set([ ...Object.keys(AREA_ALIASES) ]); -export type { CliResult, CliRunOptions } from "./types.js"; +export type { CliResult, CliRunOptions } from "../types.js"; const STANDING_COMMANDS = new Set(["server", "mcp"]); @@ -210,7 +210,7 @@ async function dispatchUpdate(args: ParsedArgs, runtime: CliRuntime): Promise"); - await (await import("./commands/webhook.js")).handleWebhookResourcePackPreview(filePath, materialPackFilePolicyOptions(args.options)); + await (await import("../commands/webhook.js")).handleWebhookResourcePackPreview(filePath, materialPackFilePolicyOptions(args.options)); return; } @@ -298,7 +298,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) { action === "review" || Boolean(args.options.ledger)) ) { - await (await import("./commands/report.js")).handleLocalReportCommand(action, args); + await (await import("../commands/report.js")).handleLocalReportCommand(action, args); return; } @@ -313,7 +313,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) { if (area === "rules" && action === "lint" && ("file" in args.options || "f" in args.options)) { let corp: CorpConfig; try { - corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp)); + corp = (await import("../helpers.js")).selectCorp(stringOption(args.options.corp)); } catch (error) { // Local lint tolerates a missing enterprise config, but a disabled tenant // is an explicit block: never degrade into the synthetic workspace corp. @@ -324,7 +324,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) { source: { type: "native" } } as any; } - await (await import("./commands/rules.js")).handleRulesCommand(action, maybeName, null, corp, args); + await (await import("../commands/rules.js")).handleRulesCommand(action, maybeName, null, corp, args); return; } @@ -332,7 +332,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) { area === "auth" && (action === "extract-keys" || action === "extract-key" || action === "extract-hose-keys" || action === "hose-extract-keys") ) { - await (await import("./commands/auth.js")).handleAuthExtractKeysCommand(maybeName, args); + await (await import("../commands/auth.js")).handleAuthExtractKeysCommand(maybeName, args); return; } @@ -341,23 +341,23 @@ async function dispatch(argv: string[], runtime: CliRuntime) { (action === "link" || action === "seal-link") && ("from-link" in args.options || maybeName === "from-link") ) { - await (await import("./commands/auth.js")).handleAuthCommand(action, null, args); + await (await import("../commands/auth.js")).handleAuthCommand(action, null, args); return; } // Local task observation and previews must not authenticate or contact a tenant. if (area === "approval-runs" && (action === "export" || action === "export-worker")) { - await (await import("./commands/approval-runs-export.js")).handleApprovalRunsExportCommand(args, runtime); + await (await import("../commands/approval-runs-export.js")).handleApprovalRunsExportCommand(args, runtime); return; } - const corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp)); + const corp = (await import("../helpers.js")).selectCorp(stringOption(args.options.corp)); const maybePromptDivergences = async () => { if (area === "report" && action === "review") return; try { const { countUnreviewedDivergences, shouldPromptDivergence } = await import( - "../domains/seal/reports/pipeline/review-store.js" + "../../domains/seal/reports/pipeline/review-store.js" ); const count = countUnreviewedDivergences(corp.id, 30); if (count > 0 && shouldPromptDivergence(corp.id)) { @@ -379,7 +379,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) { const clientCommand = CLIENT_COMMANDS[area]; if (clientCommand) { - const client = await (await import("../core/http/factory.js")).createSealClient(corp); + const client = await (await import("../../core/http/factory.js")).createSealClient(corp); await clientCommand(args, corp, client); await maybePromptDivergences(); return; diff --git a/src/cli/types.ts b/src/cli/types.ts index d860622..3ad5b11 100644 --- a/src/cli/types.ts +++ b/src/cli/types.ts @@ -1,4 +1,4 @@ -import type { LauncherConfig } from "../core/runtime.js"; +import type { LauncherConfig } from "../core/util/runtime.js"; export type ParsedArgs = { command: string[]; diff --git a/src/core/auth/hose.test.ts b/src/core/auth/hose.test.ts index 9c95b03..ef53069 100644 --- a/src/core/auth/hose.test.ts +++ b/src/core/auth/hose.test.ts @@ -137,7 +137,6 @@ describe("hose auth helpers", () => { seal: { endpoints: { approvalStylePreferences: "" } }, source: { type: "hose", - provider: "hosecloud", domain: "https://wx2.ekuaibao.com", closeToken: "hose-close-token", staffId: "corp-web:staff-1", @@ -149,7 +148,7 @@ describe("hose auth helpers", () => { const session = await getHoseSealSession(corp); expect(requestedToken).toBe("hose-close-token"); expect(session.token).toBe("seal-runtime-token"); - expect(session.enterprise.provider).toBe("hose"); + expect(session.enterprise).not.toHaveProperty("provider"); }); test("HOSE_STANDARD_DOMAINS contains 6 expected public platform domains", () => { diff --git a/src/core/auth/hose.ts b/src/core/auth/hose.ts index cadb636..6cd92ad 100644 --- a/src/core/auth/hose.ts +++ b/src/core/auth/hose.ts @@ -274,8 +274,8 @@ function hoseClient(source: HoseSealSource): KyInstance { async function fetchHoseOpenapiToken(source: HoseSealSource): Promise { const client = hoseClient(source); - const appKey = source.appKey ?? source.key; - const appSecurity = source.appSecurity ?? source.password; + const appKey = source.appKey; + const appSecurity = source.appSecurity; if (!appKey || !appSecurity) { throw new Error("Hose source has no OpenAPI credentials; the configured closeToken is only valid for Hose web-session APIs"); @@ -495,7 +495,6 @@ export async function getHoseSealSession(corp: CorpConfig): Promise 3600; const enterprise: SealEnterpriseConfig = { - provider: "hose", corpId: corp.source.corpId, staffId: corp.source.staffId, sealUrl: normalizeBaseUrl(sealUrl), diff --git a/src/core/auth/native.test.ts b/src/core/auth/native.test.ts index 73e50a3..6a77645 100644 --- a/src/core/auth/native.test.ts +++ b/src/core/auth/native.test.ts @@ -31,7 +31,6 @@ describe("getNativeSealSession", () => { const session = await getNativeSealSession(corp); expect(session.token).toBe("bearer-token-native"); expect(session.enterprise).toEqual({ - provider: "seal", corpId: "corp-native-1", staffId: "staff-123", sealUrl: "https://seal.example.com", @@ -75,7 +74,7 @@ describe("getNativeSealSession", () => { const session = await getNativeSealSession(corp); expect(session.token).toBe("bearer-token-native"); - expect(session.enterprise.provider).toBe("seal"); + expect(session.enterprise).not.toHaveProperty("provider"); expect(session.enterprise.tenantId).toBe("tenant-100"); expect(session.enterprise.tenantName).toBe("Tenant 100 Name"); expect(session.expiresAt).toBe(new Date("2026-09-22T05:30:00Z").getTime()); diff --git a/src/core/auth/native.ts b/src/core/auth/native.ts index c3d2b8a..3a34c14 100644 --- a/src/core/auth/native.ts +++ b/src/core/auth/native.ts @@ -15,7 +15,6 @@ export async function getNativeSealSession(corp: CorpConfig): Promise { tempDir = mkdtempSync(join(tmpdir(), "seal-renew-test-")); storePath = join(tempDir, "tokens.json"); + enterprisesDir = join(tempDir, "enterprises"); process.env.SEAL_USE_TOKEN_STORE = storePath; + // renewNativeSealSession writes the renewed token back through + // saveCorpConfig; keep that write inside the sandbox so tests never + // touch the real ~/.config/seal-use/enterprises directory. + process.env.SEAL_USE_ENTERPRISES_DIR = enterprisesDir; clearSealToken(fixtureCorp.id); }); @@ -56,6 +62,11 @@ describe("seal-renew: 原生 Seal 协助授权长效续期与会话池救险", ( globalThis.fetch = originalFetch; clearSealToken(fixtureCorp.id); delete process.env.SEAL_USE_TOKEN_STORE; + if (ORIGINAL_ENTERPRISES_DIR === undefined) { + delete process.env.SEAL_USE_ENTERPRISES_DIR; + } else { + process.env.SEAL_USE_ENTERPRISES_DIR = ORIGINAL_ENTERPRISES_DIR; + } rmSync(tempDir, { recursive: true, force: true }); }); diff --git a/src/core/auth/seal.ts b/src/core/auth/seal.ts index 32e351d..daaf43e 100644 --- a/src/core/auth/seal.ts +++ b/src/core/auth/seal.ts @@ -69,7 +69,6 @@ export async function renewNativeSealSession(corp: CorpConfig): Promise { token: "test-token-123", expiresAt: Date.now() + 3600_000, enterprise: { - provider: "seal", corpId: "corp-1", staffId: "staff-1", sealUrl: "https://seal.example.com" @@ -136,7 +135,6 @@ describe("token-store", () => { token: "legacy-token-456", expiresAt: Date.now() + 3600_000, enterprise: { - provider: "seal", corpId: "corp-legacy", staffId: "staff-legacy", sealUrl: "https://seal.example.com" diff --git a/src/core/auth/token-store.ts b/src/core/auth/token-store.ts index 554e274..fb49126 100644 --- a/src/core/auth/token-store.ts +++ b/src/core/auth/token-store.ts @@ -1,6 +1,6 @@ import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; -import { writeSecureFile } from "../secure-file.js"; +import { writeSecureFile } from "../util/secure-file.js"; import { SEAL_CONFIG_DIR } from "../paths.js"; import { CorpTokenCache, diff --git a/src/core/auth/types.ts b/src/core/auth/types.ts index 8e11091..7370f2d 100644 --- a/src/core/auth/types.ts +++ b/src/core/auth/types.ts @@ -7,7 +7,6 @@ export const TokenEntrySchema = z.object({ }); export const SealEnterpriseConfigSchema = z.object({ - provider: z.string(), corpId: z.string().optional(), staffId: z.string(), sealUrl: z.string().url(), diff --git a/src/core/config/loader.ts b/src/core/config/loader.ts index e96d5a8..0cd984a 100644 --- a/src/core/config/loader.ts +++ b/src/core/config/loader.ts @@ -3,7 +3,7 @@ import { homedir } from "node:os"; import { join } from "node:path"; import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigInput, GlobalConfigSchema } from "./types.js"; -import { writeSecureFile } from "../secure-file.js"; +import { writeSecureFile } from "../util/secure-file.js"; const CONFIG_ENV = "SEAL_USE_ENTERPRISES_DIR"; const LEGACY_CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR"; diff --git a/src/core/config/repository.ts b/src/core/config/repository.ts index 476e5b7..da695d9 100644 --- a/src/core/config/repository.ts +++ b/src/core/config/repository.ts @@ -1,5 +1,5 @@ import { existsSync } from "node:fs"; -import { writeSecureFile } from "../secure-file.js"; +import { writeSecureFile } from "../util/secure-file.js"; import { join } from "node:path"; import { resolveWritableEnterprisesDir } from "./loader.js"; import { CorpConfigSchema, type CorpConfig } from "./types.js"; diff --git a/src/core/config/types.test.ts b/src/core/config/types.test.ts index 0d2c0f6..a8c4d3a 100644 --- a/src/core/config/types.test.ts +++ b/src/core/config/types.test.ts @@ -8,10 +8,33 @@ import { import { isCorpActive } from "./active.js"; describe("CorpConfigSchema", () => { - test("accepts Hose key/password aliases", () => { + test("accepts Hose appKey/appSecurity credentials", () => { const config = CorpConfigSchema.parse({ id: "corp-local", name: "Local Corp", + source: { + type: "hose", + domain: "https://app.ekuaibao.com", + appKey: "app-key", + appSecurity: "app-security", + corpId: "ID01", + staffId: "ID01:STAFF01" + } + }); + + expect(config.source.type).toBe("hose"); + if (config.source.type !== "hose") { + throw new Error("expected hose source"); + } + expect(config.source.appKey).toBe("app-key"); + expect(config.source.appSecurity).toBe("app-security"); + expect(config.auth.refreshTtl).toBe(300); + }); + + test("rejects legacy key/password aliases", () => { + const result = CorpConfigSchema.safeParse({ + id: "corp-legacy", + name: "Legacy Corp", source: { type: "hose", domain: "https://app.ekuaibao.com", @@ -22,13 +45,7 @@ describe("CorpConfigSchema", () => { } }); - expect(config.source.type).toBe("hose"); - if (config.source.type !== "hose") { - throw new Error("expected hose source"); - } - expect(config.source.key).toBe("app-key"); - expect(config.source.password).toBe("app-security"); - expect(config.auth.refreshTtl).toBe(300); + expect(result.success).toBe(false); }); test("requires a Hose key and secret", () => { @@ -52,7 +69,6 @@ describe("CorpConfigSchema", () => { name: "Hose Web Session", source: { type: "hose", - provider: "hosecloud", domain: "https://wx2.ekuaibao.com", closeToken: "hose-close-token", expiresIn: 1800, @@ -71,6 +87,36 @@ describe("CorpConfigSchema", () => { expect(config.source.expiresAt).toBe("2026-09-22T13:30:00+08:00"); }); + test("drops legacy provider metadata instead of rejecting the config", () => { + const hoseConfig = CorpConfigSchema.parse({ + id: "legacy-hose", + name: "Legacy Hose", + source: { + type: "hose", + provider: "hosecloud", + domain: "https://wx2.ekuaibao.com", + closeToken: "hose-close-token", + corpId: "corp-1", + staffId: "corp-1:staff-1" + } + }); + expect(hoseConfig.source).not.toHaveProperty("provider"); + + const sealConfig = CorpConfigSchema.parse({ + id: "legacy-seal", + name: "Legacy Seal", + source: { + type: "seal", + token: "seal-token", + sealUrl: "https://seal.sealai.cc", + provider: "feishu", + providerName: "飞书" + } + }); + expect(sealConfig.source).not.toHaveProperty("provider"); + expect(sealConfig.source).not.toHaveProperty("providerName"); + }); + test("accepts Seal Bearer source with expiry metadata and normalizes legacy UTC to +08:00", () => { const config = CorpConfigSchema.parse({ id: "seal", diff --git a/src/core/config/types.ts b/src/core/config/types.ts index 31cc024..29857c5 100644 --- a/src/core/config/types.ts +++ b/src/core/config/types.ts @@ -8,12 +8,9 @@ const IsoSecondTimestampSchema = z.string().regex( export const HoseSealSourceSchema = z.object({ type: z.literal("hose"), - provider: z.string().optional(), domain: z.string().url().default("https://app.ekuaibao.com"), appKey: z.string().optional(), appSecurity: z.string().optional(), - key: z.string().optional(), - password: z.string().optional(), closeToken: z.string().optional(), expiresIn: z.number().int().positive().optional(), expiresAt: IsoSecondTimestampSchema.optional(), @@ -21,19 +18,19 @@ export const HoseSealSourceSchema = z.object({ corpId: z.string(), sealUrl: z.string().url().optional() }).superRefine((source, ctx) => { - if (!source.closeToken && !source.appKey && !source.key) { + if (!source.closeToken && !source.appKey) { ctx.addIssue({ code: "custom", path: ["appKey"], - message: "Hose source requires appKey/key or closeToken" + message: "Hose source requires appKey or closeToken" }); } - if (!source.closeToken && !source.appSecurity && !source.password) { + if (!source.closeToken && !source.appSecurity) { ctx.addIssue({ code: "custom", path: ["appSecurity"], - message: "Hose source requires appSecurity/password or closeToken" + message: "Hose source requires appSecurity or closeToken" }); } }); @@ -49,9 +46,7 @@ export const NativeSealSourceSchema = z.object({ tenantId: z.string().optional(), tenantSlug: z.string().optional(), tenantName: z.string().optional(), - providerUserId: z.string().optional(), - provider: z.string().optional(), - providerName: z.string().optional() + providerUserId: z.string().optional() }); export const SealSourceSchema = z.discriminatedUnion("type", [ diff --git a/src/core/corp-search/corp.ts b/src/core/corp-search/corp.ts index 01ca2c9..33aecc9 100644 --- a/src/core/corp-search/corp.ts +++ b/src/core/corp-search/corp.ts @@ -22,8 +22,7 @@ function corpSearchFields(corp: CorpConfig): CorpField[] { { text: corp.testCorpId, weight: 1.0 }, { text: corp.prodCorpId, weight: 1.0 }, { text: corp.environment ?? "production", weight: 0.8 }, - { text: corp.source.type, weight: 0.8 }, - { text: (corp.source as any).provider, weight: 0.8 } + { text: corp.source.type, weight: 0.8 } ]; } diff --git a/src/core/doctor/diagnose.ts b/src/core/doctor/diagnose.ts index fb5e1a5..5eae331 100644 --- a/src/core/doctor/diagnose.ts +++ b/src/core/doctor/diagnose.ts @@ -5,7 +5,7 @@ import { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR } from "../paths.js"; import { VERSION } from "../../version.js"; import { getLastCorpConfigLoadIssues, getLastGlobalConfigIssue, loadCorpConfigs, loadGlobalConfig } from "../config/loader.js"; import { formatBeijingIso } from "../config/timestamps.js"; -import { getDefaultGlobalSkillDir, getSkillVersionStatus } from "../skill-version.js"; +import { getDefaultGlobalSkillDir, getSkillVersionStatus } from "../skill/skill-version.js"; import { resolveUsageFilePath } from "../stats/usage-tracker.js"; import { EMBEDDED_DIRECTORY_SPECS, diff --git a/src/core/embedded-skill.generated.ts b/src/core/embedded-skill.generated.ts deleted file mode 100644 index e88644d..0000000 --- a/src/core/embedded-skill.generated.ts +++ /dev/null @@ -1,98 +0,0 @@ -// Generated by scripts/generate-embedded-skill.mjs. Do not edit manually. - -import file0 from "../../skills/seal-use/SKILL.md" with { type: "text" }; -import file1 from "../../skills/seal-use/agents/openai.yaml" with { type: "text" }; -import file2 from "../../skills/seal-use/assets/hose-curl-copy-as-curl.png" with { type: "file" }; -import file3 from "../../skills/seal-use/assets/hose-curl-network-fetch-xhr.png" with { type: "file" }; -import file4 from "../../skills/seal-use/assets/hose-curl-open-page-check.png" with { type: "file" }; -import file5 from "../../skills/seal-use/assets/hose-open-platform-app-center.png" with { type: "file" }; -import file6 from "../../skills/seal-use/assets/hose-open-platform-credentials.png" with { type: "file" }; -import file7 from "../../skills/seal-use/assets/hose-open-platform-product-config.png" with { type: "file" }; -import file8 from "../../skills/seal-use/references/approval-attachment-trace.md" with { type: "text" }; -import file9 from "../../skills/seal-use/references/approval-bad-cases.md" with { type: "text" }; -import file10 from "../../skills/seal-use/references/approval-run-export.md" with { type: "text" }; -import file11 from "../../skills/seal-use/references/approval-run-lightweight.md" with { type: "text" }; -import file12 from "../../skills/seal-use/references/cli.md" with { type: "text" }; -import file13 from "../../skills/seal-use/references/customer-feedback-rule-remediation.md" with { type: "text" }; -import file14 from "../../skills/seal-use/references/documents.md" with { type: "text" }; -import file15 from "../../skills/seal-use/references/enterprise-onboarding.md" with { type: "text" }; -import file16 from "../../skills/seal-use/references/expense-data.md" with { type: "text" }; -import file17 from "../../skills/seal-use/references/first-time-user.md" with { type: "text" }; -import file18 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" }; -import file19 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" }; -import file20 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" }; -import file21 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" }; -import file22 from "../../skills/seal-use/references/report-templates.md" with { type: "text" }; -import file23 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" }; -import file24 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" }; -import file25 from "../../skills/seal-use/references/sealai-browser-rum.md" with { type: "text" }; -import file26 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" }; -import file27 from "../../skills/seal-use/references/tenant-status.md" with { type: "text" }; -import file28 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" }; - -export const EMBEDDED_SKILL_TEXT_FILES: Record = { - "SKILL.md": file0, - "agents/openai.yaml": file1, - "references/approval-attachment-trace.md": file8, - "references/approval-bad-cases.md": file9, - "references/approval-run-export.md": file10, - "references/approval-run-lightweight.md": file11, - "references/cli.md": file12, - "references/customer-feedback-rule-remediation.md": file13, - "references/documents.md": file14, - "references/enterprise-onboarding.md": file15, - "references/expense-data.md": file16, - "references/first-time-user.md": file17, - "references/hose-enterprise-auth.md": file18, - "references/hose-enterprise-deploy.md": file19, - "references/hose-enterprise-init.md": file20, - "references/langfuse-trace.md": file21, - "references/report-templates.md": file22, - "references/rule-lightweight.md": file23, - "references/rule-lint.md": file24, - "references/sealai-browser-rum.md": file25, - "references/staging-simulation-workflow.md": file26, - "references/tenant-status.md": file27, - "references/webhook-resource-pack.md": file28, -}; - -export const EMBEDDED_SKILL_ASSET_PATHS: Record = { - "assets/hose-curl-copy-as-curl.png": file2, - "assets/hose-curl-network-fetch-xhr.png": file3, - "assets/hose-curl-open-page-check.png": file4, - "assets/hose-open-platform-app-center.png": file5, - "assets/hose-open-platform-credentials.png": file6, - "assets/hose-open-platform-product-config.png": file7, -}; - -export const EMBEDDED_SKILL_ALL_PATHS = [ - "SKILL.md", - "agents/openai.yaml", - "assets/hose-curl-copy-as-curl.png", - "assets/hose-curl-network-fetch-xhr.png", - "assets/hose-curl-open-page-check.png", - "assets/hose-open-platform-app-center.png", - "assets/hose-open-platform-credentials.png", - "assets/hose-open-platform-product-config.png", - "references/approval-attachment-trace.md", - "references/approval-bad-cases.md", - "references/approval-run-export.md", - "references/approval-run-lightweight.md", - "references/cli.md", - "references/customer-feedback-rule-remediation.md", - "references/documents.md", - "references/enterprise-onboarding.md", - "references/expense-data.md", - "references/first-time-user.md", - "references/hose-enterprise-auth.md", - "references/hose-enterprise-deploy.md", - "references/hose-enterprise-init.md", - "references/langfuse-trace.md", - "references/report-templates.md", - "references/rule-lightweight.md", - "references/rule-lint.md", - "references/sealai-browser-rum.md", - "references/staging-simulation-workflow.md", - "references/tenant-status.md", - "references/webhook-resource-pack.md", -]; diff --git a/src/core/http/factory.test.ts b/src/core/http/factory.test.ts index 25be1f2..a114907 100644 --- a/src/core/http/factory.test.ts +++ b/src/core/http/factory.test.ts @@ -37,7 +37,7 @@ function recoveryFixture(sourceType: "hose" | "seal", alwaysUnauthorized = false }); setSealSession(id, { token: "stale-token", expiresAt: Date.now() + 3600000, - enterprise: { provider: sourceType, staffId: "fixture-staff", sealUrl: "https://fixture.invalid" } + enterprise: { staffId: "fixture-staff", sealUrl: "https://fixture.invalid" } }); const requests: Array<{ method: string; token: string | null }> = []; let refreshes = 0; diff --git a/src/core/skill/embedded-skill.generated.ts b/src/core/skill/embedded-skill.generated.ts new file mode 100644 index 0000000..a1cc3f5 --- /dev/null +++ b/src/core/skill/embedded-skill.generated.ts @@ -0,0 +1,98 @@ +// Generated by scripts/generate-embedded-skill.mjs. Do not edit manually. + +import file0 from "../../../skills/seal-use/SKILL.md" with { type: "text" }; +import file1 from "../../../skills/seal-use/agents/openai.yaml" with { type: "text" }; +import file2 from "../../../skills/seal-use/assets/hose-curl-copy-as-curl.png" with { type: "file" }; +import file3 from "../../../skills/seal-use/assets/hose-curl-network-fetch-xhr.png" with { type: "file" }; +import file4 from "../../../skills/seal-use/assets/hose-curl-open-page-check.png" with { type: "file" }; +import file5 from "../../../skills/seal-use/assets/hose-open-platform-app-center.png" with { type: "file" }; +import file6 from "../../../skills/seal-use/assets/hose-open-platform-credentials.png" with { type: "file" }; +import file7 from "../../../skills/seal-use/assets/hose-open-platform-product-config.png" with { type: "file" }; +import file8 from "../../../skills/seal-use/references/approval-attachment-trace.md" with { type: "text" }; +import file9 from "../../../skills/seal-use/references/approval-bad-cases.md" with { type: "text" }; +import file10 from "../../../skills/seal-use/references/approval-run-export.md" with { type: "text" }; +import file11 from "../../../skills/seal-use/references/approval-run-lightweight.md" with { type: "text" }; +import file12 from "../../../skills/seal-use/references/cli.md" with { type: "text" }; +import file13 from "../../../skills/seal-use/references/customer-feedback-rule-remediation.md" with { type: "text" }; +import file14 from "../../../skills/seal-use/references/documents.md" with { type: "text" }; +import file15 from "../../../skills/seal-use/references/enterprise-onboarding.md" with { type: "text" }; +import file16 from "../../../skills/seal-use/references/expense-data.md" with { type: "text" }; +import file17 from "../../../skills/seal-use/references/first-time-user.md" with { type: "text" }; +import file18 from "../../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" }; +import file19 from "../../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" }; +import file20 from "../../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" }; +import file21 from "../../../skills/seal-use/references/langfuse-trace.md" with { type: "text" }; +import file22 from "../../../skills/seal-use/references/report-templates.md" with { type: "text" }; +import file23 from "../../../skills/seal-use/references/rule-lightweight.md" with { type: "text" }; +import file24 from "../../../skills/seal-use/references/rule-lint.md" with { type: "text" }; +import file25 from "../../../skills/seal-use/references/sealai-browser-rum.md" with { type: "text" }; +import file26 from "../../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" }; +import file27 from "../../../skills/seal-use/references/tenant-status.md" with { type: "text" }; +import file28 from "../../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" }; + +export const EMBEDDED_SKILL_TEXT_FILES: Record = { + "SKILL.md": file0, + "agents/openai.yaml": file1, + "references/approval-attachment-trace.md": file8, + "references/approval-bad-cases.md": file9, + "references/approval-run-export.md": file10, + "references/approval-run-lightweight.md": file11, + "references/cli.md": file12, + "references/customer-feedback-rule-remediation.md": file13, + "references/documents.md": file14, + "references/enterprise-onboarding.md": file15, + "references/expense-data.md": file16, + "references/first-time-user.md": file17, + "references/hose-enterprise-auth.md": file18, + "references/hose-enterprise-deploy.md": file19, + "references/hose-enterprise-init.md": file20, + "references/langfuse-trace.md": file21, + "references/report-templates.md": file22, + "references/rule-lightweight.md": file23, + "references/rule-lint.md": file24, + "references/sealai-browser-rum.md": file25, + "references/staging-simulation-workflow.md": file26, + "references/tenant-status.md": file27, + "references/webhook-resource-pack.md": file28, +}; + +export const EMBEDDED_SKILL_ASSET_PATHS: Record = { + "assets/hose-curl-copy-as-curl.png": file2, + "assets/hose-curl-network-fetch-xhr.png": file3, + "assets/hose-curl-open-page-check.png": file4, + "assets/hose-open-platform-app-center.png": file5, + "assets/hose-open-platform-credentials.png": file6, + "assets/hose-open-platform-product-config.png": file7, +}; + +export const EMBEDDED_SKILL_ALL_PATHS = [ + "SKILL.md", + "agents/openai.yaml", + "assets/hose-curl-copy-as-curl.png", + "assets/hose-curl-network-fetch-xhr.png", + "assets/hose-curl-open-page-check.png", + "assets/hose-open-platform-app-center.png", + "assets/hose-open-platform-credentials.png", + "assets/hose-open-platform-product-config.png", + "references/approval-attachment-trace.md", + "references/approval-bad-cases.md", + "references/approval-run-export.md", + "references/approval-run-lightweight.md", + "references/cli.md", + "references/customer-feedback-rule-remediation.md", + "references/documents.md", + "references/enterprise-onboarding.md", + "references/expense-data.md", + "references/first-time-user.md", + "references/hose-enterprise-auth.md", + "references/hose-enterprise-deploy.md", + "references/hose-enterprise-init.md", + "references/langfuse-trace.md", + "references/report-templates.md", + "references/rule-lightweight.md", + "references/rule-lint.md", + "references/sealai-browser-rum.md", + "references/staging-simulation-workflow.md", + "references/tenant-status.md", + "references/webhook-resource-pack.md", +]; diff --git a/src/core/embedded-skill.test.ts b/src/core/skill/embedded-skill.test.ts similarity index 95% rename from src/core/embedded-skill.test.ts rename to src/core/skill/embedded-skill.test.ts index fad997d..1c4e78a 100644 --- a/src/core/embedded-skill.test.ts +++ b/src/core/skill/embedded-skill.test.ts @@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test"; import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import packageJson from "../../package.json" with { type: "json" }; +import packageJson from "../../../package.json" with { type: "json" }; import { EMBEDDED_SKILL_ALL_PATHS, EMBEDDED_SKILL_ASSETS, @@ -39,7 +39,7 @@ describe("embedded-skill", () => { expect(existsSync(join(tmp, "assets", "hose-curl-copy-as-curl.png"))).toBe(true); expect([...res.files].sort()).toEqual([...EMBEDDED_SKILL_ALL_PATHS].sort()); for (const path of EMBEDDED_SKILL_ALL_PATHS) { - expect(readFileSync(join(tmp, path))).toEqual(readFileSync(join(import.meta.dir, "../../skills/seal-use", path))); + expect(readFileSync(join(tmp, path))).toEqual(readFileSync(join(import.meta.dir, "../../../skills/seal-use", path))); } } finally { rmSync(tmp, { recursive: true, force: true }); diff --git a/src/core/embedded-skill.ts b/src/core/skill/embedded-skill.ts similarity index 98% rename from src/core/embedded-skill.ts rename to src/core/skill/embedded-skill.ts index 1ffd155..d556b5e 100644 --- a/src/core/embedded-skill.ts +++ b/src/core/skill/embedded-skill.ts @@ -102,4 +102,4 @@ export function syncGlobalSkillIfPresent(): { synced: boolean; targetDir?: strin } // Re-export agent host skill bridging capabilities -export * from "./agent-hosts/index.js"; +export * from "../agent-hosts/index.js"; diff --git a/src/core/skill-version.test.ts b/src/core/skill/skill-version.test.ts similarity index 100% rename from src/core/skill-version.test.ts rename to src/core/skill/skill-version.test.ts diff --git a/src/core/skill-version.ts b/src/core/skill/skill-version.ts similarity index 97% rename from src/core/skill-version.ts rename to src/core/skill/skill-version.ts index 1b45670..79d7ac6 100644 --- a/src/core/skill-version.ts +++ b/src/core/skill/skill-version.ts @@ -1,7 +1,7 @@ import { existsSync, readFileSync } from "node:fs" import { homedir } from "node:os" import { join } from "node:path" -import { compareSemVer } from "./semver.js" +import { compareSemVer } from "../util/semver.js" export const GLOBAL_SKILL_DIR_ENV = "SEAL_USE_GLOBAL_SKILL_DIR" diff --git a/src/core/update-cache.test.ts b/src/core/update/update-cache.test.ts similarity index 100% rename from src/core/update-cache.test.ts rename to src/core/update/update-cache.test.ts diff --git a/src/core/update-cache.ts b/src/core/update/update-cache.ts similarity index 94% rename from src/core/update-cache.ts rename to src/core/update/update-cache.ts index d956b82..cf5139a 100644 --- a/src/core/update-cache.ts +++ b/src/core/update/update-cache.ts @@ -1,10 +1,10 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { spawn } from "node:child_process"; -import type { LauncherConfig } from "./runtime.js"; -import { formatBeijingIso, normalizeBeijingIso } from "./config/timestamps.js"; +import type { LauncherConfig } from "../util/runtime.js"; +import { formatBeijingIso, normalizeBeijingIso } from "../config/timestamps.js"; -import { SEAL_CACHE_DIR } from "./paths.js"; +import { SEAL_CACHE_DIR } from "../paths.js"; export const UPDATE_CACHE_FILE_ENV = "SEAL_USE_UPDATE_CACHE_FILE"; export const DEFAULT_UPDATE_CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours diff --git a/src/core/duration.test.ts b/src/core/util/duration.test.ts similarity index 100% rename from src/core/duration.test.ts rename to src/core/util/duration.test.ts diff --git a/src/core/duration.ts b/src/core/util/duration.ts similarity index 100% rename from src/core/duration.ts rename to src/core/util/duration.ts diff --git a/src/core/redact.test.ts b/src/core/util/redact.test.ts similarity index 100% rename from src/core/redact.test.ts rename to src/core/util/redact.test.ts diff --git a/src/core/redact.ts b/src/core/util/redact.ts similarity index 97% rename from src/core/redact.ts rename to src/core/util/redact.ts index e04e9e7..c4ea515 100644 --- a/src/core/redact.ts +++ b/src/core/util/redact.ts @@ -2,7 +2,7 @@ * Redacts credential-bearing patterns from free text before it reaches an * output channel. * - * Applied to: error messages surfaced by the CLI runner (`src/cli/runner.ts`) and + * Applied to: error messages surfaced by the CLI runner (`src/cli/run/runner.ts`) and * HTTP error responses (`src/http/routes.ts`). * * NOT applied to successful stdout payloads: those are redacted where they are diff --git a/src/core/runtime.test.ts b/src/core/util/runtime.test.ts similarity index 100% rename from src/core/runtime.test.ts rename to src/core/util/runtime.test.ts diff --git a/src/core/runtime.ts b/src/core/util/runtime.ts similarity index 96% rename from src/core/runtime.ts rename to src/core/util/runtime.ts index e08f7b5..d7c34c1 100644 --- a/src/core/runtime.ts +++ b/src/core/util/runtime.ts @@ -77,7 +77,7 @@ export async function performRuntimeSelfHealing(): Promise<{ const legacySkillDir = join(homedir(), ".agents", "skills", "seal-home"); if (existsSync(legacySkillDir)) { // Ordinary discovery must not initialize the embedded resource graph. - (await import("./embedded-skill.js")).syncGlobalSkillIfPresent(); + (await import("../skill/embedded-skill.js")).syncGlobalSkillIfPresent(); result.skillHealed = true; } } catch { diff --git a/src/core/secure-file.test.ts b/src/core/util/secure-file.test.ts similarity index 100% rename from src/core/secure-file.test.ts rename to src/core/util/secure-file.test.ts diff --git a/src/core/secure-file.ts b/src/core/util/secure-file.ts similarity index 100% rename from src/core/secure-file.ts rename to src/core/util/secure-file.ts diff --git a/src/core/semver.ts b/src/core/util/semver.ts similarity index 100% rename from src/core/semver.ts rename to src/core/util/semver.ts diff --git a/src/domains/hose/onboarding.ts b/src/domains/hose/onboarding.ts index 7545bd2..292c047 100644 --- a/src/domains/hose/onboarding.ts +++ b/src/domains/hose/onboarding.ts @@ -275,7 +275,6 @@ export async function onboardHoseWebSession(input: HoseWebSessionInput) { }, source: { type: "hose", - provider: "hosecloud", domain: details.baseUrl, closeToken: input.accessToken, ...(input.expiresIn !== undefined ? { expiresIn: input.expiresIn } : {}), diff --git a/src/domains/hose/open/approval.ts b/src/domains/hose/open/approval.ts index e0563bb..0faf804 100644 --- a/src/domains/hose/open/approval.ts +++ b/src/domains/hose/open/approval.ts @@ -42,11 +42,11 @@ export async function executeEbotApprovalCallback( ); } - const appKey = corp.source.appKey ?? corp.source.key; - const appSecurity = corp.source.appSecurity ?? corp.source.password; + const appKey = corp.source.appKey; + const appSecurity = corp.source.appSecurity; if (!appKey || !appSecurity) { throw validationError( - `缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity(或 key/password),无法换取 accessToken 执行审批回调。` + `缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity,无法换取 accessToken 执行审批回调。` ); } diff --git a/src/domains/langfuse/client.ts b/src/domains/langfuse/client.ts index c34694f..43c22d9 100644 --- a/src/domains/langfuse/client.ts +++ b/src/domains/langfuse/client.ts @@ -1,5 +1,5 @@ import { CliError } from "../../core/errors.js"; -import { redactSensitiveText } from "../../core/redact.js"; +import { redactSensitiveText } from "../../core/util/redact.js"; import type { LangfuseConfig } from "./config.js"; export type HttpQuery = Record; diff --git a/src/domains/seal/api.ts b/src/domains/seal/api.ts index 3a40e51..afd0b49 100644 --- a/src/domains/seal/api.ts +++ b/src/domains/seal/api.ts @@ -9,7 +9,7 @@ import { import { CorpConfig } from "../../core/config/types.js"; import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js"; import { createSealClientForUrl } from "../../core/http/factory.js"; -import { redactSensitiveText } from "../../core/redact.js"; +import { redactSensitiveText } from "../../core/util/redact.js"; import { safetyBlocked, validationError } from "../../core/errors.js"; import { resolveSealCustomHeaders } from "../../core/http/request-headers.js"; import { diff --git a/src/domains/seal/approval-runs/export-task.ts b/src/domains/seal/approval-runs/export-task.ts index b566e8b..31d527b 100644 --- a/src/domains/seal/approval-runs/export-task.ts +++ b/src/domains/seal/approval-runs/export-task.ts @@ -6,9 +6,9 @@ import { join } from "node:path" import { z } from "zod" import { formatBeijingIso } from "../../../core/config/timestamps.js" import { validationError } from "../../../core/errors.js" -import type { LauncherConfig } from "../../../core/runtime.js" +import type { LauncherConfig } from "../../../core/util/runtime.js" import { VERSION } from "../../../version.js" -import { redactSensitiveText } from "../../../core/redact.js" +import { redactSensitiveText } from "../../../core/util/redact.js" // Persist only export controls, never the enterprise configuration or session. export const exportTaskOptionsSchema = z.object({ diff --git a/src/domains/seal/capabilities/rules.ts b/src/domains/seal/capabilities/rules.ts index 2257808..0b83333 100644 --- a/src/domains/seal/capabilities/rules.ts +++ b/src/domains/seal/capabilities/rules.ts @@ -8,7 +8,7 @@ import { executeRulePush } from "../rules/push.js"; import { formatBeijingIso } from "../../../core/config/timestamps.js"; import { loadGlobalConfig } from "../../../core/config/loader.js"; import { validationError } from "../../../core/errors.js"; -import { redactSensitiveText } from "../../../core/redact.js"; +import { redactSensitiveText } from "../../../core/util/redact.js"; import { searchApprovalContent } from "../search/service.js"; import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rules/diff.js"; import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rules/version-snapshot.js"; diff --git a/src/domains/seal/capabilities/simulation.ts b/src/domains/seal/capabilities/simulation.ts index 3ce1a2c..65b2196 100644 --- a/src/domains/seal/capabilities/simulation.ts +++ b/src/domains/seal/capabilities/simulation.ts @@ -10,7 +10,7 @@ import { type SimulationRuleSourceInput } from "../types.js"; import * as helpers from "./helpers.js"; -import { parseDurationMs } from "../../../core/duration.js"; +import { parseDurationMs } from "../../../core/util/duration.js"; import { batchTimestampMs, collectSimulationBatches, diff --git a/src/domains/seal/enterprise/onboarding.ts b/src/domains/seal/enterprise/onboarding.ts index 7d77e81..a14f767 100644 --- a/src/domains/seal/enterprise/onboarding.ts +++ b/src/domains/seal/enterprise/onboarding.ts @@ -28,7 +28,6 @@ export type SealBearerInput = { tenantName?: string; corpId?: string; staffId?: string; - provider?: string; headers?: unknown; cookies?: unknown; force?: boolean; @@ -93,7 +92,7 @@ export function persistSealDelegateSession(input: { const tenantId = stringValue(input.session.tenant.id); const corpId = tenantSlug ?? tenantId ?? "seal-delegate"; const saved = saveSealConfig( - { id: corpId, corpId, name: input.name, provider: "seal", overwrite: input.overwrite }, + { id: corpId, corpId, name: input.name, overwrite: input.overwrite }, { token: input.session.token, sealUrl: input.session.sealUrl, @@ -139,7 +138,6 @@ function saveSealConfig( ? normalizeBeijingIso(auth.expiresAt) : formatBeijingIso(Date.now() + auth.expiresIn * 1000); const staffId = input.staffId ?? stringValue(remoteUser?.providerUserId) ?? stringValue(remoteUser?.id) ?? "seal"; - const provider = input.provider ?? stringValue(remoteUser?.provider) ?? stringValue((remoteTenant as { providerConfig?: { provider?: unknown } } | undefined)?.providerConfig?.provider); const corpId = input.corpId ?? tenantSlug ?? tenantId ?? id; const config: CorpConfig = { id, @@ -163,8 +161,7 @@ function saveSealConfig( tenantId, tenantSlug, tenantName, - providerUserId: stringValue(remoteUser?.providerUserId), - provider + providerUserId: stringValue(remoteUser?.providerUserId) }, auth: { refreshTtl: 300 } }; diff --git a/src/domains/seal/reports/export/files.test.ts b/src/domains/seal/reports/export/files.test.ts index 13309ba..7e08ca4 100644 --- a/src/domains/seal/reports/export/files.test.ts +++ b/src/domains/seal/reports/export/files.test.ts @@ -3,7 +3,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from "node:os"; import { join } from "node:path"; import { PNG } from "pngjs"; -import { runCli } from "../../../../cli/runner.js"; +import { runCli } from "../../../../cli/run/runner.js"; import { buildMonthlyReport } from "../pipeline/index.js"; import { renderReportFile, saveReportMarkdown, validateReportFile } from "./files.js"; import { BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH } from "../templates/resources.js"; diff --git a/src/domains/seal/reports/README.md b/src/domains/seal/reports/reports.readme.md similarity index 97% rename from src/domains/seal/reports/README.md rename to src/domains/seal/reports/reports.readme.md index edbbafc..fe79df1 100644 --- a/src/domains/seal/reports/README.md +++ b/src/domains/seal/reports/reports.readme.md @@ -38,5 +38,5 @@ src/domains/seal/reports/ │ ├── resources.ts # Bun 编译期静态资源嵌入定义 │ └── assets/ # 内置图 1 矢量图表资产 ├── index.ts # 报告域对外统一门面出口 (Barrel) -└── README.md # 架构与开发指南 +└── reports.readme.md # 架构与开发指南 ``` diff --git a/src/domains/seal/reports/templates/README.md b/src/domains/seal/reports/templates/templates.readme.md similarity index 100% rename from src/domains/seal/reports/templates/README.md rename to src/domains/seal/reports/templates/templates.readme.md diff --git a/src/domains/seal/rules/export-csv.ts b/src/domains/seal/rules/export-csv.ts index b086787..8f00bda 100644 --- a/src/domains/seal/rules/export-csv.ts +++ b/src/domains/seal/rules/export-csv.ts @@ -3,7 +3,7 @@ import { join, resolve } from "node:path"; import type { KyInstance } from "ky"; import { formatBeijingIso } from "../../../core/config/timestamps.js"; import type { CorpConfig } from "../../../core/config/types.js"; -import { writeSecureFile } from "../../../core/secure-file.js"; +import { writeSecureFile } from "../../../core/util/secure-file.js"; import * as api from "../api.js"; import { sanitizeFileName } from "../approval-runs/attachments.js"; diff --git a/src/domains/seal/rules/push.test.ts b/src/domains/seal/rules/push.test.ts index 9a8df0b..d864ff5 100644 --- a/src/domains/seal/rules/push.test.ts +++ b/src/domains/seal/rules/push.test.ts @@ -6,7 +6,7 @@ import type { KyInstance } from "ky"; import type { CorpConfig } from "../../../core/config/types.js"; import { classifyCliError } from "../../../core/errors.js"; import { handleRulesCommand } from "../../../cli/commands/rules.js"; -import { parseArgs } from "../../../cli/parser.js"; +import { parseArgs } from "../../../cli/parse/parser.js"; import type { ApprovalRule } from "../types.js"; import { executeRulePush, diff --git a/src/domains/seal/rules/push.ts b/src/domains/seal/rules/push.ts index 7c0651e..f020a5b 100644 --- a/src/domains/seal/rules/push.ts +++ b/src/domains/seal/rules/push.ts @@ -6,7 +6,7 @@ import { formatBeijingIso } from "../../../core/config/timestamps.js"; import type { CorpConfig } from "../../../core/config/types.js"; import { CliError } from "../../../core/errors.js"; import { SEAL_STATE_DIR } from "../../../core/paths.js"; -import { redactSensitiveText } from "../../../core/redact.js"; +import { redactSensitiveText } from "../../../core/util/redact.js"; import * as api from "../api.js"; import { buildRulePushPlan, diff --git a/src/domains/seal/rules/recode.test.ts b/src/domains/seal/rules/recode.test.ts index 3a720a1..d2b941e 100644 --- a/src/domains/seal/rules/recode.test.ts +++ b/src/domains/seal/rules/recode.test.ts @@ -10,7 +10,7 @@ import { recodeApprovalRules } from "../api.js" import type { ApprovalRulesData } from "../types.js" import { runCapabilityResult } from "../../../cli/helpers.js" import { handleRulesCommand } from "../../../cli/commands/rules.js" -import { parseArgs } from "../../../cli/parser.js" +import { parseArgs } from "../../../cli/parse/parser.js" const originalStore = process.env.SEAL_USE_RECODE_STORE const dirs: string[] = [] diff --git a/src/domains/seal/simulation/batch-search.ts b/src/domains/seal/simulation/batch-search.ts index 9241f3e..9db508e 100644 --- a/src/domains/seal/simulation/batch-search.ts +++ b/src/domains/seal/simulation/batch-search.ts @@ -1,5 +1,5 @@ import type { KyInstance } from "ky"; -import { durationSeconds, tokenizeDuration } from "../../../core/duration.js"; +import { durationSeconds, tokenizeDuration } from "../../../core/util/duration.js"; import { validationError } from "../../../core/errors.js"; import * as api from "../api.js"; import type { SimulationBatch } from "../types.js"; diff --git a/src/domains/seal/testing/sync.ts b/src/domains/seal/testing/sync.ts index 8608866..d7729ef 100644 --- a/src/domains/seal/testing/sync.ts +++ b/src/domains/seal/testing/sync.ts @@ -318,9 +318,9 @@ interface HosecloudSyncResult { async function syncHosecloudIntegrationsToTest(prodCorp: CorpConfig, testCorp: CorpConfig, prodClient: KyInstance, testClient: KyInstance): Promise { if (prodCorp.source.type !== "hose") return { skipped: true, reason: "prod source is not hose; no hosecloud credentials available" }; - const appKey = (prodCorp.source.appKey ?? prodCorp.source.key)?.trim(); - const appSecurity = (prodCorp.source.appSecurity ?? prodCorp.source.password)?.trim(); - if (!appKey || !appSecurity) return { skipped: true, reason: "prod hose source missing appKey/appSecurity (or key/password)" }; + const appKey = prodCorp.source.appKey?.trim(); + const appSecurity = prodCorp.source.appSecurity?.trim(); + if (!appKey || !appSecurity) return { skipped: true, reason: "prod hose source missing appKey/appSecurity" }; const [prodPref, testPref] = await Promise.all([ api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences), api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences) diff --git a/src/probe.test.ts b/src/probe.test.ts index e0165a3..d630b81 100644 --- a/src/probe.test.ts +++ b/src/probe.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { runCli } from "./cli/runner.js"; +import { runCli } from "./cli/run/runner.js"; const ENV_KEYS = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_DISABLE_BG_UPDATE"] as const; const ORIGINAL_ENV: Record = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]])); @@ -91,7 +91,6 @@ describe("seal-use probe stream contract", () => { expect(payload.corp).toEqual({ id: "demo-corp", name: "Demo Corp", sourceType: "seal" }); expect(payload.enterprise).toMatchObject({ - provider: "seal", sealUrl: "https://demo-corp.sealai.cc", tenantName: "Demo Tenant" }); diff --git a/src/probe.ts b/src/probe.ts index 8b7f6a8..7a6c383 100644 --- a/src/probe.ts +++ b/src/probe.ts @@ -4,7 +4,7 @@ import { createSealClient } from "./core/http/factory.js"; import type { SealEnterpriseConfig } from "./core/auth/types.js"; import { resolveLiveSealEnterpriseConfig } from "./domains/seal/enterprise/source.js"; import { getApprovalContext } from "./domains/seal/api.js"; -import { printJson } from "./cli/printer.js"; +import { printJson } from "./cli/output/printer.js"; /** One probe run's payload — the entire stdout of `seal-use probe`. */ export type ProbeResult = { diff --git a/src/server.ts b/src/server.ts index 47f4c88..2365509 100644 --- a/src/server.ts +++ b/src/server.ts @@ -3,12 +3,12 @@ import { fileURLToPath } from "node:url"; import { McpServer, type CallToolResult } from "@modelcontextprotocol/server"; import { serveStdio, type StdioServerHandle } from "@modelcontextprotocol/server/stdio"; import { z } from "zod"; -import { runCli } from "./cli/runner.js"; -import { isReadOnlyCliCommand } from "./cli/read-only.js"; -import { normalizeCliArgs, tokenizeCommand } from "./cli/tokenize.js"; +import { runCli } from "./cli/run/runner.js"; +import { isReadOnlyCliCommand } from "./cli/run/read-only.js"; +import { normalizeCliArgs, tokenizeCommand } from "./cli/parse/tokenize.js"; import { classifyCliError } from "./core/errors.js"; import { VERSION } from "./version.js"; -import { isCompiledBinary, resolveAppRoot, resolveDefaultLauncher } from "./core/runtime.js"; +import { isCompiledBinary, resolveAppRoot, resolveDefaultLauncher } from "./core/util/runtime.js"; const serverEntryFile = fileURLToPath(import.meta.url); // Source servers and compiled CLI servers share the launcher rules. In a binary, diff --git a/src/src.readme.md b/src/src.readme.md new file mode 100644 index 0000000..8b28001 --- /dev/null +++ b/src/src.readme.md @@ -0,0 +1,17 @@ +# Source Layout & Module Organization + +`src/` is split into three layers. Dependencies flow in one direction only: +`cli → domains → core`. + +``` +src/ +├── cli/ # CLI surface: parse args, dispatch commands, render JSON on stdout +├── core/ # Cross-domain infrastructure: config, auth, HTTP, search, diagnostics +└── domains/ # Business domains: seal, hose, enterprise, langfuse +``` + +Entry points: `cli.ts` (CLI), `server.ts` (MCP stdio server), `probe.ts` (local +connectivity probe). + +The full contract, including where new code belongs, lives in the root +[`AGENTS.md`](../AGENTS.md) under "Project Structure & Module Organization". diff --git a/src/streams.test.ts b/src/streams.test.ts index 4325ecd..321337b 100644 --- a/src/streams.test.ts +++ b/src/streams.test.ts @@ -22,7 +22,7 @@ import { join, relative } from "node:path"; const SRC_DIR = join(import.meta.dir); const STDOUT_WRITERS = new Set([ - "cli/printer.ts", + "cli/output/printer.ts", "cli/commands/doctor.ts", "cli/commands/skill.ts", "cli.ts", diff --git a/wsl-infra/backup-workspace-scripts.sh b/wsl-infra/backup-workspace-scripts.sh deleted file mode 100755 index dc710c9..0000000 --- a/wsl-infra/backup-workspace-scripts.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bash -set -uo pipefail - -repo_root=$(git rev-parse --show-toplevel) -if [ -n "$(git -C "$repo_root" status --porcelain -- ops)" ]; then - echo "Refusing to back up uncommitted ops files; commit them first." >&2 - exit 1 -fi - -commit=$(git -C "$repo_root" rev-parse --short=12 HEAD) -snapshot="commit-$commit" -stage=$(mktemp -d) -trap 'rm -rf "$stage"' EXIT - -git -C "$repo_root" archive --format=tar HEAD ops | tar -xf - -C "$stage" -printf 'source_commit=%s\ncreated_at_utc=%s\n' \ - "$(git -C "$repo_root" rev-parse HEAD)" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ - > "$stage/BACKUP-MANIFEST.txt" - -local_target="$HOME/Workspace/ops-backups/seal-use/$snapshot" -mkdir -p "$local_target" -cp -R "$stage/." "$local_target/" -find "$local_target" -type f -name '._*' -delete -printf 'ok\tlocal\t%s\n' "$local_target" - -sync_remote() { - local host="$1" relative_target="$2" - if ssh -o BatchMode=yes -o ConnectTimeout=8 "$host" \ - "mkdir -p '$relative_target' && find '$relative_target' -type f -name '._*' -delete" \ - && scp -q -r "$stage/ops" "$stage/BACKUP-MANIFEST.txt" "$host:$relative_target/" \ - && ssh -o BatchMode=yes -o ConnectTimeout=8 "$host" \ - "test -s '$relative_target/BACKUP-MANIFEST.txt' && test -f '$relative_target/ops/README.md'"; then - printf 'ok\t%s\t%s\n' "$host" "$relative_target" - return 0 - fi - printf 'fail\t%s\t%s\n' "$host" "$relative_target" >&2 - return 1 -} - -failures=0 -sync_remote mac13 "Workspace/ops-backups/seal-use/$snapshot" || failures=$((failures + 1)) -sync_remote wsl-dev "workspace/ops-backups/seal-use/$snapshot" || failures=$((failures + 1)) -sync_remote aliyun "workspace/ops-backups/seal-use/$snapshot" || failures=$((failures + 1)) - -if [ "$failures" -gt 0 ]; then - printf '%s remote backup(s) failed\n' "$failures" >&2 - exit 1 -fi