16 KiB
Repository Guidelines
Project Structure & Module Organization
This is a Bun + TypeScript toolkit for the seal-use CLI and a local stdio MCP server (seal-use mcp). Entry points are src/cli.ts, src/server.ts, and src/probe.ts. Shared config, auth, token, and HTTP code is under src/core/. Seal-specific API and logic is under src/domains/seal/; the capability registry under src/domains/seal/capabilities/ holds the shared handlers dispatched by the CLI (runCapability) and allow-listed by the MCP gateways. Capability IDs are camelCase internal registry identifiers (for example sealApprovalContextGet) — the MCP surface only ever exposes the seal_use / seal_use_write gateway pair, never these names (see README "One registry, two doors"). The built-in read-only Langfuse trace domain lives under src/domains/langfuse/ with its own registry (langfuseCapabilities, dispatched by runLangfuseCapability); its client only issues GET, and its credentials are injected at compile time (SEAL_BUILD_LANGFUSE_*), never stored in the tree or in user config.
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.
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.
Tests are colocated as *.test.ts files in src/.
Build, Test, and Development Commands
bun install: install dependencies.bun run dev: runsrc/server.tswith watch mode.bun run start: run the MCP server once.bun run cli -- <args>: execute CLI commands, such asbun run cli version.bun run probe -- <corpId>: run the local connectivity/config probe.bun run check: type-check withtsc --noEmit(also enforcesnoUnusedLocals/noUnusedParameters).bun run lint: lint withoxlint src(zero-warning gate; CI fails on warnings).bun test: run all colocated Bun tests.bun run verify:agents-md: validate the rootAGENTS.mddeveloper 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 theskills/seal-use/SKILL.mdrouting hub (structure and bidirectionalreferences/routing); wired into pre-commit (staged docs only) and CI.bun run verify:readme: lightweight hygiene and structure checks forREADME.md(warnings only, never blocks).bun run bump <version | patch | minor>: 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.
Coding Style & Naming Conventions
Use TypeScript ES modules with explicit .js import extensions for local files. Validate external data with Zod or narrow types before use. Follow existing style: two-space indentation, double quotes, omitted trailing semicolons, camelCase variables/functions, PascalCase classes/types, and lowercase hyphenated filenames such as token-store.ts.
Prefer small domain functions over broad utility modules.
CLI & Agent Harness Protocol Guidelines
- Machine Channel (
stdout): Data commands MUST output clean, parseable JSON onstdout. Never dump human prose, raw logs, or progress banners intostdout. The Agent Harness parsesstdoutdirectly into typed payloads.- Documented exception — document-output commands:
seal-use --help/seal-use help <area>(src/cli/printer.ts),seal-use doctor guide(src/cli/commands/doctor.ts), andseal-use skill dump(src/cli/commands/skill.ts) intentionally write Markdown tostdout, 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 onstderrinstead.src/probe.tsis a local developer probe script rather than abinentry point, so its[probe] …lines are outside this contract.
- Documented exception — document-output commands:
- Guidance & Diagnostic Channel (
stderr): Usestderrfor runtime logs, network probing status, self-healing notifications, and explicit Next-Step Command Suggestions (e.g.👉 Next action: seal-use deploy hosecloud sync <signKey>). - 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 lazyawait 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/*.jsonsynchronously (<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-runreturning structured JSON previews withpreview: trueand a clean diff, without executing mutations. Live execution requires explicit--yesor--confirm. - Exit Code Contract:
0: Successful execution.1: Upstream API failure or domain business block (including quality gates such as a lint score below threshold).2: Malformed command line — parameter validation failure, unknown subcommand, or invalid JSON flag value.10: Safety gate block requiring user confirmation (--confirm/--yes).11: Missing or invalid authentication (HTTP 401/403, or an expired/missing/invalidtoken/bearer/session).12: Output protection — response exceeds the size limit; use--summary/--fields/--count/--output-file(or--fullwhen 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 letsrc/cli/runner.tshandle stream routing and exit code assignment.
Testing Guidelines
Use bun:test with describe, test, and expect. Place tests next to covered code using name.test.ts, for example src/core/config/loader.test.ts. Tests that change environment variables or working directories must restore them in afterEach. Ensure background tasks are guarded with SEAL_DISABLE_BG_UPDATE=1 or NODE_ENV=test during tests. Detailed test hygiene guidelines are in .agents/rules/testing.md.
Commit & Pull Request Guidelines
Recent commits use concise imperative subjects, often Add ... or Refine ..., such as Add compact approval rule listing. Keep subjects under roughly 72 characters. Branches created on a workstation must carry that device's prefix from git config seal.branchPrefix (e.g. mac15/improve-corp-search on this Mac), enforced by the .githooks pre-commit/pre-push guards. Specific workflows and domain guidelines are maintained in .agents/rules/:
- Branch naming (device-prefix rule & mechanical enforcement):
.agents/rules/branch-naming.md - Issue triage & PR workflow (No premature release):
.agents/rules/issue-pr-workflow.md - CLI stream & exit code protocol:
.agents/rules/cli-protocol.md - Testing conventions & isolation:
.agents/rules/testing.md - TypeScript & ESM conventions:
.agents/rules/typescript-style.md - Staging & test sandbox regression:
.agents/rules/staging-simulation.md - Webhook material pack & attachment policy:
.agents/rules/material-pack-policy.md - Security trade-offs (usability-first accepted risks):
.agents/rules/security-posture.md - Workspace hygiene (branch/worktree cleanup & release delta review):
.agents/rules/workspace-hygiene.md - Skill documentation layering & tool-agent boundaries:
.agents/rules/skill-documentation.md
Release & Publishing Guidelines
-
Automated Release Command (Preferred):
- Run
bun run release <patch | minor | major | version>(supports--dry-run). - This script automatically encapsulates the protected-branch release lifecycle:
- Pre-flight cleanliness &
ghauthentication checks. - Manifest version bumping (
bump-version.ts) & automaticCHANGELOG.mdentry generation. - Local validation (
bun test && bun run check). - Release branch creation (
codex/release-vX.Y.Z), commit, and push toorigin. - GitHub PR creation, CI monitoring, and merge.
- Main branch fast-forward (
git pull --ff-only origin main). - Annotated tag creation (
vX.Y.Z) and push toorigin(git push origin refs/tags/vX.Y.Z), with synchronous best-effort mirror tohome(Gitea). - Clean removal of temporary release branch.
- Pre-flight cleanliness &
- Run
-
Manual Protected-Branch Release & Workspace Isolation (Reference):
- Isolation Rule: If the main working directory contains uncommitted changes or another branch is actively being edited, NEVER switch branches or stash in the shared repository. Instead, use an isolated worktree for release operations:
git worktree add -b codex/release-vX.Y.Z /tmp/seal-use-release main cd /tmp/seal-use-release # Execute bump, commit, push, PR, merge, tag here # When finished, remove the worktree: git worktree remove /tmp/seal-use-release - Do not tag or push
maindirectly. Create a release branch, commit the version bump, push it, open a PR tomain, wait for the required CI check, and merge the PR first. - After the PR is merged, fast-forward the local
main, then create and push the annotated tag toorigin:git switch -c codex/release-vX.Y.Z git add <release-files> git commit -m "Release vX.Y.Z: ..." git push origin HEAD:refs/heads/codex/release-vX.Y.Z gh pr create --base main --head codex/release-vX.Y.Z --title "Release vX.Y.Z: ..." --body "..." gh pr checks <pr-number> --watch gh pr merge <pr-number> --merge git switch main git pull --ff-only origin main git tag -a vX.Y.Z -m "🚀 Release summary text describing key changes" 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.timerpolls GitHub every 15 minutes (or can be triggered immediately viasystemctl start seal-use-release-sync.service), mirrors Git repository refs (branches and tags) and pulls release assets into Gitea (wsl-infra/systemd/). - The workflow enforces the merge-before-tag rule rather than trusting the operator:
release.ymlrefuses to publish unless the tagged commit is an ancestor oforigin/main. Actions in both workflows are pinned to commit SHAs rather than moving tags for supply-chain integrity.
- Isolation Rule: If the main working directory contains uncommitted changes or another branch is actively being edited, NEVER switch branches or stash in the shared repository. Instead, use an isolated worktree for release operations:
Security & Configuration Tips
Never commit real enterprise credentials, Seal tokens, service logs, or local generated state. Enterprise configs live only in ~/.config/seal-use/enterprises (with legacy fallback to ~/.config/seal-home/enterprises); the project tree carries none. For auth or tenant changes, verify with bun run probe or seal-use auth diagnose.
Documented exception: the Langfuse read-only key pair for seal-use langfuse is injected at compile time (SEAL_BUILD_LANGFUSE_* — repository secrets in release.yml for releases; for developer builds, shell env vars or the repo-local gitignored .env.langfuse, never under ~/.config, which is user config space) and is never written to the tree or to user config; src/domains/langfuse/client.ts is GET-only, which is what makes the embedded key safe to ship. See SECURITY.md.
Credential files are written 0600; a config placed by hand keeps the 0o644 default, so run seal-use doctor and act on its credential_permissions check before sharing a machine or a backup. See SECURITY.md for the trust model (self-update, custom linters).
Agent-Specific Instructions
Do not create .codex/skills; Codex is compatible with .agents/skills, and this project treats .agents/ as authoritative. At project scope, prefer AGENTS.md instructions when present.
Skill Documentation Layering & Traffic Routing Discipline
- Main
skills/<skill>/SKILL.mdis a Lightweight Traffic Routing Hub (精准路由中枢): KeepSKILL.mdlean, structured, and focused on discovery, installation, universal conventions, and the Reference Routing Table (## 参考文档路由). ## 参考文档路由is the Terminal Anchor (锁死收尾锚点): The## 参考文档路由section MUST be the final H2 heading ofSKILL.md. Never append new feature sections, diagnostic guides, or ad-hoc instructions after it; all detailed manuals belong inreferences/.- NEVER bloat
SKILL.mdinto a feature billboard: Do NOT write lengthy multi-step workflows, full section breakdowns, extensive table schemas, or qualitative debate procedures intoSKILL.md. - Overcome Locality Bias (杜绝“就近修改”惯性): When developing or extending a feature, do not casually append detailed guides to
SKILL.mdjust because it is open or visible. Always place the detailed manual inskills/<skill>/references/<topic>.md, and keepSKILL.mdstrictly to a one-line routing table entry. references/*.mdis the Single Source of Truth: All operational guides, schema specifications, business debate workflows (Tangent), and troubleshooting catalogs belong inreferences/.- Deterministic Wrench vs. Agent Discretion (CLI 是扳手,Agent 自由裁量):
- The CLI provides deterministic, repeatable tooling: data fetching, ledger export/import, offline schema/math gates, and self-contained rendering.
- The Agent and user exercise business discretion: pruning templates, filtering dirty rows in local ledgers, debating edge cases, and authoring qualitative takeaways.
- Strict Offline Boundary: When driven by a local file (
--ledger 台账.xlsx), the CLI treats the local file as the absolute boundary and NEVER queries cloud APIs for rows deleted or pruned from the file. The validation gate checks only internal consistency. See.agents/rules/skill-documentation.md.