Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
docs(agents): add CLAUDE.md mirror and policy-sync gate
Zihao Peng128182732829
diff --git a/.github/workflows/docs-check.yml b/.github/workflows/docs-check.ymlindex f0f5993df..2099a04c0 100644--- a/.github/workflows/docs-check.yml+++ b/.github/workflows/docs-check.yml@@ -2,9 +2,10 @@ name: Docs check# ci.yml ignores docs/** and **/*.md, so documentation drift was never caught.# This workflow runs the documentation checks: the English/Chinese pair check,-# the whole-tree page/ADR check, and a VitePress build, which fails on a dead-# link anywhere in the tree. `check:release-docs` stays out of CI on purpose-# because it intentionally fails on rc versions.+# the whole-tree page/ADR check, the AGENTS.md/CLAUDE.md policy-sync gate, and+# a VitePress build, which fails on a dead link anywhere in the tree.+# `check:release-docs` stays out of CI on purpose because it intentionally+# fails on rc versions.on:push:@@ -12,6 +13,8 @@ on:paths:- 'docs/**'- 'README*.md'+ - 'AGENTS.md'+ - 'CLAUDE.md'- 'packages/shared/src/changelog*.ts'- 'scripts/check-*.mjs'- 'docs/scripts/**'@@ -20,6 +23,8 @@ on:paths:- 'docs/**'- 'README*.md'+ - 'AGENTS.md'+ - 'CLAUDE.md'- 'packages/shared/src/changelog*.ts'- 'scripts/check-*.mjs'- 'docs/scripts/**'@@ -52,6 +57,9 @@ jobs:- name: Install dependenciesrun: pnpm install --frozen-lockfile+ - name: Check AGENTS.md / CLAUDE.md policy sync+ run: pnpm check:agent-policy+- name: Check locale pairs and every documentation pagerun: pnpm docs:checkdiff --git a/AGENTS.md b/AGENTS.mdindex b9eaf649e..38454fa99 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,7 +1,15 @@# AGENTS.md+Policy-Sync: 2026-02-16.1+Mandatory rules for AI coding agents working in PI-Desktop.+`CLAUDE.md` is the Claude Code / Claude Cowork entry point and a condensed+mirror of the non-negotiables in this file. This file is authoritative.+When you change either file, update the other so the non-negotiables stay+aligned, and set the same `Policy-Sync:` token in both. The gate is+`pnpm check:agent-policy` (`scripts/check-agent-policy-sync.mjs`).+PI-Desktop is released software with real users. Treat every change as production maintenance, not prototype work.Optimize for:diff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 000000000..87f1bcd55--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1,288 @@+# CLAUDE.md++Policy-Sync: 2026-02-16.1++Instructions for Claude Code CLI and Claude Cowork on PI-Desktop.++**Authoritative policy:** [`AGENTS.md`](AGENTS.md). Read it before any non-trivial change. If this file and `AGENTS.md` disagree, follow `AGENTS.md`. Domain specs under `docs/spec/` remain authoritative for product behavior, protocols, and security boundaries.++**Mirror sync:** This file condenses `AGENTS.md` for Claude Code. When policy changes, update both files, keep the shared non-negotiables aligned, and set the same `Policy-Sync:` token in both. Enforced by `pnpm check:agent-policy` (`scripts/check-agent-policy-sync.mjs`).++PI-Desktop is released software with real users. Treat every change as production maintenance, not prototype work.++Priority order when deciding what to do:++1. Correctness and user data safety+2. Security and backward compatibility+3. Architectural integrity+4. Testability and maintainability+5. Delivery speed++Optimize for changing the system safely, not merely changing it quickly.++---++## Hard rules (do not negotiate)++### Worktree isolation++Every request uses:++```text+1 request = 1 branch + 1 dedicated worktree+```++- Never develop on `main` or in the primary checkout.+- Never merge unvalidated task code into local `main`.+- Never reuse, modify, or delete another agent's branch or worktree.+- Never discard unrelated work in the primary checkout.+- Resolve conflicts only inside your own task worktree.++Create the worktree from current remote `main`:++```bash+git fetch origin main+git worktree add \+ -b <type>/<short-description> \+ <worktree-path> \+ origin/main+cd <worktree-path>+```++Suggested worktree path: `../PI-Desktop-worktrees/<short-description>`.++Branch names: `feat/...`, `fix/...`, `docs/...`, `refactor/...`, `chore/...`.++### Delivery order (code-bearing changes)++```text+1. branch + worktree from origin/main+2. implement in the worktree+3. targeted static/unit/integration checks+4. review the full diff+5. commit+6. fetch + rebase/refresh against latest origin/main (private branch)+7. resolve conflicts in the worktree+8. task-candidate E2E in the same worktree+9. push branch+10. open/update PR+11. PR integration validation+12. merge into remote main through repository gates+13. synchronize local main+14. remove your worktree and merged local branch+```++Do **not** insert `merge task → local main` between refresh and task-candidate E2E. The task branch itself is the local integration candidate after incorporating latest `origin/main`.++Record E2E evidence:++```text+Task candidate:+Base main:+E2E suites:+Result:+Environment:+```++If a required suite cannot run, report `NOT RUN` with reason, alternative validation, and remaining risk. Never report a skipped command as passing.++### Architecture (frozen)++```text+Renderer → Preload IPC → Electron Main → Rust Host Core / Node Agent Runtime → pi-ai / pi-agent-core+```++Ownership:++```text+Renderer = UI and interaction+Electron Main = thin orchestrator+Rust Host Core = persistence and authoritative host/native state+Agent Runtime = agent execution+Plugin SDK = extension contract+Shared = cross-boundary contracts and schemas+```++Boundaries you must not break:++- Renderer never touches SQLite or Electron Main internals.+- SQLite is owned exclusively by Rust `host-core`.+- Agent execution does not move into the renderer.+- Electron Main stays a thin orchestrator.+- Shared packages do not depend on desktop implementation code.+- Plugin permissions and sandbox boundaries are never bypassed.++Changing a frozen architecture, public interface, data ownership model, or security boundary requires an ADR under `docs/adr/`.++### Behavior and data safety++Unless the task explicitly requires a behavior change, do not:++- remove functionality or change user-visible defaults+- change persisted data semantics without migration+- change IPC/RPC or Plugin SDK contracts+- weaken security, permissions, sandbox, or URL/filesystem checks+- hide behavior changes inside a `refactor` commit++Database / schema changes need migration, schema version bump, upgrade compatibility, tests, and spec updates. Never assume an empty database.++### Architecture ratchet++Do not pile new logic into God Modules. Prefer shrink-or-stay-stable for:++```text+apps/desktop/electron/main/index.ts+apps/desktop/src/stores/app-store.ts+apps/desktop/src/components/ChatTranscript.tsx+apps/desktop/src/components/Composer.tsx+crates/host-core/src/plugins.rs+crates/host-core/src/db.rs+crates/host-core/src/providers.rs+crates/host-core/src/plans.rs+```++New logic belongs in the domain module that owns the state or process boundary. Facades stay for compatibility only.++Size guidance:++- new TS/TSX modules normally < ~500 LOC; reconsider around ~800+- new Rust modules normally < ~700 LOC; reconsider around ~1000+- generated files, locales, fixtures, declarative data are exempt++Keep diffs small and coherent: one concern, no drive-by cleanup, no unrelated formatting or dependency bumps.++### Security and errors++Least privilege for filesystem, shell, network, plugins, MCP, clipboard, and credentials. Never “fix” a feature by weakening a permission check or sandbox.++Avoid unnecessary `any`, `as any`, `@ts-ignore`, `@ts-nocheck`. Avoid Rust `unwrap()` / `expect()` on normal external failure paths. Do not silently swallow unexpected errors. Failures must stay observable without leaking secrets.++Never commit API keys, tokens, credentials, local DBs, logs, `node_modules/`, build artifacts, or machine-specific paths.++---++## Read before you change++Minimum for any implementation:++1. [`docs/spec/00-baseline.md`](docs/spec/00-baseline.md) — frozen product/architecture decisions+2. Relevant specs under [`docs/spec/`](docs/spec/) (see [`docs/spec/NAV.md`](docs/spec/NAV.md))+3. Relevant ADRs under `docs/adr/`+4. [`docs/spec/06-delivery/03-ai-development-workflow.md`](docs/spec/06-delivery/03-ai-development-workflow.md)+5. [`docs/spec/06-delivery/04-e2e-test-plan.md`](docs/spec/06-delivery/04-e2e-test-plan.md)+6. [`docs/spec/06-delivery/05-change-checklist.md`](docs/spec/06-delivery/05-change-checklist.md)++Also useful:++- [`CONTRIBUTING.md`](CONTRIBUTING.md) — human-facing process (when it conflicts with `AGENTS.md` workflow, `AGENTS.md` wins)+- [`docs/spec/02-architecture/03-repo-structure.md`](docs/spec/02-architecture/03-repo-structure.md) — layout+- [`SECURITY.md`](SECURITY.md) — private vulnerability reporting++Use **English** for code, identifiers, comments, commits, specs, ADRs, and repository docs. GitHub issue/PR discussion may match the original author's language.++Observable behavior changes must update the relevant spec. User-visible or protocol-visible changes must update the corresponding E2E scenario docs. New E2E scenario IDs are semantic, e.g. `E2E-SESSION-switch-does-not-show-stale-transcript`.++---++## Repo map++```text+apps/desktop/ Electron app+ electron/main|preload|shared/+ src/ React renderer (components, stores, lib, pages, hooks)+ test/ node --test suites+crates/host-core/ Rust privileged host (binary pi-desktop-host-core)+packages/+ shared/ IPC/protocol contracts, error codes+ i18n/ UI catalogs+ agent-runtime/ pi sidecar wrapper+ plugin-sdk/ plugin author types/validators+ plugin-devkit/ pi-plugin CLI+examples/plugins/ sample plugins+docs/spec|adr|guide/ specs, ADRs, user guide+scripts/ repo automation and E2E scripts+```++pnpm owns JS packages; Cargo owns Rust. Root scripts fan out to both. Toolchain: Node ≥ 22.19, pnpm ≥ 10 (repo pins `[email protected]`).++---++## Validation commands++Run only checks that match the affected surface. Prefer the narrower authoritative gate over ceremonial full runs.++| Surface | Typical checks |+| --- | --- |+| JS packages | `pnpm build:js` · `pnpm --filter @pi-desktop/desktop typecheck` · `pnpm lint` · `pnpm -r --if-present test` |+| Rust host-core | `cargo fmt --check` · `cargo test -p host-core --locked` · `cargo clippy -p host-core --all-targets` |+| Full local | `pnpm typecheck` · `pnpm test` |+| Architecture budgets | see `scripts/check-architecture.mjs` |+| E2E | `pnpm test:e2e` and targeted `pnpm test:e2e:*` scripts |++E2E exists to validate **executable integration state** (latest applicable `main` + task changes), not merely the branch name `main`. Run required E2E on the task candidate after refreshing against latest `origin/main`.++Docs-only changes: review rendered Markdown and `git diff --check`; no runtime tests required.++---++## Claude Code session checklist++Before editing:++1. Confirm you are (or will create) a dedicated worktree — not the primary checkout, not `main`.+2. Identify observable behavior, persistence, protocol, security, and architecture impact.+3. Read the relevant spec/ADR and list the validation you will run.+4. For a linked issue, verify the claim against current code first. For a linked PR, preserve a sound direction; do not force-push contributor branches.++While editing:++- One logical concern; no unrelated cleanup.+- Preserve process boundaries and contracts.+- Prefer domain modules over expanding facades or the central store.+- Update specs/ADRs/E2E scenario docs when behavior is observable.+- Keep long-lived resources (listeners, timers, watchers, MCP, child processes) owned and cleaned up across reload, project/session switch, disable, and shutdown.+- Never assume state is unchanged across `await` (stale results, cancellation, duplicate runs, races).++Before finishing:++1. Run the targeted validation set for the change.+2. Review the complete diff (`git diff`). No secrets, no unrelated files.+3. Commit with Conventional Commits, English, one logical commit when practical:++```text+feat(composer): add model selection shortcut+fix(host-core): preserve session ownership during restart+docs(spec): clarify plan checkpoint wording+```++4. Refresh against latest `origin/main` if preparing a PR candidate.+5. Run required task-candidate E2E when the change is code-bearing.+6. Report exactly what ran, what did not, and residual risk.++Do not push, open a PR, or merge unless the user explicitly asks.++---++## Issue and PR intake++**Issue:** fetch, read body/comments/labels, verify against code. Bugs: reproduce or give concrete evidence; classify as confirmed regression / existing defect / already fixed / expected behavior / environment-specific / insufficient evidence. Do not implement first and investigate later.++**PR:** judge principle and direction before replacing work. Preserve authorship on a sound PR. Landing blockers include build/typecheck/test/E2E failure, merge conflict, data corruption risk, security violation, secret leakage, sandbox bypass, incompatible protocol change.++Security reports are private via `SECURITY.md` — never open a public issue for vulnerabilities or credential exposure.++---++## Quick “where do I put this?”++| Change | Put it in |+| --- | --- |+| UI rendering / interaction | `apps/desktop/src/` components or feature modules |+| Renderer workflow logic | hooks / services / `lib/` — not the central Zustand store |+| IPC surface | preload + `packages/shared/` contracts + main handlers |+| Persistence / schema / host tools | `crates/host-core/` domain modules |+| Agent execution | `packages/agent-runtime/` / host orchestration — not renderer |+| Plugin API | `packages/plugin-sdk/` + host plugin modules; update plugin specs |+| Cross-cutting protocol types | `packages/shared/` |++When unsure which layer owns a concern, follow the frozen process model and existing domain modules — do not invent a new boundary without an ADR.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 4be754459..a1de95ea8 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -12,6 +12,9 @@ public interfaces.Read the documents relevant to your change:- [`AGENTS.md`](AGENTS.md) — repository rules for contributors and agents.+- [`CLAUDE.md`](CLAUDE.md) — Claude Code / Cowork mirror of the non-negotiables.+ When you change either policy file, update the other, set the same+ `Policy-Sync:` token, and run `pnpm check:agent-policy`.- [`README.md`](README.md) — product overview and development context.- [`docs/spec/00-baseline.md`](docs/spec/00-baseline.md) — frozen architectureand product decisions.diff --git a/docs/spec/06-delivery/05-change-checklist.md b/docs/spec/06-delivery/05-change-checklist.mdindex 8374a0836..dec5a5628 100644--- a/docs/spec/06-delivery/05-change-checklist.md+++ b/docs/spec/06-delivery/05-change-checklist.md@@ -97,6 +97,9 @@ Reference the [spec update matrix](03-ai-development-workflow.md#3-spec-update-mAfter implementation (or alongside it):- [ ] Every affected spec file is updated with the new behavior.+- [ ] If `AGENTS.md` changed: `CLAUDE.md` still mirrors the non-negotiables,+ both files share the same `Policy-Sync:` token, and `pnpm check:agent-policy`+ passes. The reverse applies when only `CLAUDE.md` changed.- [ ] If architectural boundary changed: ADR is written or updated in `docs/adr/`.- [ ] If an implementation default changed: `decisions-log.md` entry updated.- [ ] If baseline frozen decisions are affected: baseline bump + explicit ADR (not MVP-normal).diff --git a/package.json b/package.jsonindex 8cd5c18ee..a75a93669 100644--- a/package.json+++ b/package.json@@ -38,6 +38,7 @@"test:e2e:subagent-models": "node scripts/e2e-subagent-models.mjs","check:marketplace": "node scripts/check-marketplace-catalog.mjs","check:release-docs": "node scripts/check-release-docs.mjs",+ "check:agent-policy": "node scripts/check-agent-policy-sync.mjs","docs:dev": "pnpm --filter @pi-desktop/docs dev","docs:build": "pnpm --filter @pi-desktop/docs build","docs:preview": "pnpm --filter @pi-desktop/docs preview",diff --git a/scripts/README.md b/scripts/README.mdindex ad5e41bca..a554beba3 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -14,6 +14,7 @@ disagrees, so a green `check:release-docs` is a precondition, not a substitute.|---|---|---|| `release.mjs` | `node scripts/release.mjs <version> [--tag]` | Bump every workspace version surface, commit, and optionally create the `vX.Y.Z` tag the Release workflow builds from || `check-release-docs.mjs` | `pnpm check:release-docs` | Verify the changelog, its test list, `APP_VERSION`, workspace versions, Cargo versions, and both README release lines agree |+| `check-agent-policy-sync.mjs` | `pnpm check:agent-policy` | Verify `AGENTS.md` and `CLAUDE.md` share the same `Policy-Sync` token, cross-references, and non-negotiable policy anchors || `check-marketplace-catalog.mjs` | `pnpm check:marketplace -- --url <url> --plugin <id>` | Marketplace catalog preflight; rejects a version record missing a checksum, package URL, size, or permissions, and a catalog `author` that is not a string || `check-style-tokens.mjs` | run by the desktop `lint` script | Fail renderer styles that hardcode values instead of design-system tokens |diff --git a/scripts/check-agent-policy-sync.mjs b/scripts/check-agent-policy-sync.mjsnew file mode 100644index 000000000..fe81f70b9--- /dev/null+++ b/scripts/check-agent-policy-sync.mjs@@ -0,0 +1,216 @@+#!/usr/bin/env node+/**+ * Agent policy mirror check: AGENTS.md and CLAUDE.md must stay in sync.+ *+ * Usage:+ * node scripts/check-agent-policy-sync.mjs+ * pnpm check:agent-policy+ *+ * AGENTS.md is the authoritative AI-agent policy. CLAUDE.md is the Claude Code+ * / Cowork entry point and a condensed mirror of the non-negotiables. Changing+ * one without the other is documentation drift and fails this gate.+ *+ * Enforced:+ * 1. Both files exist at the repository root.+ * 2. Both declare the same `Policy-Sync: <token>` revision near the top.+ * 3. CLAUDE.md names AGENTS.md as authoritative; AGENTS.md names CLAUDE.md+ * as the Claude Code mirror that must stay synchronized.+ * 4. Shared non-negotiable policy anchors appear in both files (normalized+ * whitespace, case-insensitive).+ *+ * When policy text changes:+ * - update the affected file(s) so the non-negotiables remain aligned;+ * - bump the `Policy-Sync:` token in BOTH files to the same new value;+ * - run `pnpm check:agent-policy`.+ */+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import path from "node:path";++const root = fileURLToPath(new URL("..", import.meta.url));+const failures = [];++const read = (relPath) => {+ try {+ return readFileSync(path.join(root, relPath), "utf8");+ } catch {+ failures.push(`${relPath}: file is missing`);+ return null;+ }+};++const normalize = (text) =>+ text+ .replace(/[→↓]/g, " ")+ .replace(/\s+/g, " ")+ .trim()+ .toLowerCase();++const agentsRaw = read("AGENTS.md");+const claudeRaw = read("CLAUDE.md");+const agents = agentsRaw ? normalize(agentsRaw) : "";+const claude = claudeRaw ? normalize(claudeRaw) : "";++// Shared non-negotiables. Each anchor is a distinctive phrase (or alternate+// phrases) that must remain true in both the authoritative policy and the+// Claude Code mirror. Prefer stable wording over section titles.+/** @type {{ id: string, anyOf: string[] }[]} */+const REQUIRED_ANCHORS = [+ {+ id: "worktree-isolation",+ anyOf: ["1 request = 1 branch + 1 dedicated worktree"],+ },+ {+ id: "never-develop-on-main",+ anyOf: [+ "never develop on `main`",+ "never develop directly on `main`",+ "develop directly on `main`",+ ],+ },+ {+ id: "process-model",+ anyOf: [+ "renderer preload ipc electron main rust host core / node agent runtime",+ ],+ },+ {+ id: "sqlite-host-core-only",+ anyOf: [+ "sqlite remains owned exclusively by rust host-core",+ "sqlite is owned exclusively by rust host-core",+ "sqlite remains owned exclusively by rust `host-core`",+ "sqlite is owned exclusively by rust `host-core`",+ ],+ },+ {+ id: "main-thin-orchestrator",+ anyOf: ["electron main must remain a thin orchestrator", "electron main stays a thin orchestrator"],+ },+ {+ id: "no-local-main-before-e2e",+ anyOf: ["merge task → local main"],+ },+ {+ id: "task-candidate-e2e",+ anyOf: ["task-candidate e2e"],+ },+ {+ id: "architecture-ratchet-hotspots",+ anyOf: [+ "apps/desktop/src/stores/app-store.ts",+ "crates/host-core/src/db.rs",+ ],+ },+ {+ id: "preserve-behavior-default",+ anyOf: [+ "unless the task explicitly requires",+ "unless the task explicitly requires behavior to change",+ ],+ },+ {+ id: "never-weaken-security",+ anyOf: [+ "never fix functionality by weakening",+ "never “fix” a feature by weakening",+ 'never "fix" a feature by weakening',+ "never fix a feature by weakening",+ ],+ },+ {+ id: "adr-for-frozen-boundaries",+ anyOf: [+ "changing a frozen architecture, public interface, data ownership model, or security boundary requires an adr",+ "requires an adr under `docs/adr/`",+ ],+ },+ {+ id: "specs-stay-synchronized",+ anyOf: ["observable behavior changes must update the relevant spec"],+ },+];++function requireContains(label, haystack, needle, message) {+ if (!haystack.includes(needle)) {+ failures.push(`${label}: ${message}`);+ }+}++if (agentsRaw && claudeRaw) {+ const syncToken = /policy-sync:\s*`?([^\s`]+)`?/i;++ const agentsToken = agentsRaw.match(syncToken)?.[1];+ const claudeToken = claudeRaw.match(syncToken)?.[1];++ if (!agentsToken) {+ failures.push(+ 'AGENTS.md: missing `Policy-Sync: <token>` (for example `Policy-Sync: 2026-02-14.1`)',+ );+ }+ if (!claudeToken) {+ failures.push(+ 'CLAUDE.md: missing `Policy-Sync: <token>` (for example `Policy-Sync: 2026-02-14.1`)',+ );+ }+ if (agentsToken && claudeToken && agentsToken !== claudeToken) {+ failures.push(+ `Policy-Sync token mismatch: AGENTS.md has \`${agentsToken}\`, CLAUDE.md has \`${claudeToken}\`. Update both mirrors and set the same new token.`,+ );+ }++ requireContains(+ "CLAUDE.md",+ claude,+ "agents.md",+ "must name AGENTS.md as the authoritative policy",+ );+ requireContains(+ "CLAUDE.md",+ claude,+ "authoritative",+ "must state that AGENTS.md is authoritative",+ );+ requireContains(+ "AGENTS.md",+ agents,+ "claude.md",+ "must name CLAUDE.md as the Claude Code mirror and require it to stay synchronized",+ );++ for (const anchor of REQUIRED_ANCHORS) {+ const inAgents = anchor.anyOf.some((phrase) => agents.includes(normalize(phrase)));+ const inClaude = anchor.anyOf.some((phrase) => claude.includes(normalize(phrase)));+ if (!inAgents && !inClaude) {+ failures.push(+ `policy anchor \`${anchor.id}\`: missing from both AGENTS.md and CLAUDE.md (looked for: ${anchor.anyOf+ .map((p) => `"${p}"`)+ .join(" | ")})`,+ );+ } else if (!inAgents) {+ failures.push(+ `policy anchor \`${anchor.id}\`: present in CLAUDE.md but missing from AGENTS.md`,+ );+ } else if (!inClaude) {+ failures.push(+ `policy anchor \`${anchor.id}\`: present in AGENTS.md but missing from CLAUDE.md — update the Claude Code mirror and bump Policy-Sync in both files`,+ );+ }+ }+}++if (failures.length > 0) {+ console.error("Agent policy sync check failed:\n");+ for (const failure of failures) {+ console.error(` - ${failure}`);+ }+ console.error(+ "\nAGENTS.md is authoritative. Update the other mirror, keep non-negotiables aligned,",+ );+ console.error(+ "and set the same `Policy-Sync:` token in both files. Then re-run: pnpm check:agent-policy",+ );+ process.exit(1);+}++console.log("Agent policy sync check passed (AGENTS.md ↔ CLAUDE.md).");