From 5bfc36572d03030e4616a32064dc29779f94bb25 Mon Sep 17 00:00:00 2001 From: agent-kit-sync Date: Sat, 28 Nov 2026 21:34:26 +0000 Subject: [PATCH] chore: sync private v6.25.0 (5be4cff54) --- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- .cursor/agent-kit.json | 2 +- .cursor/commands/update.md | 9 +- .cursor/context/config.example.json | 2 +- .cursor/rules/cursor-skills-api.mdc | 46 +- .cursor/rules/cursor-skills-devops.mdc | 55 +- .cursor/rules/cursor-skills-general.mdc | 35 +- .cursor/rules/cursor-skills-groovy.mdc | 16 - .cursor/rules/cursor-skills-integrations.mdc | 45 +- .cursor/rules/cursor-skills-json.mdc | 2 +- .cursor/rules/cursor-skills-mobile.mdc | 42 +- .cursor/rules/cursor-skills-n8n.mdc | 2 +- .cursor/rules/cursor-skills-node.mdc | 45 +- .cursor/rules/cursor-skills-php.mdc | 52 +- .cursor/rules/cursor-skills-prompts.mdc | 2 +- .cursor/rules/cursor-skills-python.mdc | 50 +- .cursor/rules/cursor-skills-sql.mdc | 2 +- .cursor/rules/cursor-skills-testing.mdc | 45 +- .cursor/rules/cursor-skills-webdesign.mdc | 40 +- .cursor/scripts/run-plan-all-consolidate.sh | 199 ++++- .../community/cursor-skills-node/SKILL.md | 47 +- .../core/hitl-gates/run-plan-all-queue.md | 2 +- .gitignore | 3 + CHANGELOG.md | 39 + PRIVACY.md | 2 +- README.md | 2 +- categories.md | 6 +- claude-directory/.claude-plugin/plugin.json | 2 +- claude-directory/README.md | 2 +- dashboard/dashboard-data.mjs | 131 ++- dashboard/dashboard.html | 49 +- dashboard/lib/live-refresh.mjs | 1 + docs/bootstrap.md | 2 +- docs/capability-inventory.md | 3 +- docs/coherence-inventory.md | 3 +- docs/consumer-configuration.md | 73 +- .../mission-control-snapshot.schema.json | 67 +- docs/cursor-native-audit.md | 3 +- docs/drift-inventory.md | 2 +- docs/getting-started.md | 21 +- docs/install-ubuntu24-bare-metal.md | 2 +- docs/layers-spec.md | 2 +- docs/marketplace.md | 2 +- docs/mission-control-embedding.md | 4 +- docs/multiple-machines.md | 2 +- gemini-extension.json | 2 +- package.json | 2 +- packages/cli/README.md | 1 + packages/cli/package.json | 2 +- packages/cli/src/commands/add.ts | 19 +- packages/cli/src/commands/countdown.test.ts | 572 ++++++++++++ packages/cli/src/commands/countdown.ts | 422 ++++++++- packages/cli/src/commands/diff.ts | 7 + packages/cli/src/commands/doctor.test.ts | 103 ++- packages/cli/src/commands/doctor.ts | 148 +++- packages/cli/src/commands/handoff.test.ts | 4 +- packages/cli/src/commands/handoff.ts | 2 + packages/cli/src/commands/init.test.ts | 9 + packages/cli/src/commands/init.ts | 2 + packages/cli/src/commands/install.test.ts | 9 + packages/cli/src/commands/install.ts | 41 +- packages/cli/src/commands/installs.ts | 237 +++++ packages/cli/src/commands/update-all.test.ts | 408 +++++++++ packages/cli/src/commands/update-all.ts | 823 ++++++++++++++++++ .../src/commands/update-legacy-pack.test.ts | 222 +++++ .../commands/update-retired-skills.test.ts | 180 ++++ packages/cli/src/commands/update.test.ts | 21 +- packages/cli/src/commands/update.ts | 355 +++++--- .../dashboard/dashboard-data-snapshot.test.ts | 232 +++++ .../dashboard/plugin-ux-validation.test.ts | 65 ++ packages/cli/src/hooks/session-start.test.ts | 48 + packages/cli/src/hooks/session-start.ts | 44 +- packages/cli/src/index.ts | 1 + packages/cli/src/installs/index.ts | 80 ++ packages/cli/src/installs/inspect.ts | 243 ++++++ packages/cli/src/installs/installs.test.ts | 422 +++++++++ packages/cli/src/installs/scan.ts | 112 +++ packages/cli/src/installs/store.ts | 275 ++++++ .../cli/src/invariants/shell-guard.test.ts | 103 +++ packages/cli/src/invariants/shell-guard.ts | 65 +- .../cli/src/lifecycle/check-updates.test.ts | 101 ++- packages/cli/src/lifecycle/check-updates.ts | 171 +++- packages/cli/src/lifecycle/diff.ts | 5 +- .../fixtures/agent-kit-manifest-v3.0.0.json | 12 + .../cli/src/lifecycle/legacy-pack-ids.test.ts | 55 ++ .../cli/src/lifecycle/overlay-known-hashes.ts | 11 + packages/cli/src/lifecycle/retired.test.ts | 155 ++++ packages/cli/src/lifecycle/retired.ts | 116 +++ packages/cli/src/lifecycle/sync.ts | 29 +- packages/cli/src/lifecycle/targets.test.ts | 9 +- packages/cli/src/lifecycle/targets.ts | 24 +- .../cli/src/lifecycle/update-notice.test.ts | 297 +++++++ packages/cli/src/lifecycle/update-notice.ts | 334 +++++++ packages/cli/src/plan-loop/run-loop.ts | 3 +- .../run-plan-all-orchestrator.test.ts | 14 + packages/cli/src/plan-loop/sentinel.test.ts | 24 + packages/cli/src/plan-loop/sentinel.ts | 25 + .../cli/src/plan-loop/stream-render.test.ts | 83 +- packages/cli/src/plan-loop/stream-render.ts | 88 +- packages/cli/src/readiness/env-checks.ts | 22 +- .../cli/src/readiness/install-health.test.ts | 419 +++++++++ packages/cli/src/readiness/install-health.ts | 552 ++++++++++++ packages/cli/src/registry/client.ts | 59 +- .../cli/src/registry/pack-aliases.test.ts | 95 ++ packages/cli/src/registry/pack-aliases.ts | 46 + packages/cli/src/registry/resolve.ts | 194 +---- packages/cli/src/scanner/detect-repository.ts | 2 + packages/cli/src/scanner/safe-fixes.test.ts | 1 + packages/cli/src/test-support/vitest-setup.ts | 30 + packages/cli/src/utils/agent-session.ts | 69 ++ packages/cli/src/utils/dir-lock.ts | 214 +++++ packages/cli/src/welcome/help-groups.ts | 2 +- packages/cli/vitest.config.ts | 2 + plugin.json | 2 +- skills/hitl-gates/run-plan-all-queue.md | 2 +- 117 files changed, 8789 insertions(+), 928 deletions(-) delete mode 100644 .cursor/rules/cursor-skills-groovy.mdc create mode 100644 packages/cli/src/commands/installs.ts create mode 100644 packages/cli/src/commands/update-all.test.ts create mode 100644 packages/cli/src/commands/update-all.ts create mode 100644 packages/cli/src/commands/update-legacy-pack.test.ts create mode 100644 packages/cli/src/commands/update-retired-skills.test.ts create mode 100644 packages/cli/src/installs/index.ts create mode 100644 packages/cli/src/installs/inspect.ts create mode 100644 packages/cli/src/installs/installs.test.ts create mode 100644 packages/cli/src/installs/scan.ts create mode 100644 packages/cli/src/installs/store.ts create mode 100644 packages/cli/src/lifecycle/fixtures/agent-kit-manifest-v3.0.0.json create mode 100644 packages/cli/src/lifecycle/legacy-pack-ids.test.ts create mode 100644 packages/cli/src/lifecycle/retired.test.ts create mode 100644 packages/cli/src/lifecycle/retired.ts create mode 100644 packages/cli/src/lifecycle/update-notice.test.ts create mode 100644 packages/cli/src/lifecycle/update-notice.ts create mode 100644 packages/cli/src/readiness/install-health.test.ts create mode 100644 packages/cli/src/readiness/install-health.ts create mode 100644 packages/cli/src/registry/pack-aliases.test.ts create mode 100644 packages/cli/src/registry/pack-aliases.ts create mode 100644 packages/cli/src/test-support/vitest-setup.ts create mode 100644 packages/cli/src/utils/agent-session.ts create mode 100644 packages/cli/src/utils/dir-lock.ts diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index fc1d089..c78e94a 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "agent-kit", "displayName": "Mission Kit", - "version": "6.23.0", + "version": "6.25.0", "description": "Plan, build, ship, and keep shipping. Agent Kit for Claude Code: plans, handoff, durable memory and staging-to-prod gates for long-term projects, followed from Mission Control in your browser.", "author": { "name": "agent-kit-startup" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index eb57496..96da27d 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-kit", - "version": "6.23.0", + "version": "6.25.0", "description": "Plan, build, ship, and keep shipping. Agent Kit skills for long-term projects with your own coding agents: plans, handoff, durable memory and staging-to-prod gates.", "author": { "name": "agent-kit-startup" diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 34ac234..0201ba7 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -7,7 +7,7 @@ "description": "Plan, build, ship, and keep shipping. Agent Kit slash commands, rules and skills for long-term projects with your own coding agents: plans, handoff, durable memory and staging-to-prod gates. Follow the work in Mission Control.", "keywords": ["agents", "hitl", "handoff", "git-staging", "context", "multi-ide", "anti-slop"], "license": "Apache-2.0", - "version": "6.23.0", + "version": "6.25.0", "homepage": "https://github.com/agent-kit-startup/agent-kit", "websiteURL": "https://agent.missionkit.io/", "privacyPolicyURL": "https://github.com/agent-kit-startup/agent-kit/blob/main/PRIVACY.md", diff --git a/.cursor/agent-kit.json b/.cursor/agent-kit.json index fc1e833..15be7a3 100644 --- a/.cursor/agent-kit.json +++ b/.cursor/agent-kit.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "version": "6.23.0", + "version": "6.25.0", "protected": [ ".claude/commands/agent-kit.md", ".cursor/HANDOFF.md", diff --git a/.cursor/commands/update.md b/.cursor/commands/update.md index ca19af8..8e6aa3a 100644 --- a/.cursor/commands/update.md +++ b/.cursor/commands/update.md @@ -11,14 +11,15 @@ audience: user Update the Agent Kit layer (L0 + packs + skills) from the public registry, treating this repo as a **consumer** — not the dev factory. Checks the latest released version, compares with what's installed, and applies the update respecting protected L3 paths. -**Check ≠ apply.** Opt-in `updateCheck` and `agent-kit update --check` only notify. Apply always goes through this command's Ask confirm (or an explicit CLI `agent-kit update` invoke by an operator). `updateApply.auto` defaults to `false` and must never silent-write L0. +**Check ≠ apply.** The update notice (default on; opt-out `updateCheck.enabled: false`) and `agent-kit update --check` only notify. Apply always goes through this command's Ask confirm (or an explicit CLI `agent-kit update` invoke by an operator). `updateApply.auto` defaults to `false` and must never silent-write L0. ## When to Use - When you want to check if a newer Agent Kit release is available - To pull the latest rules, commands, skills, and pack updates from the public repo -- After a new `agent-kit-startup/agent-kit` release (check [releases](https://github.com/agent-kit-startup/agent-kit/releases)) -- After a sessionStart nudge (when `updateCheck.enabled` is true) that reports an update available +- After a new release, or when the sessionStart update notice reports something behind + +**Several repos behind?** The operator types `agent-kit installs scan`, then `agent-kit update --all` (one plan, one confirm, one PR/MR per repo, no merge). It refuses in agent sessions; never run it here. ## Hard stops @@ -142,6 +143,6 @@ Agent: Running agent-kit update... Done! 8 updated, 2 added, 1 protected. ``` Or use the URL directly via `--url`. -- **"npx resolution failed"**: Ensure Node.js ≥18 is available. Try `pnpm exec agent-kit update` as fallback. +- **"npx resolution failed"**: Needs Node.js 22.12+. Try `npx -y @dadado/agent-kit-cli update` as fallback. - **"Registry URL differs from installed"**: The current manifest may point to the dev repo. The update will switch it to the public repo — that's correct for consumer mode. diff --git a/.cursor/context/config.example.json b/.cursor/context/config.example.json index d8cdda5..8cb09a9 100644 --- a/.cursor/context/config.example.json +++ b/.cursor/context/config.example.json @@ -39,7 +39,7 @@ "tickThreshold": 3 }, "updateCheck": { - "enabled": false, + "enabled": true, "intervalDays": 7, "lastCheckedAt": null }, diff --git a/.cursor/rules/cursor-skills-api.mdc b/.cursor/rules/cursor-skills-api.mdc index 83cf4e0..dfe595e 100644 --- a/.cursor/rules/cursor-skills-api.mdc +++ b/.cursor/rules/cursor-skills-api.mdc @@ -1,46 +1,22 @@ --- -description: CURSOR-SKILLS rules for APIs (REST, GraphQL, gRPC). OpenAPI, tests, versioning. +description: Kit guidance for APIs (REST, GraphQL, gRPC): contract first, versioning, one error envelope, contract tests. globs: "**/api/**/*,**/*-api*,**/swagger.*,**/openapi.*,**/*.graphql,**/*.proto" alwaysApply: false --- -# CURSOR-SKILLS - API +# APIs (REST, GraphQL, gRPC) -Source: [cursor-skills/api](https://github.com/araguaci/cursor-skills/tree/main/api) +## Contract -## CURSOR setup +- The schema (OpenAPI, GraphQL SDL, `.proto`) is the source of truth. Code and docs derive from it, or CI checks them against it. +- Version the API (path or header). Inside one version, changes are additive only; deprecate with a date and a `Sunset` header. -- REST Client, Thunder Client, or Postman; JSON Tools; docs generator; Swagger Viewer. +## Behavior -## Typical structure +- One error envelope for every failure: code, message, details, request id. Use real status codes; never a `200` with an error body. +- Validate input at the edge. Every list endpoint paginates. Unsafe retries (charges, creates) take an idempotency key. +- Authentication and authorization are on by default; public routes are an explicit allowlist. Rate-limit by caller. -``` -project/ -├── src/ ├── tests/ ├── docs/ ├── schemas/ -├── swagger.yaml └── .env -``` +## Tests -## Patterns - -- REST: correct verbs and resources; HTTP status codes; versioning; JSON. -- **GraphQL**: queries, mutations, subscriptions; schema; introspect; validation. -- **gRPC**: services, methods, Protocol Buffers; error handling. - -## Documentation - -- OpenAPI/Swagger; request/response examples; error codes; authentication. -- Tools: Swagger/OpenAPI, Postman, Insomnia, ReDoc. - -## Security and quality - -- Validate inputs; auth; rate limit; CORS; HTTPS. -- Prettier, ESLint; endpoint tests (unit + integration); coverage ≥ 80%. - -## REST Client config (example) - -```json -{ - "editor.formatOnSave": true, - "rest-client.environmentVariables": { "baseUrl": "http://localhost:3000" } -} -``` +- Contract tests against the schema, plus one happy path and one failure path per endpoint. diff --git a/.cursor/rules/cursor-skills-devops.mdc b/.cursor/rules/cursor-skills-devops.mdc index 0167df9..46330c3 100644 --- a/.cursor/rules/cursor-skills-devops.mdc +++ b/.cursor/rules/cursor-skills-devops.mdc @@ -1,54 +1,23 @@ --- -description: CURSOR-SKILLS rules for DevOps (Docker, Kubernetes, CI/CD, Terraform, IaC). +description: Kit guidance for DevOps (Docker, Kubernetes, CI/CD, Terraform): staging first, build once and promote, infrastructure as code. globs: "**/Dockerfile,**/docker-compose*.{yml,yaml},**/.github/**/*.yml,**/.gitlab-ci.yml,**/*.yml,**/k8s/**/*,**/*.tf,**/*.tfvars" alwaysApply: false --- -# CURSOR-SKILLS - DevOps +# DevOps (containers, CI/CD, infrastructure) -Source: [cursor-skills/devops](https://github.com/araguaci/cursor-skills/tree/main/devops) +## Flow -## CURSOR setup +- Staging first: nothing reaches production without passing staging (see `cursor-skills-git-workflow`). Build the artifact once and promote that same artifact. +- Write down the rollback path before the deploy, not during the incident. -- Docker, Kubernetes, GitLens, Remote Development, YAML, Terraform. +## Infrastructure -## Typical structure +- Infrastructure is code. No console edits; plan, review the plan, then apply. +- Terraform: remote state with locking, small modules, `fmt` and `validate` in CI, no real values committed in `*.tfvars`. +- Kubernetes: resource requests and limits, readiness and liveness probes, config in ConfigMap or Secret, never the `latest` tag. -``` -project/ -├── docker/ ├── k8s/ ├── terraform/ ├── .github/ -└── .env -``` +## Containers and CI -## Docker - -- Dockerfile and docker-compose; multi-stage builds; layer cache; security (non-root user, minimal images). - -## Kubernetes - -- Pods, Services, Deployments; ConfigMaps and Secrets; resources and limits; health checks; naming conventions. - -## CI/CD - -- Pipelines (GitHub Actions, GitLab CI, etc.); stages (lint, test, build, deploy); triggers; notifications; rollback. -- When the project adopts Git staging → production flow: use `git staging` and `git prod`; never commit directly to `main`. See rule [cursor-skills-git-workflow.mdc](cursor-skills-git-workflow.mdc). - -## DevOps spine: Git staging → prod - -The two-step flow (staging → main) is the kit's operational memory. Reinforcements that keep work from leaking straight to production: - -1. **Staging-first always.** Work and commits happen on a working branch or on `staging`, never with checkout on `main`. -2. **Leave `main` after `git prod`.** Promotion leaves checkout on `main`; when done, run `git checkout staging`. Staying on `main` is the most common way a commit escapes onto the production line. -3. **Prune legacy branches.** An old pre-prod branch (`homologacao`, `develop`) already migrated to `staging` should be removed (local and remotes) so it does not confuse the flow or history. -4. **Enforcement, not only convention.** Install the guards in `git-hooks/` (`pre-commit` and `pre-push`) that abort commit/push directly to `main`/`master`. Install notes in [git-hooks/README.md](git-hooks/README.md). -5. **Audit the `main` line.** `git log --first-parent --no-merges main` should return only the root commit. Any other non-merge there is a commit that was born directly on `main` (flow violation). - -Details and prompts in [autogit/gitupdate.md](autogit/gitupdate.md); full rule in [cursor-skills-git-workflow.mdc](cursor-skills-git-workflow.mdc). - -## IaC (Terraform) - -- Modules; versioning; remote state; `terraform fmt`; document resources and variables. - -## Best practices - -- Logs, env vars, secrets out of code; infra tests when possible; deploy and troubleshooting docs. +- Docker: pinned base image, multi-stage build, non-root user, `.dockerignore`, no secrets in layers. +- CI: lint and unit tests first, slow suites after; cache dependencies; pin third-party actions to a commit SHA; give tokens the least scope that works. diff --git a/.cursor/rules/cursor-skills-general.mdc b/.cursor/rules/cursor-skills-general.mdc index c83ea68..4685ac6 100644 --- a/.cursor/rules/cursor-skills-general.mdc +++ b/.cursor/rules/cursor-skills-general.mdc @@ -1,27 +1,16 @@ --- -description: CURSOR-SKILLS general rules (best practices, setup, quality). Source: cursor-skills.vercel.app +description: Kit baseline for code and repository hygiene: small diffs, tests with the change, no secrets, repo conventions first. alwaysApply: true --- -# CURSOR-SKILLS - General Rules - -Base: [CURSOR-SKILLS](https://github.com/araguaci/cursor-skills). Apply the repository's conventions in any environment. - -## Principles - -- **Setup**: use extensions, linting, and formatting suited to the environment; Git integration and debugging. -- **Structure**: follow the environment's conventions, consistent naming, separation of concerns. -- **Quality**: readable code, error handling, useful comments, tests. -- **Workflow**: Git, tests, CI/CD, documentation, and code review. -- **Documentation**: professional, inheritable standard (`docs-professional-standard`); project voice, no people, unrelated projects, or session context. Chat vs repo hygiene (`agent-output-hygiene`). - -## Coding Guidelines - -- **Think Before Coding:** do not assume; flag uncertainty; show tradeoffs; ask when a requirement is ambiguous. -- **Simplicity First:** the minimum code that solves the problem; no unrequested features; no abstraction for a single use; ask "would a senior find this overengineered?". -- **Surgical Changes:** touch only what is needed; do not "improve" adjacent code without being asked; keep the existing style; remove only what your change made orphaned. -- **Goal-Driven Execution:** define success criteria before implementing; iterate until the goal is verified. - -## Git - -Flow, branch guards, and Conventional Commits: `cursor-skills-git-workflow` (SoT `autogit/gitupdate.md`). +# General engineering baseline + +- **Read before writing.** Match the naming, layout, formatter and linter the repo already uses before applying a preference of your own. +- **Smallest change that solves the task.** No drive-by refactors; a new dependency needs a reason in the PR. +- **Tests travel with the change.** A behavior change changes a test; a bug fix starts with a failing one. +- **No secrets in git.** Keys, tokens and `.env` files stay out of commits and logs (see `git-secrets-safety`). +- **Errors are handled or surfaced,** never swallowed. Log context, not payloads that hold personal data. +- **Names carry intent;** comments say why, not what. +- **Docs follow behavior.** README, CHANGELOG and ADRs change in the same PR as the behavior they describe. +- **Branching:** staging first, never `main` (see `cursor-skills-git-workflow`). +- Stack rules (`cursor-skills-`) load by file glob; follow them on top of this one. diff --git a/.cursor/rules/cursor-skills-groovy.mdc b/.cursor/rules/cursor-skills-groovy.mdc deleted file mode 100644 index fcd29f9..0000000 --- a/.cursor/rules/cursor-skills-groovy.mdc +++ /dev/null @@ -1,16 +0,0 @@ ---- -description: Rules for Groovy (syntax, filter scripts, and integration). -globs: "**/*.groovy" -alwaysApply: false ---- - -# CURSOR-SKILLS - Groovy - -## Context - -- Groovy scripts for email filters, integrations, or tools that run Groovy. - -## Syntax and best practices - -- Groovy: Java-compatible syntax; closures; GStrings; verify compatibility with the runtime where the script runs. -- Keep the script documented and aligned with project docs when they exist. diff --git a/.cursor/rules/cursor-skills-integrations.mdc b/.cursor/rules/cursor-skills-integrations.mdc index 979a453..91dcf1f 100644 --- a/.cursor/rules/cursor-skills-integrations.mdc +++ b/.cursor/rules/cursor-skills-integrations.mdc @@ -1,41 +1,16 @@ --- -description: CURSOR-SKILLS rules for integrations (webhooks, microservices, DBs, queues). +description: Kit guidance for integrations (webhooks, queues, third-party APIs): timeouts, idempotency, signed webhooks, one adapter per vendor. globs: "**/integrations/**/*,**/webhooks/**/*,**/microservices/**/*" alwaysApply: false --- -# CURSOR-SKILLS - Integrations +# Integrations (webhooks, queues, external services) -Source: [cursor-skills/integrations](https://github.com/araguaci/cursor-skills/tree/main/integrations) - -## CURSOR setup - -- Docker, Kubernetes, GitLens, Remote Development, Database Client, REST Client. - -## Typical structure - -``` -project/ -├── src/ ├── tests/ ├── configs/ ├── docker/ ├── k8s/ -└── .env -``` - -## Principles - -- Microservices; error handling and logging; secure communication; retries and idempotency when applicable. - -## Webhooks - -- Standardized events and payloads; validation (e.g. signature); retry; security. - -## Microservices - -- Consistent APIs; discovery; load balancing; health checks; communication tests. - -## Database - -- Connection pooling; transactions; indexes; prepared statements; avoid N+1; naming conventions. - -## Communication - -- HTTP, gRPC, or WebSocket as appropriate; error handling; queues (RabbitMQ, Kafka, etc.) when it makes sense. +- **Assume the other side fails.** Set a timeout on every call, retry a bounded number of times with backoff and jitter, and have a fallback. +- **Webhooks:** verify the signature, answer `2xx` fast and process asynchronously, dedupe by event id, tolerate replays and out-of-order delivery. +- **Consumers are idempotent.** Treat queues as at-least-once. +- **One adapter per vendor.** Validate inbound payloads at that boundary and map them to internal types; vendor types do not leak inward. +- **Version payloads** you emit; additive changes only within a version. +- **Credentials** live in the environment or a secret manager, one set per environment, rotated. +- **Trace across hops** with a correlation id. Log outcome and latency, not payloads with personal data. +- **Data stays with its owner.** No cross-service reads of another service's tables. diff --git a/.cursor/rules/cursor-skills-json.mdc b/.cursor/rules/cursor-skills-json.mdc index e6bfc74..6067534 100644 --- a/.cursor/rules/cursor-skills-json.mdc +++ b/.cursor/rules/cursor-skills-json.mdc @@ -4,7 +4,7 @@ globs: "**/*.json" alwaysApply: false --- -# CURSOR-SKILLS - JSON +# JSON Aligned with skill [.cursor/skills/community/json-data-config/SKILL.md](.cursor/skills/community/json-data-config/SKILL.md). diff --git a/.cursor/rules/cursor-skills-mobile.mdc b/.cursor/rules/cursor-skills-mobile.mdc index dcabeaf..6882e72 100644 --- a/.cursor/rules/cursor-skills-mobile.mdc +++ b/.cursor/rules/cursor-skills-mobile.mdc @@ -1,39 +1,15 @@ --- -description: CURSOR-SKILLS rules for mobile (React Native, Flutter, Expo). Platform, performance, tests. +description: Kit guidance for mobile (React Native, Expo, Flutter): platform wrappers, performance, offline states, release hygiene. globs: "**/*.dart,**/android/**/*,**/ios/**/*,**/App.tsx,**/app.json" alwaysApply: false --- -# CURSOR-SKILLS - Mobile +# Mobile (React Native, Expo, Flutter) -Source: [cursor-skills/mobile](https://github.com/araguaci/cursor-skills/tree/main/mobile) - -## CURSOR setup - -- React Native Tools, Flutter, Dart, Expo Tools; on native projects: Android Studio / Xcode per stack. - -## Typical structure - -``` -project/ -├── src/ ├── tests/ ├── assets/ ├── android/ ├── ios/ -└── .env -``` - -## By framework - -- **React Native**: components, navigation, native APIs; ESLint; performance (lists, memo, lazy). -- **Flutter**: widgets, state management; `dart.flutterSdkPath` if needed; Flutter tests. -- **Expo**: expo-cli / expo-dev-client; Expo APIs and components; `expo.toolsPath` if needed. - -## Platform - -- iOS/Android differences; platform-specific code when needed; responsive design; each OS guidelines. - -## Performance and quality - -- Optimize images and assets; rendering and memory; Prettier, ESLint; tests (unit, integration, E2E); coverage ≥ 80%. - -## Security - -- Validate inputs; auth; sensitive data; HTTPS; OWASP mobile. +- **One toolkit per app.** Do not mix state or navigation patterns inside the same project. +- **Isolate platform differences** behind small wrappers and run both iOS and Android before a change reaches staging. +- **Every screen has loading, empty and error states.** Assume a slow or absent network; cache and retry. +- **Performance:** virtualized lists, avoid needless rebuilds and re-renders, measure on a low-end device before optimizing. +- **Secrets stay out of the bundle.** Tokens go in secure storage. Ask for a permission in context and work when it is denied. +- **Release:** CI bumps version and build number; over-the-air updates only for JavaScript-level changes. +- **Tests:** unit tests for logic, component or widget tests for screens, one E2E smoke test on the critical path. diff --git a/.cursor/rules/cursor-skills-n8n.mdc b/.cursor/rules/cursor-skills-n8n.mdc index 8a09c66..275ffa8 100644 --- a/.cursor/rules/cursor-skills-n8n.mdc +++ b/.cursor/rules/cursor-skills-n8n.mdc @@ -4,7 +4,7 @@ globs: "**/n8n/**/*,**/*workflow*.json,**/workflows/**/*.json" alwaysApply: false --- -# CURSOR-SKILLS - n8n +# n8n Aligned with skill [.cursor/skills/community/n8n-workflows/SKILL.md](.cursor/skills/community/n8n-workflows/SKILL.md). diff --git a/.cursor/rules/cursor-skills-node.mdc b/.cursor/rules/cursor-skills-node.mdc index 3e1d8cc..e492624 100644 --- a/.cursor/rules/cursor-skills-node.mdc +++ b/.cursor/rules/cursor-skills-node.mdc @@ -1,41 +1,16 @@ --- -description: CURSOR-SKILLS rules for Node.js (Express, NestJS, Next.js). ESLint, Prettier, tests. +description: Kit guidance for Node.js (Express, NestJS, Next.js): repo tooling first, strict types, validated config, thin handlers. globs: "**/*.js,**/*.ts,**/*.tsx,**/*.mjs,**/*.cjs" alwaysApply: false --- -# CURSOR-SKILLS - Node.js +# Node.js and TypeScript -Source: [cursor-skills/node](https://github.com/araguaci/cursor-skills/tree/main/node) - -## CURSOR setup - -- ES6 snippets, Node Extension Pack, npm Intellisense, Prettier, ESLint, Thunder Client / REST Client. - -## Typical structure - -``` -project/ -├── src/ ├── tests/ ├── docs/ ├── node_modules/ -├── package.json ├── package-lock.json └── .env -``` - -## Packages - -- npm or yarn; `package-lock.json`/`yarn.lock`; separate dev deps; semver; scripts in `package.json`. - -## By framework - -- **Express**: middleware, routes, error handling; `source.fixAll.eslint`, format on save. -- **NestJS**: modules, services, controllers, DI; TypeScript, ESLint. -- **Next.js**: pages, App Router, API routes, SSR/SSG/ISR; Emmet for `javascriptreact`. - -## Code - -- ES6+; TypeScript when it makes sense; error handling; JSDoc; standardization (Prettier, ESLint). -- **Tests**: Jest or Mocha; coverage ≥ 80%. - -## Security, DB, and APIs - -- Validate inputs; OWASP; hashing; HTTPS. Sequelize/TypeORM; avoid N+1; transactions. -- REST: HTTP codes, versioning, JSON; auth, rate limit, CORS. +- **Use the repo's tooling.** One package manager and its lockfile; the Node version pinned (`engines`, `.nvmrc` or mise). Lint and format with the repo's config. +- **TypeScript is strict.** No `any` without a comment saying why. Follow the package's module type (ESM or CJS) and do not mix them. +- **Async:** `async`/`await`, no floating promises, a timeout on every outbound call. +- **Config comes from the environment,** validated once at startup; the process fails fast. No `process.env` scattered through the code. +- **Thin handlers.** Route handlers and controllers parse and respond; logic lives in services, I/O in adapters. This holds for Express, NestJS and Next.js route handlers. +- **Next.js:** server components by default, client components marked on purpose, secrets only on the server. +- **Security:** validate input, never `eval`, run a dependency audit in CI. +- **Tests:** colocated or under `tests/`; unit tests make no network calls. diff --git a/.cursor/rules/cursor-skills-php.mdc b/.cursor/rules/cursor-skills-php.mdc index 5ebed4d..1bb7134 100644 --- a/.cursor/rules/cursor-skills-php.mdc +++ b/.cursor/rules/cursor-skills-php.mdc @@ -1,50 +1,14 @@ --- -description: CURSOR-SKILLS rules for PHP (Laravel, Symfony, WordPress). PSR, Composer, security. +description: Kit guidance for PHP (Laravel, Symfony, WordPress): PSR, strict types, escaping on output, prepared statements. globs: "**/*.php" alwaysApply: false --- -# CURSOR-SKILLS - PHP +# PHP (Laravel, Symfony, WordPress) -Source: [cursor-skills/php](https://github.com/araguaci/cursor-skills/tree/main/php) - -## CURSOR setup - -- PHP Intelephense, PHP Debug (Xdebug), PHP DocBlocker, Composer. -- Laravel Blade / Symfony / WordPress snippets per project. - -## Typical structure - -``` -project/ -├── app/ ├── config/ ├── public/ ├── resources/ -├── tests/ ├── vendor/ ├── composer.json ├── composer.lock └── .env -``` - -## Required standards - -- **PSR**: PSR-1, PSR-2/PSR-12, PSR-4 (autoload). -- **Composer**: always for deps; `composer.lock`; autoload; separate dev deps. -- **Tools**: PHP CS Fixer, PHPStan, PHPUnit, Xdebug. - -## By framework - -- **Laravel**: Artisan, Eloquent, MVC, middleware, validation, PHPUnit, Laravel security. -- **Symfony**: Bundles, services, DI, PHPUnit, Symfony security. -- **WordPress**: Coding standards, hooks/filters, plugin/theme architecture, WP tests. - -## Code and documentation - -- PHPDoc on classes and methods; comments on complex logic; README and API docs. - -## Security - -- Validate and sanitize inputs; prepared statements; CSRF; secure auth; OWASP; password hashing; HTTPS. - -## DB - -- Normalization, indexes, FKs, naming conventions; prepared statements; avoid N+1; transactions. - -## REST APIs (in PHP) - -- REST, correct HTTP codes, versioning, JSON; auth, rate limit, CORS, HTTPS. +- **Standards:** PSR-12 style, PSR-4 autoloading, Composer for every dependency; commit `composer.lock` for applications. +- **Typed code:** `declare(strict_types=1)`, parameter and return types, static analysis (PHPStan or Psalm) at the level the repo sets. +- **Framework first.** Laravel and Symfony: container, validators or form requests, migrations. WordPress: hooks and filters, never edit core, nonces and capability checks on every action. +- **Security:** prepared statements only (`$wpdb->prepare` in WordPress), escape on output (`esc_html` and friends), validate input, `password_hash` for passwords, no secrets in the repo. +- **Errors:** exceptions, no `@` suppression, PSR-3 logging. +- **Tests:** PHPUnit or Pest; one failing test before a bug fix. diff --git a/.cursor/rules/cursor-skills-prompts.mdc b/.cursor/rules/cursor-skills-prompts.mdc index 7a9cc9f..6759c98 100644 --- a/.cursor/rules/cursor-skills-prompts.mdc +++ b/.cursor/rules/cursor-skills-prompts.mdc @@ -4,7 +4,7 @@ globs: "**/prompt*.md,**/prompts/**/*.md,**/modelo-guest.md" alwaysApply: false --- -# CURSOR-SKILLS - Prompts (Markdown) +# Prompts (Markdown) Aligned with skill [.cursor/skills/community/prompts-markdown/SKILL.md](.cursor/skills/community/prompts-markdown/SKILL.md). diff --git a/.cursor/rules/cursor-skills-python.mdc b/.cursor/rules/cursor-skills-python.mdc index 07e4ecb..d09c6db 100644 --- a/.cursor/rules/cursor-skills-python.mdc +++ b/.cursor/rules/cursor-skills-python.mdc @@ -1,46 +1,16 @@ --- -description: CURSOR-SKILLS rules for Python (Django, Flask, FastAPI, Data Science). PEP, venv, tests. +description: Kit guidance for Python (Django, Flask, FastAPI, data work): pinned environment, type hints, pytest. globs: "**/*.py" alwaysApply: false --- -# CURSOR-SKILLS - Python +# Python (Django, Flask, FastAPI, data work) -Source: [cursor-skills/python](https://github.com/araguaci/cursor-skills/tree/main/python) - -## CURSOR setup - -- Python, Pylance, Python Debugger, Docstring Generator, Python Indent, Test Explorer, Jupyter (if applicable). - -## Typical structure - -``` -project/ -├── src/ ├── tests/ ├── docs/ -├── requirements.txt ├── requirements-dev.txt ├── pyproject.toml └── .env -``` - -## Required standards - -- **PEP**: 8 (style), 257 (docstrings), 484 (type hints), 526 (annotations). -- **Environment**: always venv or conda; `requirements.txt`; pip-tools; separate dev deps. -- **Tools**: Black, isort, flake8, mypy, pytest. - -## By framework - -- **Django**: MVT, ORM, admin, forms; `python.formatting.provider: "black"`. -- **Flask**: blueprints, app factory; flake8, Black. -- **FastAPI**: DI, Pydantic, OpenAPI; async; Pylint, Black. - -## Data Science - -- Jupyter: clear cells, validation, versioning, clean before sharing. -- Pandas, NumPy, matplotlib/seaborn; scikit-learn; model validation and documentation. - -## Code and documentation - -- Docstrings and type hints on functions/classes; comments on complex logic; README and API docs. - -## Security and DB - -- Validate inputs; OWASP; hashing; HTTPS. ORM (Django/SQLAlchemy); avoid N+1; transactions. +- **Environment:** pin the Python version, use one virtual environment per project (uv, venv or poetry) and lock dependencies. Never install into the system interpreter. +- **Style:** PEP 8 through the repo's formatter and linter (ruff when none is set); type hints on public functions, checked by mypy or pyright where the repo has one. +- **Layout:** `pyproject.toml`, a `src/` package, console entry points instead of loose scripts. +- **Errors:** raise specific exceptions, no bare `except`, context managers for files and connections, `logging` instead of `print`. +- **Django:** logic in models and services rather than views, migrations committed, settings from the environment. +- **Flask and FastAPI:** app factory, Pydantic or equivalent models at the boundary, dependencies injected. +- **Data work:** notebooks are not the source of truth, seed randomness, keep datasets out of git. +- **Tests:** pytest with fixtures; no network in unit tests. diff --git a/.cursor/rules/cursor-skills-sql.mdc b/.cursor/rules/cursor-skills-sql.mdc index 9c26cb1..087fb59 100644 --- a/.cursor/rules/cursor-skills-sql.mdc +++ b/.cursor/rules/cursor-skills-sql.mdc @@ -4,7 +4,7 @@ globs: "**/*.sql" alwaysApply: false --- -# CURSOR-SKILLS - SQL (Postgres) +# SQL (Postgres) Aligned with skill [.cursor/skills/community/sql-postgres/SKILL.md](.cursor/skills/community/sql-postgres/SKILL.md). diff --git a/.cursor/rules/cursor-skills-testing.mdc b/.cursor/rules/cursor-skills-testing.mdc index 49ed49b..dd8c6fa 100644 --- a/.cursor/rules/cursor-skills-testing.mdc +++ b/.cursor/rules/cursor-skills-testing.mdc @@ -1,41 +1,16 @@ --- -description: CURSOR-SKILLS rules for tests (unit, integration, E2E). Jest, Cypress, fixtures, mocks. +description: Kit guidance for tests (unit, integration, E2E): deterministic, named by behavior, mocks only at boundaries. globs: "**/*.test.*,**/*.spec.*,**/tests/**/*,**/__tests__/**/*,**/e2e/**/*,**/cypress/**/*" alwaysApply: false --- -# CURSOR-SKILLS - Testing +# Tests (unit, integration, E2E) -Source: [cursor-skills/testing](https://github.com/araguaci/cursor-skills/tree/main/testing) - -## CURSOR setup - -- Jest, Cypress, Testing Library, Coverage Gutters, Test Explorer, Mocha (per project). - -## Typical structure - -``` -project/ -├── src/ ├── tests/ ├── coverage/ ├── fixtures/ ├── mocks/ -└── .env -``` - -## Unit - -- Isolated, fast tests; clear assertions; mocks for external deps; descriptive names; `jest.autoRun: "off"` if preferred. - -## Integration - -- Component interaction and data flow; test DB and external services mocked or controlled; setup/teardown; `testing.autoRun: "off"` if preferred. - -## E2E - -- User journeys; Cypress or similar; page objects; test data and cleanup; `cypress.autoRun: "off"` if preferred. - -## Organization and data - -- Group by feature; names that describe the scenario; fixtures for data; consistent mocks; coverage ≥ 80% where it makes sense. - -## Tools - -- Prettier, ESLint; coverage reports; test-case and troubleshooting docs. +- **Shape:** many fast unit tests, fewer integration tests, a handful of E2E tests for the critical journeys. +- **One reason to fail.** Name a test by the behavior (`does X when Y`) and keep it arrange, act, assert. +- **Deterministic.** Control the clock, randomness and network. Fix a flaky test or quarantine it with an issue; never retry it into green. +- **Mock at the boundary** (network, time, filesystem) and prefer fakes. Never mock the unit under test. +- **Fixtures stay small and local.** No mutable state shared between tests. +- **A bug fix starts with a regression test** that fails first. +- **Coverage is a signal, not a target.** Check that the branches you changed are exercised. +- **E2E:** select by role or test id, isolate the data, run it in the staging pipeline. diff --git a/.cursor/rules/cursor-skills-webdesign.mdc b/.cursor/rules/cursor-skills-webdesign.mdc index 3f57014..3da7b4e 100644 --- a/.cursor/rules/cursor-skills-webdesign.mdc +++ b/.cursor/rules/cursor-skills-webdesign.mdc @@ -1,39 +1,13 @@ --- -description: CURSOR-SKILLS rules for Web (HTML, CSS, JS, React, Vue, Angular). A11y, BEM, responsive. +description: Kit guidance for the web front end (HTML, CSS, JS frameworks): semantics, accessibility, tokens, performance. globs: "**/*.html,**/*.css,**/*.scss,**/*.vue,**/*.jsx,**/*.svelte" alwaysApply: false --- -# CURSOR-SKILLS - Web Design +# Web front end (HTML, CSS, JavaScript frameworks) -Source: [cursor-skills/webdesign](https://github.com/araguaci/cursor-skills/tree/main/webdesign) - -## CURSOR setup - -- HTML CSS Support, ES6 snippets, Auto Rename Tag, Prettier, Live Server, Emmet. -- React: React DevTools, ES7+ snippets. Vue: Vetur/Volar, Vue 3 Snippets. Angular: Angular Language Service, CLI. - -## HTML - -- Semantic HTML5; accessibility (ARIA, alt, heading hierarchy, keyboard); W3C; responsive. - -## CSS - -- CSS3, responsive, BEM, custom properties, controlled specificity. -- CSS modules or styled-components; mobile-first; flexible grids; responsive images. - -## JavaScript / Frameworks - -- ES6+; TypeScript when appropriate; error handling. -- **React**: functional components, hooks, state management. -- **Vue**: Composition API, reactivity, conventions. -- **Angular**: TypeScript, services, DI. - -## Tests and tools - -- Jest (unit), Cypress (E2E), Storybook, Lighthouse, Axe (a11y). -- Build: bundling, env vars, cache, CDN for assets. - -## A11y and security - -- Semantics, ARIA, keyboard, screen readers; validate/sanitize inputs; CSP; CORS; HTTPS. +- **Semantic HTML first.** Landmarks, headings in order, one `h1`, real buttons and links. +- **Accessibility is a requirement:** labels on inputs, alt text, visible focus, a keyboard path through every flow, AA contrast (4.5:1 for text), respect `prefers-reduced-motion`. +- **CSS:** design tokens as custom properties, one naming scheme per project (BEM or utilities, not both), mobile first, fluid layouts instead of fixed pixel widths. Colors come from tokens, never hard-coded. +- **Components** are small and single-purpose, state lives close to where it is used, no business logic in templates. Follow the framework's idioms (hook rules in React, composition in Vue, signals or services in Angular). +- **Performance:** sized images with lazy loading, `font-display` on web fonts, no layout shift, a budget checked in CI. diff --git a/.cursor/scripts/run-plan-all-consolidate.sh b/.cursor/scripts/run-plan-all-consolidate.sh index cccdd5a..bc35523 100755 --- a/.cursor/scripts/run-plan-all-consolidate.sh +++ b/.cursor/scripts/run-plan-all-consolidate.sh @@ -28,6 +28,12 @@ # - Validate / normalize --outcomes (including multiline) BEFORE any HANDOFF mutation. # - Apply Plan/Mode/queue/cursor/status/outcomes as one atomic rewrite (temp + replace). # - Never use awk -v for outcomes (newlines break -v and caused partial rewrites). +# - History is kept: Plan, Mode, Last updated, Queue cursor and Queue status become +# " · antes: " when the value changes (unchanged +# head = line left as is). Run queue is replaced bare. +# - Old Queue outcomes rows that --outcomes does not carry forward move to +# "- **Queue outcomes anteriores:**" (newest first), never deleted. +# - Dry-run and apply print the same line diff (- removed / + added) of HANDOFF. # # Smoke (dry-run, no mutations): # .cursor/scripts/run-plan-all-consolidate.sh --preflight @@ -65,7 +71,8 @@ OUTCOMES="none" TOUCH_ACTIVE_PLAN=0 usage() { - sed -n '2,36p' "$0" | sed 's/^# \{0,1\}//' + # Print the leading comment block (line 2 up to the first non-comment line). + awk 'NR == 1 { next } /^#/ { sub(/^# ?/, ""); print; next } { exit }' "$0" } die() { @@ -99,13 +106,20 @@ handoff_field() { sed -n "s/^- \\*\\*${label}:\\*\\*[[:space:]]*//p" "$HANDOFF" | head -n 1 } +# Current value of a field without its "· antes:" history trail. +field_head() { + local value="$1" + printf '%s' "${value%% · antes: *}" +} + queue_in_flight() { [[ -f "$HANDOFF" ]] || return 1 local mode status queue - mode="$(handoff_field "Mode")" - status="$(handoff_field "Queue status")" + mode="$(field_head "$(handoff_field "Mode")")" + status="$(field_head "$(handoff_field "Queue status")")" + status="${status%% *}" queue="$(handoff_field "Run queue")" - [[ "$mode" == "run-plan-all" ]] || return 1 + [[ "$mode" == "run-plan-all" || "$mode" == "run-plan-all "* ]] || return 1 if [[ "$status" == "running" || "$status" == "paused" || "$status" == "blocked" ]]; then return 0 fi @@ -144,8 +158,15 @@ assert_plan_live() { active_plan_basename() { local raw - raw="$(handoff_field "Plan")" - raw="${raw//\`/}" + local tick='`' + raw="$(field_head "$(handoff_field "Plan")")" + if [[ "$raw" == *"$tick"*"$tick"* ]]; then + # Plan name inside the first pair of backticks, e.g. `a.plan.md` (queue cursor 3). + raw="${raw#*"$tick"}" + raw="${raw%%"$tick"*}" + else + raw="${raw%% *}" + fi raw="${raw##*/}" printf '%s' "$raw" } @@ -284,19 +305,40 @@ cmd_drop() { } # Upsert "- **Label:** value" inside a working copy (never mutates HANDOFF directly). +# Values travel through ENVIRON, never awk -v (which rewrites backslash escapes). +# trail=1 keeps history: " · antes: " when the +# old head differs; an unchanged head leaves the line byte-identical. upsert_field_in_file() { local file="$1" local label="$2" local value="$3" + local trail="${4:-0}" local tmp tmp="$(mktemp)" if grep -q "^- \\*\\*${label}:\\*\\*" "$file"; then - awk -v lab="$label" -v val="$value" ' - BEGIN { done=0 } + UPSERT_LABEL="$label" UPSERT_VALUE="$value" UPSERT_TRAIL="$trail" awk ' + BEGIN { + lab = ENVIRON["UPSERT_LABEL"] + val = ENVIRON["UPSERT_VALUE"] + trail = ENVIRON["UPSERT_TRAIL"] + sep = " · antes: " + done = 0 + } { - if (!done && $0 ~ ("^- \\*\\*" lab ":\\*\\*")) { - print "- **" lab ":** " val - done=1 + if (!done && index($0, "- **" lab ":**") == 1) { + done = 1 + old = substr($0, length("- **" lab ":**") + 1) + sub(/^[ \t]+/, "", old) + head = old + cut = index(old, sep) + if (cut > 0) head = substr(old, 1, cut - 1) + sub(/[ \t]+$/, "", head) + if (trail == "1" && head == val) { print; next } + if (trail == "1" && old != "" && old != "none" && old != "`none`") { + print "- **" lab ":** " val sep old + } else { + print "- **" lab ":** " val + } next } print @@ -309,51 +351,85 @@ upsert_field_in_file() { mv "$tmp" "$file" } -# Replace Queue outcomes block using a side file (supports multiline; never awk -v). +# Replace the live Queue outcomes block using a side file (multiline; never awk -v). +# Old rows that the new block does not carry forward (exact match after trim; "none" +# placeholders ignored) move to "- **Queue outcomes anteriores:**", newest first, +# right after the live block. Existing prior rows are kept (deduplicated). replace_outcomes_in_file() { local file="$1" local outcomes_file="$2" local tmp tmp="$(mktemp)" awk -v ofile="$outcomes_file" ' + function trim(x) { sub(/^[ \t]+/, "", x); sub(/[ \t]+$/, "", x); return x } + function placeholder(x) { return (x == "" || x == "none" || x == "- none" || x == "`none`") } + function is_live(x) { return (x ~ /^- \*\*Queue outcomes:\*\*/) } + function is_prior(x) { return (x ~ /^- \*\*Queue outcomes anteriores:\*\*/) } + function inline_of(x) { sub(/^- \*\*[^*]+:\*\*/, "", x); return trim(x) } + # Same block-end rule as the original rewrite: a field, heading or blank line ends it. + function ends_block(x) { + if (x ~ /^- \*\*/ || x ~ /^#/ || x ~ /^$/) return 1 + if (x ~ /^ / || x ~ /^[[:space:]]*-/) return 0 + return 1 + } BEGIN { n = 0 while ((getline line < ofile) > 0) { + if (trim(line) == "") continue n++ lines[n] = line + isnew[trim(line)] = 1 } close(ofile) - skip = 0 - done = 0 + nold = 0; nprior = 0; mode = 0 } - function emit_outcomes( i) { + # Pass 1: collect old live rows and existing prior rows. + FNR == NR { + if (is_live($0)) { mode = 1; r = inline_of($0); if (r != "") old[++nold] = r; next } + if (is_prior($0)) { mode = 2; r = inline_of($0); if (r != "") prior[++nprior] = r; next } + if (mode != 0 && ends_block($0)) mode = 0 + if (mode == 1) old[++nold] = trim($0) + else if (mode == 2) prior[++nprior] = trim($0) + next + } + FNR == 1 { + # Build the prior block: displaced rows first (newest), then existing ones. + np = 0 + for (i = 1; i <= nold; i++) { + r = old[i] + if (placeholder(r) || (r in isnew) || (r in seen)) continue + seen[r] = 1; outp[++np] = r + } + for (i = 1; i <= nprior; i++) { + r = prior[i] + if (placeholder(r) || (r in seen)) continue + seen[r] = 1; outp[++np] = r + } + skip = 0; done = 0 + } + function emit_blocks( i) { print "- **Queue outcomes:**" - for (i = 1; i <= n; i++) { - if (lines[i] != "") print " " lines[i] + for (i = 1; i <= n; i++) print " " lines[i] + if (np > 0) { + print "- **Queue outcomes anteriores:**" + for (i = 1; i <= np; i++) print " " outp[i] } } + # Pass 2: emit, dropping the old live and prior blocks wherever they are. { - if ($0 ~ /^- \*\*Queue outcomes:\*\*/) { - emit_outcomes() - skip = 1 - done = 1 - next + if (is_live($0)) { + if (!done) emit_blocks() + done = 1; skip = 1; next } + if (is_prior($0)) { skip = 1; next } if (skip == 1) { - if ($0 ~ /^- \*\*/ || $0 ~ /^#/ || $0 ~ /^$/) { - skip = 0 - } else if ($0 ~ /^ / || $0 ~ /^[[:space:]]*-/) { - next - } else { - skip = 0 - } + if (ends_block($0)) skip = 0 + else next } - if (skip == 0) print + print } - END { - if (!done) emit_outcomes() - } - ' "$file" >"$tmp" + END { if (!done) emit_blocks() } + ' "$file" "$file" >"$tmp" mv "$tmp" "$file" } @@ -470,13 +546,8 @@ cmd_rewrite_queue() { [[ -n "$item" ]] && info " $item" done <<< "$outcomes_display" - if [[ "$DRY_RUN" -eq 1 ]]; then - rm -f "$outcomes_file" - info "dry-run: HANDOFF not written (pass --apply --approved to mutate)" - return 0 - fi - - # Build the full rewrite in a working copy, then atomically replace HANDOFF. + # Build the full rewrite in a working copy (dry-run and apply share it), then + # print the line diff and, on apply, atomically replace HANDOFF. local work work="$(mktemp)" if [[ -f "$HANDOFF" ]]; then @@ -491,19 +562,55 @@ cmd_rewrite_queue() { } >"$work" fi - upsert_field_in_file "$work" "Plan" "\`${activate}\`" - upsert_field_in_file "$work" "Last updated" "$stamp" - upsert_field_in_file "$work" "Mode" "run-plan-all" + upsert_field_in_file "$work" "Plan" "\`${activate}\`" 1 + upsert_field_in_file "$work" "Last updated" "$stamp" 1 + upsert_field_in_file "$work" "Mode" "run-plan-all" 1 upsert_field_in_file "$work" "Run queue" "$queue_bracket" - upsert_field_in_file "$work" "Queue cursor" "$cursor_line" - upsert_field_in_file "$work" "Queue status" "$STATUS" + upsert_field_in_file "$work" "Queue cursor" "$cursor_line" 1 + upsert_field_in_file "$work" "Queue status" "$STATUS" 1 replace_outcomes_in_file "$work" "$outcomes_file" rm -f "$outcomes_file" + print_rewrite_diff "$work" + local prior_rows + prior_rows="$(awk ' + /^- \*\*Queue outcomes anteriores:\*\*/ { on = 1; next } + on && (/^- \*\*/ || /^#/ || /^$/) { on = 0 } + on && /^ / { c++ } + END { print c + 0 } + ' "$work")" + info "Queue outcomes anteriores: ${prior_rows} row(s) kept from earlier queues" + + if [[ "$DRY_RUN" -eq 1 ]]; then + rm -f "$work" + info "dry-run: HANDOFF not written (pass --apply --approved to mutate)" + return 0 + fi + atomic_replace_file "$work" "$HANDOFF" info "HANDOFF queue fields updated (atomic)" } +# Print every HANDOFF line the rewrite removes (-) or adds (+). Unchanged lines are +# omitted; a "· antes:" trail shows up as the old line removed and the trailed line added. +print_rewrite_diff() { + local work="$1" + local base="$HANDOFF" + [[ -f "$base" ]] || base="/dev/null" + local out rc=0 + out="$(diff -U0 "$base" "$work")" || rc=$? + if [[ "$rc" -gt 1 ]]; then + die "diff failed (exit $rc) while previewing the HANDOFF rewrite" + fi + info "HANDOFF line diff (- removed, + added):" + if [[ "$rc" -eq 0 ]]; then + info " (no changes)" + return 0 + fi + # Skip the two file headers and the @@ hunk markers; keep content lines verbatim. + printf '%s\n' "$out" | tail -n +3 | grep -v '^@@' | sed 's/^/ /' +} + cmd_merge_checklist() { local source target source="$(normalize_plan "$1")" diff --git a/.cursor/skills/community/cursor-skills-node/SKILL.md b/.cursor/skills/community/cursor-skills-node/SKILL.md index aedb937..2be0123 100644 --- a/.cursor/skills/community/cursor-skills-node/SKILL.md +++ b/.cursor/skills/community/cursor-skills-node/SKILL.md @@ -1,42 +1,17 @@ --- name: cursor-skills-node -description: CURSOR-SKILLS rules for Node.js (Express, NestJS, Next.js). ESLint, Prettier, tests. -version: 0.1.0 +description: Kit guidance for Node.js (Express, NestJS, Next.js): repo tooling first, strict types, validated config, thin handlers. +version: 0.2.0 category: language --- -# CURSOR-SKILLS - Node.js +# Node.js and TypeScript -Source: [cursor-skills/node](https://github.com/araguaci/cursor-skills/tree/main/node) - -## CURSOR setup - -- ES6 snippets, Node Extension Pack, npm Intellisense, Prettier, ESLint, Thunder Client / REST Client. - -## Typical structure - -``` -project/ -├── src/ ├── tests/ ├── docs/ ├── node_modules/ -├── package.json ├── package-lock.json └── .env -``` - -## Packages - -- npm or yarn; `package-lock.json`/`yarn.lock`; separate dev deps; semver; scripts in `package.json`. - -## By framework - -- **Express**: middleware, routes, error handling; `source.fixAll.eslint`, format on save. -- **NestJS**: modules, services, controllers, DI; TypeScript, ESLint. -- **Next.js**: pages, App Router, API routes, SSR/SSG/ISR; Emmet for `javascriptreact`. - -## Code - -- ES6+; TypeScript when it makes sense; error handling; JSDoc; standardization (Prettier, ESLint). -- **Tests**: Jest or Mocha; coverage ≥ 80%. - -## Security, DB, and APIs - -- Validate inputs; OWASP; hashing; HTTPS. Sequelize/TypeORM; avoid N+1; transactions. -- REST: HTTP codes, versioning, JSON; auth, rate limit, CORS. +- **Use the repo's tooling.** One package manager and its lockfile; the Node version pinned (`engines`, `.nvmrc` or mise). Lint and format with the repo's config. +- **TypeScript is strict.** No `any` without a comment saying why. Follow the package's module type (ESM or CJS) and do not mix them. +- **Async:** `async`/`await`, no floating promises, a timeout on every outbound call. +- **Config comes from the environment,** validated once at startup; the process fails fast. No `process.env` scattered through the code. +- **Thin handlers.** Route handlers and controllers parse and respond; logic lives in services, I/O in adapters. This holds for Express, NestJS and Next.js route handlers. +- **Next.js:** server components by default, client components marked on purpose, secrets only on the server. +- **Security:** validate input, never `eval`, run a dependency audit in CI. +- **Tests:** colocated or under `tests/`; unit tests make no network calls. diff --git a/.cursor/skills/core/hitl-gates/run-plan-all-queue.md b/.cursor/skills/core/hitl-gates/run-plan-all-queue.md index 5489d8a..2f2e9c0 100644 --- a/.cursor/skills/core/hitl-gates/run-plan-all-queue.md +++ b/.cursor/skills/core/hitl-gates/run-plan-all-queue.md @@ -169,7 +169,7 @@ Use the safe helper after the confirm Ask grants consolidations. Canonical launc | Drop / archive | `.cursor/scripts/run-plan-all-consolidate.sh --drop PLAN.plan.md --apply --approved` (refuse overwrite unless `--force-overwrite`) | | HANDOFF queue rewrite | `.cursor/scripts/run-plan-all-consolidate.sh --rewrite-queue --queue "a.plan.md,b.plan.md" --cursor 0 --status running --activate a.plan.md --apply --approved` | -`--rewrite-queue` validates and normalizes `--outcomes` (including multiline) **before** any HANDOFF mutation, then applies Plan/Mode/queue/cursor/status/outcomes as one atomic rewrite. Invalid outcomes (for example a line that looks like a HANDOFF machine field) refuse with the file untouched. Backlog CRUD callers still cannot rewrite the queue. +`--rewrite-queue` validates and normalizes `--outcomes` (including multiline) **before** any HANDOFF mutation, then applies Plan/Mode/queue/cursor/status/outcomes as one atomic rewrite. Invalid outcomes (for example a line that looks like a HANDOFF machine field) refuse with the file untouched. Backlog CRUD callers still cannot rewrite the queue. The rewrite keeps history by default (no flag). Plan, Mode, Last updated, Queue cursor and Queue status become ` · antes: ` when the value changes (an unchanged value leaves the line as it was; Run queue is replaced bare). Old Queue outcomes rows that `--outcomes` does not carry forward move to `- **Queue outcomes anteriores:**` right after the live block, newest first: history, not live outcomes (the orchestrator and `agent-kit queue` read only `- **Queue outcomes:**`; `agent-kit handoff` keeps both). Dry-run prints the same HANDOFF line diff as the apply (`-` removed, `+` added): read it before `--apply --approved`. Queue field shape aligns with `serializeRunPlanAllQueueFields` in `packages/cli/src/plan-loop/run-plan-all-orchestrator.ts` (machine-field bullets only). This path does not promote. diff --git a/.gitignore b/.gitignore index 9ae79e1..c5ec85d 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ # Generated readiness snapshot and init/scan profile (local workspace state) .cursor/context/readiness.json +.cursor/context/install-health.json # Local Field Report dismissals (attention IDs only; no transcript body) .cursor/context/field-report-dismissals.json # Local Field Report per-plan verdicts (plan basenames + Ask provenance; no review prose) @@ -23,6 +24,8 @@ .cursor/context/gate-exit.json # Local review job ledger (branch -> last reviewed tip; countdown --job review) .cursor/context/review-ledger.json +# Local countdown cost ledger (one NDJSON line per fire; append-only) +.cursor/context/cost-ledger.ndjson # Local pending-only plan index (generated from HANDOFF-named plans) .cursor/context/plan-index.json # Local /run-plan-all queue owner lease (pid, session, heartbeat; run-plan-all only) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf5d683..f4ed610 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,45 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and ## [Unreleased] +## [6.25.0] - 2026-11-28 + +### Added + +- Consumer configuration documents the command shapes a self-started headless loop needs under `claude -p --permission-mode dontAsk` with a closed allowlist (start in the worktree root, one command per call, no `cd`, `&&` or pipes, prefix rules), so a night tick no longer stops on a denied compound command before it tests or commits. +- `agent-kit countdown` keeps a local cost ledger and can refuse a fire over budget. Every fire except a usage error appends one JSON line to `.cursor/context/cost-ledger.ndjson` (`at`, `repo`, `plan`, `todo`, `job`, `backend`, `model`, `cost_usd`, `input_tokens`, `output_tokens`, `exit`, `outcome`; `null` where unknown), and the `AGENT_KIT_RESULT` line gains `cost_usd` as its last field. The cost is what the job's agent sessions printed on their result lines: sessions add up, a later result of the same session is shown as `$X session total` and replaces that session's earlier figure (claude reports a running total), and a backend that reports no cost gives `null`, never 0. Token counts are not printed by the job and stay `null`. The ledger is gitignored (the installer adds the pattern; an older install gets a clone-local `.git/info/exclude` line before the first write), append-only and never leaves the machine; a failed write prints one warning and keeps the exit code. `--budget-remaining ` refuses the fire before anything is fetched, with exit 2, `outcome` `needs-operator`, a `budget: ...` reason and a ledger line, when the value is 0 or less, or below `AGENT_KIT_CLAUDE_MAX_BUDGET_USD` times the ticks of the fire; a value that is not a number, or an empty one, is a usage error (exit 1). The consumer configuration guide has a wrapper that computes the night's remaining budget from the ledger with `jq`. `agent-kit run-plan` exit codes and driver events are unchanged (protocol 1.5.0). + +### Changed + +- `agent-kit countdown` now exits 5 (needs operator) when the tick ended because the agent requested a stop (`LOOP_TICK_RESULT: stop - `) while the plan still has to-dos, instead of 0. A stop when no pending or in-progress to-do is left stays 0, a gate stays 2 and Circuit's Dead stays 3. Every fire, refusals and usage errors included, now ends with one machine-readable stdout line, `AGENT_KIT_RESULT {"outcome":"ok|needs-operator|broken","reason":"...","repo":"...","plan":"...","todo":"...","exit":N}`, always the last line Countdown writes. Compatibility: a wrapper or timer that treated every 0 as "did work" now sees 5 on a stop; treat it like 2 (the documented systemd unit now has `SuccessExitStatus=2 5`). `agent-kit run-plan` still exits 0 on an agent stop and its driver events are unchanged (protocol 1.5.0). + +## [6.24.0] - 2026-11-28 + +### Added + +- `agent-kit installs` keeps a per-machine index of where the kit is installed, in `~/.config/agent-kit/installs.json` (`$XDG_CONFIG_HOME` respected, `AGENT_KIT_INSTALLS_FILE` overrides): path, `origin` remote without credentials, kit version, CLI version, last seen and a kind (`repo`, `worktree`, `fixture`, `factory` or `home`). `install`, `init`, `update` and `doctor` record the repo they ran in, silently, and a registry problem never fails them. `agent-kit installs scan [--root ]...` finds `.cursor/agent-kit.json` under bounded roots (default `$HOME`, depth 5, at most 20,000 folders, skipping `node_modules`, build output and hidden folders except `.worktrees` and `.claude/worktrees`, never following symlinks). `agent-kit installs list [--json]` shows the rows and `agent-kit installs prune` drops the ones whose folder or manifest is gone. The index is never written inside a repo, and the repo's own manifest wins over it. +- `agent-kit doctor` reports install health in a new `install:` section, read-only: the global CLI against npm `latest` (both `@dadado/agent-kit-cli` and `@missionkit/cli`, binaries `agent-kit` and `missionkit`); a CLI living inside a per-version node dir of mise, nvm, nvm-windows or fnm, whose globals vanish on the next node switch, with one fix line per manager (for mise, the exact `~/.config/mise/config.toml` tool entry); a home-level install under `~/.cursor` older than the repo's kit, naming its paths without moving them; and a semver `registry.ref` pin older than the CLI, with `agent-kit update --ref`. Volta, Homebrew and system node are not flagged. The npm lookup is skipped under `CI` or with `updateCheck.enabled: false` and fails open when offline. Doctor writes the result to `.cursor/context/install-health.json` (gitignored), and Mission Control Health shows it as an Install group, outside the seven workspace checks (`dashboardDataVersion` 1.14.0). +- An update notice, on by default and check-only. At most once a day (cached in `update-notice.json` next to `installs.json`) the CLI asks npm for `latest`, and on every session it compares each registered `repo` and `home` install with the CLI (worktrees, fixtures and the factory are left out). When something is behind, sessionStart adds one line naming the command, for example ``Agent Kit: CLI 6.19.1 < npm 6.22.0 (`npm i -g @dadado/agent-kit-cli@latest`); 9 installs behind, oldest v3.0.0 at ~/x (`agent-kit update --all`).``, and Mission Control Health shows one Updates card with the count and the oldest install (`dashboardDataVersion` 1.15.0; a broadcast snapshot carries no path). A CLI inside a per-version node dir points at `agent-kit doctor` for the install that survives a node switch. It is silent when everything is current, off under `CI`, with `updateCheck.enabled: false` or with `AGENT_KIT_NO_UPDATE_CHECK=1` (or `NO_UPDATE_NOTIFIER=1`), and a failed npm lookup is skipped silently until the next day (installs behind the CLI are still reported). It never applies anything. +- `agent-kit update --all` updates every repository in the install index in one pass, and only when you type it: it refuses without a terminal (stdin and stdout must be a TTY) and inside an agent session (Claude Code, Cursor agent, a headless or plan-loop run), and `--yes` does not lift either. It first stops when the CLI is not the npm `latest`, because the update stamps the CLI's version. Then it prints one plan table (current and target version, pre-prod branch and how far behind origin it is, dirty kit files, queue lease) with a skip reason per row: current, worktree (`--include-worktrees` to include them), fixture, factory, home install, live writer, diverged pre-prod branch, dirty kit files, a major jump that needs a single-repo `update`, or a `chore/kit-X.Y.Z` branch that already exists. After one confirm, each repo in turn fast-forwards its pre-prod branch (`staging`, else the default branch; never a rebase), branches `chore/kit-X.Y.Z`, applies the update, commits only the kit files it wrote, pushes and opens one PR (`gh`) or MR (`glab -R host/group/repo`); a repo without a remote gets the branch and commit only. A summary table lists the links and per-repo errors; one failing repo does not stop the others, a rerun skips what is already open, and nothing is ever merged. + +### Changed + +- The shell guard (`agent-kit guard shell`, used by the Cursor and Claude hooks) now lets `git restore --staged ` through: it only resets the index and keeps the edit. `git restore `, `--worktree` / `-W`, and `git checkout -- ` stay denied, and `git checkout --theirs` / `--ours ` is now denied with or without `--`. Every denial now ends with what to run instead (for example `git stash`, `git restore --staged `, `git reset --keep `, or a working branch and a PR into staging). A merge whose PR/MR base the guard cannot resolve names the literal `-R` form for its forge (`gh pr merge -R owner/repo` or `glab mr merge -R host/group/repo`). +- `updateCheck.enabled` now defaults to `true`: the check only notifies, and `install` and `doctor` take the npm answer from the same daily machine cache instead of stamping `.cursor/context/config.json`. Set `updateCheck.enabled: false` to turn it off. `updateApply.auto` still defaults to `false`; apply stays the `/update` confirm or an explicit `agent-kit update`. +- The commands catalog contract (`docs/mission-control-embedding.md`) now says a host runs a catalog row with its context, and that `/git-prod` and `/kit-prod` are interactive only rather than never runnable: a host may open them in a session you drive, after its own confirmation, and their production gate inside that session is the yes. Colony does this from its palette, menus and buttons. + +- Getting started now has one row per node manager (mise, nvm, nvm-windows, fnm; Volta, Homebrew and system node are not affected) with the fix that keeps `agent-kit` on `PATH` across node upgrades, notes that the mise entry was checked with mise 2026.11.10 on Linux only, and documents the default-on update notice and `agent-kit update --all`. `/update` points the operator to `update --all` when several repos are behind, and the Ubuntu bare-metal guide and README link the node-manager install. +- The stack and language rules (`cursor-skills-general`, `-api`, `-devops`, `-integrations`, `-mobile`, `-node`, `-php`, `-python`, `-testing`, `-webdesign`) and the matching community skills (`cursor-skills-api`, `-integrations`, `-mobile`, `-node`, `-php`, `-python`, `-webdesign`) are rewritten as short guidance written by the kit, with no third-party text. File names, skill ids, globs and `alwaysApply` are unchanged, so existing installs keep working and `agent-kit update` replaces the content in place. `categories.md` now lists the `api`, `language`, `mobile` and `web` categories those skills already used. + +### Removed + +- The `cursor-skills-groovy` rule and community skill, whose origin could not be shown. `agent-kit update` deletes an unedited installed copy, keeps and reports an edited one, and drops `cursor-skills-groovy` from `skills` in `.cursor/agent-kit.json`. + +### Fixed + +- `/run-plan-all` queue rewrites (`.cursor/scripts/run-plan-all-consolidate.sh --rewrite-queue`) no longer erase HANDOFF history. Plan, Mode, Last updated, Queue cursor and Queue status keep their `· antes:` trail with the new value in front, old Queue outcomes rows that are not carried forward move to a `Queue outcomes anteriores` bullet instead of being deleted, and the dry-run prints every line the apply would remove or add. `agent-kit handoff` keeps the prior-outcomes bullet when it regenerates the HANDOFF. +- The `/update` troubleshooting fallback is now `npx -y @dadado/agent-kit-cli update` instead of `pnpm exec agent-kit update`, which only worked inside a repo that lists the CLI as a dependency. +- `agent-kit update`, `diff` and `install` now accept a manifest that still lists a pre-rename L1 pack id (`gestao-projeto`, `gestao-contexto`, `engenharia-arquitetura`). The id resolves to its English pack, and `update` and `install` rewrite it in `.cursor/agent-kit.json` with one line per rename. A pack id the registry does not ship is now a named warning with the next step (`diff`, `update`) or a clean error (`install --pack`), instead of `Pack '…' not found in registry.` with a stack trace. + ## [6.23.0] - 2026-11-24 ### Changed diff --git a/PRIVACY.md b/PRIVACY.md index 5ca8196..2a6be61 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -4,7 +4,7 @@ Mission Kit (Agent Kit on npm) collects no telemetry. ## Install, init, and hooks -`agent-kit init` (`packages/cli/src/commands/init.ts`) is a wrapper over install. `agent-kit install` (`packages/cli/src/commands/install.ts`) writes local project files. Neither command posts usage events, identifiers, or prompt text. +`agent-kit init` (`packages/cli/src/commands/init.ts`) is a wrapper over install. `agent-kit install` (`packages/cli/src/commands/install.ts`) writes local project files. Neither command posts usage events, identifiers, or prompt text. `install`, `init`, `update` and `doctor` also record the repository's local path, its `origin` remote (credentials stripped) and kit version in a machine index, `~/.config/agent-kit/installs.json`, which stays on your machine (`agent-kit installs` lists it). Hooks in `.cursor/hooks/` call the local CLI. The shell adapters do not open a network connection. Two optional checks stay off unless `.cursor/context/config.json` turns them on (`updateCheck.enabled` and `cursorUpdateCheck.enabled` both default to false in `.cursor/context/config.example.json`): diff --git a/README.md b/README.md index f6a0122..ec24247 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ npx @dadado/agent-kit-cli dashboard npx @dadado/agent-kit-cli dashboard-broadcast ``` -`npx` is ephemeral: it never leaves an `agent-kit` bin on your `PATH`. Run `npm i -g @dadado/agent-kit-cli` once if you prefer the bare `agent-kit dashboard` form. Using mise with `node = "latest"`? Install it as a mise tool instead, or the next node patch drops it: [Getting started - mise](docs/getting-started.md#how-to-invoke-them). +`npx` is ephemeral: it never leaves an `agent-kit` bin on your `PATH`. Run `npm i -g @dadado/agent-kit-cli` once if you prefer the bare `agent-kit dashboard` form. Using mise with `node = "latest"` (or nvm, fnm)? Install it as a mise tool instead, or the next node patch drops it: [Getting started - node managers](docs/getting-started.md#how-to-invoke-them). Once installed, the kit tells you at session start when the CLI or a repo falls behind, and `agent-kit update --all` (typed in your own terminal) opens one update PR/MR per repo. Open the **printed** URL if the browser did not open (with `PORT` unset, each workspace gets a stable port in `3333–3588`; do not assume `:3333`). In Cursor chat, `/dashboard` starts the same flow. diff --git a/categories.md b/categories.md index c796d2d..5a8cb48 100644 --- a/categories.md +++ b/categories.md @@ -10,6 +10,10 @@ Official list of categories for skill metadata. Used in frontmatter (`category`) | devops | CI/CD, deploy, infra, environment scripts | | quality | Tests, accessibility, UX, code review | | creation | Creation of skills, rules, agents; generators; technical design | +| api | API design and contracts: REST, GraphQL, gRPC, OpenAPI | +| language | Language and runtime conventions: Node.js, PHP, Python | +| mobile | Mobile apps: React Native, Expo, Flutter | +| web | Web front end: HTML, CSS, JavaScript frameworks, accessibility | ## Usage in frontmatter @@ -23,4 +27,4 @@ category: data --- ``` -Value of `category` must be one of the table items (ex.: `integrations`, `data`, `docs`, `devops`, `quality`, `creation`). +Value of `category` must be one of the table items (ex.: `integrations`, `data`, `docs`, `devops`, `quality`, `creation`, `api`, `language`, `mobile`, `web`). diff --git a/claude-directory/.claude-plugin/plugin.json b/claude-directory/.claude-plugin/plugin.json index c1da1d8..f45382e 100644 --- a/claude-directory/.claude-plugin/plugin.json +++ b/claude-directory/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "agent-kit", "displayName": "Mission Kit", - "version": "6.23.0", + "version": "6.25.0", "description": "Plan, build, review, ship, keep: a working routine for long-term projects with Claude Code. Plans with to-dos you approve, review agents, staging-to-production gates that wait for your yes, and a handoff and memory that survive new chats.", "author": { "name": "agent-kit-startup" diff --git a/claude-directory/README.md b/claude-directory/README.md index df72ff4..5e3891a 100644 --- a/claude-directory/README.md +++ b/claude-directory/README.md @@ -46,7 +46,7 @@ State, memory and a live view that survive new chats and new agents. ## Install -This folder is the plugin as listed in the Claude plugin directory (version 6.23.0): the commands, agents and skills above, and no hooks or scripts. The commands work on a repository prepared by the agent-kit CLI (`agent-kit install`); see [install.md](https://github.com/agent-kit-startup/agent-kit/blob/main/install.md). Mission Control comes with the CLI. +This folder is the plugin as listed in the Claude plugin directory (version 6.25.0): the commands, agents and skills above, and no hooks or scripts. The commands work on a repository prepared by the agent-kit CLI (`agent-kit install`); see [install.md](https://github.com/agent-kit-startup/agent-kit/blob/main/install.md). Mission Control comes with the CLI. The full kit (every command, the session-start context and the shell guard hooks) installs from the repository marketplace: diff --git a/dashboard/dashboard-data.mjs b/dashboard/dashboard-data.mjs index 469e10d..45dfa64 100644 --- a/dashboard/dashboard-data.mjs +++ b/dashboard/dashboard-data.mjs @@ -6,7 +6,8 @@ import { execFile, execFileSync } from "node:child_process"; import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; -import { dirname, join, resolve } from "node:path"; +import { homedir } from "node:os"; +import { dirname, isAbsolute, join, resolve } from "node:path"; import { collectChats } from "./lib/chat-sessions.mjs"; import { collectGateExitTickets } from "./lib/gate-exit-tickets.mjs"; import { @@ -171,7 +172,7 @@ function redactTerminalOutput(text) { const SNAPSHOT = { _schema: { - version: "1.13.0", + version: "1.15.0", description: "Mission Control dashboard data model", fields: { generatedAt: "ISO-8601 timestamp of snapshot generation", @@ -205,12 +206,12 @@ const SNAPSHOT = { "Running process snapshots (node, serve.mjs, git operations) with elapsed time and a generated narration per process", skills: "Available skills discovered in .cursor/skills/", health: - "Aggregated health: status ok|warning|degraded|not-initialized (error only on the serve empty-checks path) and the fixed seven checks[] ({id, label, ok, severity: ok|warning|degraded|not-initialized, detail}); ok means severity === ok; not-initialized marks a fresh workspace (no plans, no HANDOFF, no memory entries); Commands, Config and Agents also read a Mission Kit Cursor or Claude Code plugin install (1.13.0)", + "Aggregated health: status ok|warning|degraded|not-initialized (error only on the serve empty-checks path) and the fixed seven checks[] ({id, label, ok, severity: ok|warning|degraded|not-initialized, detail}); ok means severity === ok; not-initialized marks a fresh workspace (no plans, no HANDOFF, no memory entries); Commands, Config and Agents also read a Mission Kit Cursor or Claude Code plugin install (1.13.0); install ({generatedAt, status ok|warning, checks[] ({id: global-cli|node-manager|home-install|registry-pin, label, ok, severity: ok|warning, detail, fix|null})}|null) is the machine install health that `agent-kit doctor` last wrote to .cursor/context/install-health.json, read-only and outside checks[] and status; null when doctor has not run; broadcast keeps no paths and no fix (1.14.0); updateNotice ({generatedAt, cliVersion, npmLatest|null, cliBehind, installsBehind, oldest {kitVersion, path|null}|null, label, severity: warning, detail, fix|null}|null) is the machine update notice the sessionStart hook last wrote beside ~/.config/agent-kit/installs.json: registered repo/home installs behind the CLI and the CLI behind npm; check-only, null when current or off (CI, AGENT_KIT_NO_UPDATE_CHECK, NO_UPDATE_NOTIFIER, updateCheck.enabled false); broadcast keeps no path and no fix (1.15.0)", missionControl: "Normalized now/activity/attention/plans view model (source-backed; bounded)", }, }, generatedAt: new Date().toISOString(), - dashboardDataVersion: "1.13.0", + dashboardDataVersion: "1.15.0", plans: [], system: { repoRoot: ROOT, @@ -228,7 +229,7 @@ const SNAPSHOT = { outcomeLedger: emptyOutcomeLedgerSummary(), processes: [], skills: [], - health: { status: "ok", checks: [] }, + health: { status: "ok", checks: [], install: null }, missionControl: null, }; @@ -1645,6 +1646,126 @@ const checks = [ ]; SNAPSHOT.health.checks = checks; + +// Install health (c2): written by `agent-kit doctor`, read here fail-open. A +// sibling of checks[] so the fixed seven ids and the aggregate stay unchanged. +const INSTALL_HEALTH_IDS = new Set(["global-cli", "node-manager", "home-install", "registry-pin"]); +function readInstallHealth() { + const raw = healthReadJson(join(ROOT, ".cursor", "context", "install-health.json")); + if (!raw || typeof raw !== "object" || !Array.isArray(raw.checks)) return null; + const items = raw.checks + .filter((c) => c && typeof c === "object" && INSTALL_HEALTH_IDS.has(c.id)) + .map((c) => { + const severity = c.severity === "warning" ? "warning" : "ok"; + const label = truncateStr(typeof c.label === "string" ? c.label : c.id, 80); + const rawFix = typeof c.fix === "string" && c.fix ? c.fix : null; + // Only a ready-to-run command becomes a terminal copy; a config line (the + // mise tool entry) or a template with a placeholder rides in the detail. + const fix = rawFix && c.fixKind === "command" ? rawFix : null; + const baseDetail = typeof c.detail === "string" ? c.detail : ""; + const fullDetail = + rawFix && !fix + ? `${baseDetail} (${c.fixKind === "config-line" ? "add" : "fix"}: ${rawFix})` + : baseDetail; + return { + id: c.id, + label, + ok: severity === "ok", + severity, + // Paths are home-relative on disk; a broadcast snapshot carries none. + detail: HEALTH_BROADCAST + ? severity === "ok" + ? "No action needed" + : "Needs attention: run agent-kit doctor on this machine" + : truncateStr(fullDetail, 800), + fix: HEALTH_BROADCAST ? null : fix && truncateStr(fix, 300), + }; + }); + return { + generatedAt: typeof raw.generatedAt === "string" ? raw.generatedAt : null, + status: items.some((c) => c.severity === "warning") ? "warning" : "ok", + checks: items, + }; +} +SNAPSHOT.health.install = readInstallHealth(); + +// Update notice (c4): `agent-kit hook session-start` writes the computed notice +// into the machine cache beside installs.json; read here fail-open, never +// computed (no semver or install-kind logic in the dashboard). Same gates as the +// CLI: off under CI, the env opt-out and `updateCheck.enabled: false`. +function updateNoticeFile(env) { + const override = + typeof env.AGENT_KIT_INSTALLS_FILE === "string" ? env.AGENT_KIT_INSTALLS_FILE.trim() : ""; + if (override) return join(dirname(resolve(override)), "update-notice.json"); + const xdg = typeof env.XDG_CONFIG_HOME === "string" ? env.XDG_CONFIG_HOME.trim() : ""; + const configDir = xdg && isAbsolute(xdg) ? xdg : join(homedir(), ".config"); + return join(configDir, "agent-kit", "update-notice.json"); +} +function envFlagOn(value) { + if (typeof value !== "string") return false; + const v = value.trim().toLowerCase(); + return v !== "" && v !== "0" && v !== "false"; +} +function readUpdateNotice() { + const env = process.env; + if ( + envFlagOn(env.CI) || + envFlagOn(env.AGENT_KIT_NO_UPDATE_CHECK) || + envFlagOn(env.NO_UPDATE_NOTIFIER) + ) { + return null; + } + const cfg = healthReadJson(join(ROOT, ".cursor", "context", "config.json")); + if (cfg && typeof cfg === "object" && cfg.updateCheck && cfg.updateCheck.enabled === false) + return null; + const raw = healthReadJson(updateNoticeFile(env)); + const n = raw && typeof raw === "object" ? raw.notice : null; + if (!n || typeof n !== "object" || typeof n.line !== "string" || !n.line) return null; + const count = Number.isInteger(n.installsBehind) && n.installsBehind > 0 ? n.installsBehind : 0; + const cliBehind = n.cliBehind === true; + if (!count && !cliBehind) return null; + const cliVersion = typeof n.cliVersion === "string" ? truncateStr(n.cliVersion, 32) : null; + const npmVersion = + n.npmLatest && typeof n.npmLatest.version === "string" + ? truncateStr(n.npmLatest.version, 32) + : null; + const oldest = + count && n.oldest && typeof n.oldest === "object" && typeof n.oldest.kitVersion === "string" + ? { + kitVersion: truncateStr(n.oldest.kitVersion, 32), + // Home-relative on disk; a broadcast snapshot carries no path. + path: + HEALTH_BROADCAST || typeof n.oldest.path !== "string" + ? null + : truncateStr(n.oldest.path, 300), + } + : null; + const parts = []; + if (cliBehind && npmVersion) parts.push(`CLI ${cliVersion} is behind npm ${npmVersion}`); + if (count) { + const where = oldest?.path ? ` at ${oldest.path}` : ""; + parts.push( + `${count} ${count === 1 ? "install" : "installs"} behind CLI ${cliVersion}${oldest ? `, oldest v${oldest.kitVersion}${where}` : ""}`, + ); + } + const cliCommand = + typeof n.cliCommand === "string" && n.cliCommand ? truncateStr(n.cliCommand, 200) : null; + // The CLI first: `update --all` stamps the CLI version, so an old CLI cannot reach npm latest. + const fix = cliBehind && cliCommand ? cliCommand : count ? "agent-kit update --all" : null; + return { + generatedAt: typeof n.generatedAt === "string" ? n.generatedAt : null, + cliVersion, + npmLatest: npmVersion, + cliBehind, + installsBehind: count, + oldest, + label: count ? `${count} ${count === 1 ? "install" : "installs"} behind` : "CLI behind npm", + severity: "warning", + detail: `${parts.join("; ")}. Check-only: nothing is applied.`, + fix: HEALTH_BROADCAST ? null : fix, + }; +} +SNAPSHOT.health.updateNotice = readUpdateNotice(); SNAPSHOT.health.status = checks.some((c) => c.severity === "degraded") ? "degraded" : workspaceFresh diff --git a/dashboard/dashboard.html b/dashboard/dashboard.html index 5d69536..b005094 100644 --- a/dashboard/dashboard.html +++ b/dashboard/dashboard.html @@ -6409,7 +6409,8 @@ ? frc.tickThreshold : 3; const uc = cfg.updateCheck || {}; - const updateCheckEnabled = !!uc.enabled; + // On by default (check-only); only an explicit false turns it off. + const updateCheckEnabled = uc.enabled !== false; const updateCheckInterval = typeof uc.intervalDays === 'number' && Number.isFinite(uc.intervalDays) ? uc.intervalDays : 7; const modeRows = CONFIG_PERSONA_MODES.map((mode) => { @@ -6463,7 +6464,7 @@
- Update check (opt-in) + Update check (on by default, notify only)
@@ -6746,6 +6747,42 @@ }, }; +/** + * Machine install health (`health.install`, written by `agent-kit doctor`): + * a separate group outside the fixed seven checks and the aggregate status. + * Absent until doctor has run on this workspace. + */ +/** + * Machine update notice (`health.updateNotice`): one card with the count of + * registered installs behind the CLI and the oldest one, or the CLI behind + * npm. Null when everything is current or the check is off. + */ +function renderUpdateNoticeGroup(notice, renderCard) { + if (!notice || typeof notice !== 'object' || !notice.label) return ''; + return ` +
+
Updates (check-only, at most daily)
+
+ ${renderCard({ id: 'update-notice', label: notice.label, ok: false, severity: 'warning', detail: notice.detail, fix: notice.fix })} +
+
`; +} + +function renderInstallHealthGroup(install, renderCard) { + const items = install && Array.isArray(install.checks) ? install.checks : []; + if (items.length === 0) return ''; + const title = install.generatedAt + ? `Install (agent-kit doctor, ${install.generatedAt.slice(0, 10)})` + : 'Install (agent-kit doctor)'; + return ` +
+
${escapeHtml(title)}
+
+ ${items.map(renderCard).join('')} +
+
`; +} + /** Vitals grouping: checks grouped into vital systems for the diagnosis dashboard. */ const HEALTH_VITAL_GROUPS = [ { label: 'Planning spine', checks: ['plans', 'handoff'] }, @@ -9507,9 +9544,13 @@ const sev = healthCheckSeverity(c, healthStatus); const notStarted = sev === 'not-initialized'; const detail = (typeof c.detail === 'string' && c.detail) || (c.ok ? meta.okDetail : meta.failDetail); + // Install checks (health.install) carry their own terminal fix line. + const ownFix = typeof c.fix === 'string' && c.fix + ? { text: c.fix, subject: c.fix, destination: 'terminal', label: 'Copy fix' } + : null; const autofix = c.ok || notStarted ? null - : (meta.autofixBySeverity && meta.autofixBySeverity[sev]) || meta.autofix || null; + : ownFix || (meta.autofixBySeverity && meta.autofixBySeverity[sev]) || meta.autofix || null; const fixPrompt = [`Fix this failing health check: ${c.label || id}`, detail].join('\n'); const fixBtn = ``; const autofixBtn = autofix @@ -9581,7 +9622,7 @@
${g.items.map(renderCheckCard).join('')}
- `).join('')}`; + `).join('')}${renderUpdateNoticeGroup(health.updateNotice, renderCheckCard)}${renderInstallHealthGroup(health.install, renderCheckCard)}`; } parts.push(` diff --git a/dashboard/lib/live-refresh.mjs b/dashboard/lib/live-refresh.mjs index e905b87..3186dee 100644 --- a/dashboard/lib/live-refresh.mjs +++ b/dashboard/lib/live-refresh.mjs @@ -35,6 +35,7 @@ export const SNAPSHOT_REPO_SOURCE_RELS = Object.freeze([ ".cursor/context/config.json", ".cursor/context/current", ".cursor/context/readiness.json", + ".cursor/context/install-health.json", ".cursor/context/field-report-dismissals.json", ".cursor/context/field-report-plan-verdicts.json", ".cursor/context/mission-timing.json", diff --git a/docs/bootstrap.md b/docs/bootstrap.md index d83c5f8..a521994 100644 --- a/docs/bootstrap.md +++ b/docs/bootstrap.md @@ -72,7 +72,7 @@ The kit can update itself against the same source without ever touching your pla **Multi-workspace safety:** each project keeps its own `.cursor/agent-kit.json` manifest and `.cursor/agent-kit.managed-hashes.json` overlay ledger. The CLI confirms the absolute root before writing (interactive prompt; `--yes` skips). The shared registry cache (`~/.cache/agent-kit/registry/`) is directory-locked so parallel installs cannot race. -**Check ≠ apply.** Opt-in session nudges use `updateCheck.enabled` in `.cursor/context/config.json` (default `false`). When enabled, `sessionStart` may advise that a newer public release exists; it never rewrites `.cursor/`. Applying still requires `/update` with Ask confirmation (or an explicit terminal `agent-kit update`). `updateApply.auto` defaults to `false` and is not a silent background path. +**Check ≠ apply.** The update notice is on by default and check-only: at most once a day, `sessionStart` prints one line when the CLI is behind npm or a registered install is behind the CLI; it never rewrites `.cursor/`. Turn it off with `updateCheck.enabled: false` in `.cursor/context/config.json` or `AGENT_KIT_NO_UPDATE_CHECK=1`; it is always off under `CI`. Applying still requires `/update` with Ask confirmation (or an explicit terminal `agent-kit update`). `updateApply.auto` defaults to `false` and is not a silent background path. **Cursor product updates (separate):** opt-in `cursorUpdateCheck.enabled` (default `false`) plus `agent-kit cursor-awareness --check` / `/cursor-update-awareness` report advisory gaps vs `docs/cursor-native-audit.md` (walk-up from cwd; use `--cwd` when the inventory is not under the shell directory). Confirmed work routes through Ask → `/backlog-add` or `/dogfood`. Never auto Field Reports. See [cursor-update-awareness.md](cursor-update-awareness.md). diff --git a/docs/capability-inventory.md b/docs/capability-inventory.md index c61c161..3ed3077 100644 --- a/docs/capability-inventory.md +++ b/docs/capability-inventory.md @@ -56,7 +56,7 @@ Factory-only counting policy: inventories that describe the **consumer/L0** surf - `cursor-plan-handoff.mdc` - Multi-phase plan execution with HANDOFF contract - `context-guardian.mdc` - Context window monitoring with automatic handoff - `cursor-skills-git-workflow.mdc` - Staging-to-production Git flow enforcement -- `cursor-skills-general.mdc` - Base CURSOR-SKILLS principles and conventions +- `cursor-skills-general.mdc` - Kit baseline for code and repository hygiene - `ux-tone.mdc` - Chat tone guidelines with persona chrome support - `agent-output-hygiene.mdc` - Chat vs repository content separation - `docs-professional-standard.mdc` - Project documentation voice and inheritance standard @@ -69,7 +69,6 @@ Factory-only counting policy: inventories that describe the **consumer/L0** surf - `cursor-skills-n8n.mdc` - n8n workflow editing patterns - `cursor-skills-api.mdc` - REST/GraphQL API development standards - `cursor-skills-devops.mdc` - CI/CD and infrastructure guidance -- `cursor-skills-groovy.mdc` - Groovy syntax and integration rules - `cursor-skills-integrations.mdc` - Webhooks, microservices, database patterns - `cursor-skills-json.mdc` - JSON validation and formatting standards - `cursor-skills-mobile.mdc` - React Native, Flutter, Expo development diff --git a/docs/coherence-inventory.md b/docs/coherence-inventory.md index 789d90c..4c699e8 100644 --- a/docs/coherence-inventory.md +++ b/docs/coherence-inventory.md @@ -24,7 +24,6 @@ Living inventory for internal coherence (`f6-coherence`). Classifies each artifa | `cursor-skills-n8n.mdc` | stack | false | ✅ globs; skill path updated | | `cursor-skills-api.mdc` | stack | false | ✅ keep | | `cursor-skills-devops.mdc` | stack | false | ✅ keep | -| `cursor-skills-groovy.mdc` | stack | false | ✅ keep (community language) | | `cursor-skills-integrations.mdc` | stack | false | ✅ keep | | `cursor-skills-json.mdc` | stack | false | ✅ keep; pairs with `json-data-config` skill | | `cursor-skills-mobile.mdc` | stack | false | ✅ keep | @@ -163,7 +162,7 @@ Install path = pack/registry member, or dogfood-only / demoted (see [domain-pack 1. **`.cursor/hooks.json`** - ✅ shipped (sessionStart / preCompact); optional later: shell gate for push to main, prompt secrets check. 2. **Registry-canonical public cutover** - see [topology-private-public.md](topology-private-public.md) for Phase B status and remaining ops work. -3. **Stack language rules** (php/groovy/mobile/…) - keep as stack; no promotion to L0. +3. **Stack language rules** (php/mobile/…) - keep as stack; no promotion to L0. 4. **`skills-registry.json` / `_legacy/v2`** - obsolete paths; do not resurrect flat skill ids. 5. **`package.json` / `.cursor-plugin/plugin.json` version sync** - version alignment checked against current `package.json`; bump on next release tag, not blocking inventory truth. diff --git a/docs/consumer-configuration.md b/docs/consumer-configuration.md index 6fe41e8..d9e9f79 100644 --- a/docs/consumer-configuration.md +++ b/docs/consumer-configuration.md @@ -90,13 +90,14 @@ Invocation-time inputs; not persisted configuration. The table lists consumer-fa | `agent-kit run` | ``, `--cwd`, `--backend auto\|cursor-agent\|claude\|codex\|cursor-acp\|openrouter`, `--model`, `--dry-run`, `--plain`, `--no-hitl` | One headless session from `.cursor/commands/.md`. `auto` picks the first installed CLI. Catalog: run-plan (aliases the tick loop), run-plan-all, continue-plan, start-project, backlog-*, git-staging. `git-prod` / `kit-prod` are refused (operator-gated; no `--force` promote). Factory `kit-staging` is not in the catalog. `run run-plan --backend claude` aliases the tick loop on the `claude` backend (implemented 2026-09-06); see the `agent-kit run-plan` row for flags, env, and the terminal rendering / HITL relay shared with `run-plan` and `run-plan-all` below. On the `claude` backend a catalog slash is spawned with the same headless argv as a tick (`--dangerously-skip-permissions --permission-prompts none --output-format stream-json`), because the dispatched L0 bodies edit files and run git and plain `claude -p` would deny every Edit/Write/Bash while still exiting 0; the same env passthrough, redaction, nested-session strip, version floor, and opt-in caps apply. `run-plan-all` is also a first-class citty command (`agent-kit run-plan-all`); typing `/run-plan-all` in zsh is a filesystem path. | | `agent-kit run-plan-all` | `--cwd`, `--backend auto\|cursor-agent\|claude\|codex\|cursor-acp\|openrouter`, `--model`, `--dry-run`, `--plain`, `--no-hitl` | First-class citty name for `agent-kit run run-plan-all`. Dispatches `.cursor/commands/run-plan-all.md` (catalog; not the `run-plan` tick loop). `agent-kit /run-plan-all` rewrites to this name. Typing `/run-plan-all` in zsh is a filesystem path. A `per-plan-release` queue confirm ships inside the dispatched command. `agent-kit run git-prod` stays refused. Same terminal rendering, `--plain` gate and HITL relay as `agent-kit run-plan` below (both backends; `cursor-agent` follows its own published `tool_call` event shape). | | `agent-kit run-plan` | `--max-ticks N`, `--model M`, `--sleep S`, `--backend auto\|cursor-agent\|claude\|codex\|cursor-acp\|openrouter`, `--dry-run`, `--plain`, `--no-hitl`; env `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN` (gateway routing on the `claude` backend; on every backend, `cursor-agent` included, any value present in the runner environment is redacted from every tick log, tip and error), `AGENT_KIT_CLAUDE_MAX_TURNS`, `AGENT_KIT_CLAUDE_MAX_BUDGET_USD` (`claude` backend only; opt-in runaway caps, no default) | Runs the tick loop; `--backend claude` detail, terminal rendering, and the HITL relay/transport are covered below the table (`#### agent-kit run-plan detail`), not in this cell. | -| `agent-kit countdown` | `--cwd`, `--job tick\|dispatch\|review`, `--slash ` (dispatch only), `--backend`, `--model`, `--max-ticks N` (default 1), `--max-pack-bytes N` (review only, default 98304), `--include-reviewed` (review only), `--window-min M` (default 120), `--stall-min M` (default 20); env `AGENT_KIT_CLAUDE_MAX_TURNS`, `AGENT_KIT_CLAUDE_MAX_BUDGET_USD` (passed through to the job) | One-shot launcher for an external timer (cron, a systemd timer, a CI schedule); never a daemon. Runs one headless job with `--no-hitl --land-on-gate` and refuses to start while a gate exit is pending. Exit codes: 0 completed (a clean review included), 2 gate exit pending, gate reached or review findings landed, 3 Circuit's Dead (failed, stalled, over the window, dirty tree, fetch failed). `git-prod` / `kit-prod` refused. See the detail below. | +| `agent-kit countdown` | `--cwd`, `--job tick\|dispatch\|review`, `--slash ` (dispatch only), `--backend`, `--model`, `--max-ticks N` (default 1), `--max-pack-bytes N` (review only, default 98304), `--include-reviewed` (review only), `--window-min M` (default 120), `--stall-min M` (default 20), `--budget-remaining `; env `AGENT_KIT_CLAUDE_MAX_TURNS`, `AGENT_KIT_CLAUDE_MAX_BUDGET_USD` (passed through to the job) | One-shot launcher for an external timer (cron, a systemd timer, a CI schedule); never a daemon. Runs one headless job with `--no-hitl --land-on-gate` and refuses to start while a gate exit is pending or when `--budget-remaining` does not cover the fire. Exit codes: 0 completed (a clean review and a stop on an exhausted plan included), 1 usage error, 2 gate exit pending, gate reached, review findings landed or budget refused, 3 Circuit's Dead (failed, stalled, over the window, dirty tree, fetch failed), 5 needs operator (the tick ended because the agent requested a stop while to-dos remain). The last stdout line is always `AGENT_KIT_RESULT {...}` (one JSON object, with the fire's `cost_usd`), and each fire appends one line to `.cursor/context/cost-ledger.ndjson`. `git-prod` / `kit-prod` refused. See the detail below. | | `agent-kit sessions` | `--live`, `--json`, `--cwd` | Without `--live`: the folder's saved Claude Code chats with their resume commands (`--json`: `{withheld, vendors[]}`, unchanged). With `--live`: a read-only roster of the agents running in the workspace now (see [Live agents and the workspace lease](#live-agents-and-the-workspace-lease)). Always exit `0`; a missing source is a note. | | `agent-kit queue lease` | `--json`, `--cwd` | Read-only probe of `.cursor/context/run-plan-all.lock`: exit `0` when free, stale or held by the caller's own session (`AGENT_KIT_QUEUE_LEASE_SESSION`); exit `1` with a `Queue lease held:` line while another live session holds it. Never writes the lease. | | `agent-kit ground-control` | `status [--json]`, `accept `, `discard `, each with `--cwd` | Exit 0 done, 1 usage or unknown stamp, 2 `accept` while the branch is unmerged, 3 a git or forge step failed (the ticket is kept). Never merges; [detail](#agent-kit-ground-control-detail) | | `agent-kit conflicts` | `[--json]`; `propose [--backend claude\|cursor-agent] [--json] [--verify [--verify-cmd ] [--verify-timeout ]] [--dry-run]`, each with `--cwd` | Read-only. Lists unmerged paths as hunks (ours, base, theirs). `propose` runs the `resolve-conflicts` prompt in a no-tools session outside the repository, refuses proposals with conflict markers, a missing or repeated hunk, or edits around the hunk, and, only with `--verify`, verifies the resolved file in a temporary worktree (`stack.validationCommands` and `stack.testCommands` from HEAD, or `--verify-cmd`). Verification is off by default because it runs code nobody has reviewed yet, the model's text and the files the merge brought in, unsandboxed, as you, with your environment and network; pass `--verify` only for a branch whose code you trust (`--verify-cmd` without `--verify` exits 1). The temporary worktree has no dependencies installed, so on a Node repository pass the install first, for example `--verify --verify-cmd 'pnpm install --frozen-lockfile --prefer-offline && pnpm test'` (npm: `npm ci --prefer-offline && npm test`); when verification fails and `node_modules` is still missing, the verification note prints that command for the repository's lockfile and verification commands. Exit 0 done, 1 usage, not an unmerged path, or a refused file (binary, deleted, unparsable). Never writes, stages, commits or pushes | | `agent-kit commands` | `--json`, `--cwd` | Reads `.cursor/commands/*.md` of the `--cwd` workspace (default: the current directory). Plain output is one line per command with its layer and tags (`headless`, `interactive-only`, `meta`, `context: `); `--json` prints the versioned catalog ([contract](mission-control-embedding.md#commands-catalog)). Catalog 1.1.0 adds per command `context` (`none`, `goal`, `plan`, `branch`, `pr`, `sha`: what a host may pass after the slash), `interactiveOnly` (`git-prod`, `kit-prod`: never headless or from a driver) and `audience` (`meta` commands exist to build or ship the kit and hosts hide them outside the factory workspace), read from each command file's frontmatter; a project command without them gets `none`, `false` and `user`. Read-only: it lists, never runs. | | Mission Control server | `PORT` (default 3333), `HOST`, `MISSION_CONTROL_REPO_ROOT`, `MISSION_CONTROL_KIT_ROOT` / `AGENT_KIT_HOME` (Path C kit-root fallback), `MISSION_CONTROL_TOKEN` (LAN broadcast), `MISSION_CONTROL_SHARE_BASE` / `MISSION_CONTROL_SHARE_TTL_SEC` / `MISSION_CONTROL_SHARE_SHOW_LAN` (cosmetic Share URL mask), `MISSION_CONTROL_NO_OPEN`, `MISSION_CONTROL_PREFERRED_BROWSER`, `agent-kit dashboard --browser`, `agent-kit dashboard-broadcast --browser`, `AGENT_KIT_DASHBOARD_DATA_TIMEOUT_MS`, `AGENT_KIT_DASHBOARD_DATA_BUDGET_MS` | Kit-root fallback is documented in README Path C and `/dashboard`. Preferred browser: one OS open (app/binary) or OS default; never multi-open. ADR `2026-08-11_mission-control-preferred-browser.md`. Share mask: ADR `2026-08-11_mission-control-broadcast-url-mask.md`. | +| `agent-kit installs` | `list [--json]` (default), `scan [--root ]... [--depth N] [--max-dirs N] [--json]`, `prune [--json]`; env `AGENT_KIT_INSTALLS_FILE`, `XDG_CONFIG_HOME` | Machine install registry at `~/.config/agent-kit/installs.json` (`$XDG_CONFIG_HOME/agent-kit/` when set; `AGENT_KIT_INSTALLS_FILE` overrides the file): one row per kit install with path, `origin` remote without credentials, kit version, CLI version, last seen and kind (`repo`, `worktree`, `fixture`, `factory`, `home`). `install`, `init`, `update` and `doctor` record their repo silently and fail open. `scan` walks bounded roots (default `$HOME`, depth 5, at most 20,000 folders; skips `node_modules`, build output and hidden folders except `.worktrees` and `.claude/worktrees`; never follows symlinks). `prune` drops rows whose folder or manifest is gone. An index only: never written inside a repo, and the repo manifest wins. ADR `2026-08-02_multi-workspace-install-isolation-surfaces.md` (amend 2026-11-26). | | Registry / hooks | `AGENT_KIT_REGISTRY`, `ALLOW_MAIN_PUSH` | `ALLOW_MAIN_PUSH=1` disables main-push protection for the session (doctor warns). | | Audits, `backend: "cloud"` | `CURSOR_API_KEY` | **Secret.** Cursor user or service-account key for Cursor Cloud Agents (`@cursor/sdk` uses the same variable). Supply it from the environment or a gitignored `.env`; `.env.example` ships an empty placeholder only. Never commit, echo, log, or persist it — it must not appear in `.cursor/context/audit-wait/*.json`, monitors, CHANGELOG, dogfood, or HANDOFF. Prefer a service-account key for shared use; Team Admin keys are not supported. ADR `2026-08-14_cursor-cloud-agents-sdk-audits-backend.md`. | @@ -174,11 +175,57 @@ Mission Control and Colony keep their existing process views; reading this roste Countdown fires one headless job per invocation and exits; scheduling belongs to the operating system timer, never to the kit. Each fire, in order: -1. Fetches `origin` with `--prune` (a failed fetch is exit 3: pending gate-exit branches cannot be checked). -2. Refuses while `.cursor/context/gate-exit.json` lists a pending gate exit: it appends `skipped ` to the marker and exits 2 (an unreadable marker also exits 2). Triage the gate exit first. -3. Refuses on a dirty working tree (exit 3); the tree is reported, never cleaned. Run Countdown in a dedicated clone or worktree, not the checkout you edit by hand. -4. Refuses when an unmerged `gate-exit/*` branch exists and the marker has no entry for it (exit 2). -5. Runs the job: `--job tick` (default) is `agent-kit run-plan --max-ticks 1 --no-hitl --land-on-gate`; `--job dispatch --slash ` is `agent-kit run ` with the same flags; `--job review` is `agent-kit run review-pack` (below). The child's gate stops and failures land through `--land-on-gate`. +1. With `--budget-remaining `, refuses when the remaining budget does not cover the fire (exit 2, below), before anything is fetched. +2. Fetches `origin` with `--prune` (a failed fetch is exit 3: pending gate-exit branches cannot be checked). +3. Refuses while `.cursor/context/gate-exit.json` lists a pending gate exit: it appends `skipped ` to the marker and exits 2 (an unreadable marker also exits 2). Triage the gate exit first. +4. Refuses on a dirty working tree (exit 3); the tree is reported, never cleaned. Run Countdown in a dedicated clone or worktree, not the checkout you edit by hand. +5. Refuses when an unmerged `gate-exit/*` branch exists and the marker has no entry for it (exit 2). +6. Runs the job: `--job tick` (default) is `agent-kit run-plan --max-ticks 1 --no-hitl --land-on-gate`; `--job dispatch --slash ` is `agent-kit run ` with the same flags; `--job review` is `agent-kit run review-pack` (below). The child's gate stops and failures land through `--land-on-gate`. + +Exit codes and the result line: + +| Exit | `outcome` | Meaning | +|------|-----------|---------| +| 0 | `ok` | The job completed: a tick that continued or used up its budget, a stop on an exhausted plan, a clean review, nothing to review. | +| 1 | `broken` | Usage error (bad flag, a `--budget-remaining` that is not a number, unknown job or slash, not a git repository, malformed `roles`). | +| 2 | `needs-operator` | A gate exit is pending (refused at preflight, a gate reached with no reply, review findings landed): triage it with `agent-kit ground-control`. Or `--budget-remaining` refused the fire (`reason` starts with `budget:`): wait for the next budget window or raise it. | +| 3 | `broken` | Circuit's Dead: the job failed, stalled or ran past the window, the tree was dirty, or the fetch failed. | +| 5 | `needs-operator` | The tick ended because the agent requested a stop (`LOOP_TICK_RESULT: stop - `: a question for you, nothing implementable) while the plan still has to-dos. | + +A stop counts as an exhausted plan, and stays 0, only when the active plan has no pending or in-progress to-do left after the run; a reason such as "no implementable to-dos" with to-dos left is a 5. Only when the plan cannot be read does the reason text decide (`plan exhausted`, `nothing to do`, `no implementable` and similar mean 0). The agent stop is read for `--job tick` and its alias `--job dispatch --slash run-plan`, never for other jobs. A gate takes precedence: a stop next to a new pending gate exit is 2. Exit 5 lands no gate-exit note, so the next fire is not refused and will likely stop on the same question until you answer it in the plan or HANDOFF. `agent-kit run-plan` itself still exits 0 on an agent stop, and its driver events (`run_end.exitCode`, protocol 1.5.0) are unchanged; only Countdown maps the stop to 5, from the `Agent requested stop:` line the tick prints. Compatibility: a wrapper that treated every 0 as "did work" now sees 5 on a stop; treat 5 like 2 (waiting for you, not a failure). + +Every fire, refusals and usage errors included, ends with exactly one machine-readable line, the last line Countdown writes to stdout (also appended to the run log): + +```text +AGENT_KIT_RESULT {"outcome":"needs-operator","reason":"agent requested stop: which database?","repo":"my-app","plan":"poc.plan.md","todo":"k1","exit":5,"cost_usd":1.85} +``` + +`outcome` follows the table above, `reason` is one redacted line, `repo` is the workspace folder name, `plan` the active plan file of a tick job (else `null`) and `todo` the single `in_progress` to-do after the run (`null` when there is none or more than one). `exit` repeats the process exit code. `cost_usd` is what the job's agent sessions reported spending (below), or `null` when nothing was reported. Fields may be added at the end in later releases; read them by name. The job's own output is echoed above it, so a script should take the last line that starts with `AGENT_KIT_RESULT `, for example ` countdown ... | grep '^AGENT_KIT_RESULT ' | tail -n 1`. + +Cost ledger and budget: every fire except a usage error appends one JSON line to `.cursor/context/cost-ledger.ndjson` in the workspace, written just before the `AGENT_KIT_RESULT` line. The file is local only (nothing is sent anywhere), append-only and gitignored: the installer adds the pattern, and when the repository's `.gitignore` does not list it yet the CLI adds it to the clone-local `.git/info/exclude` before the first write, so it never makes the tree dirty. A failed write prints one `countdown: warning: cost ledger not written: ...` line and never changes the exit code. One line per fire, `null` where unknown: + +```json +{"at":"2026-11-28T03:00:00.000Z","repo":"my-app","plan":"poc.plan.md","todo":"k1","job":"tick","backend":"claude","model":null,"cost_usd":1.85,"input_tokens":null,"output_tokens":null,"exit":0,"outcome":"ok"} +``` + +`at` is the fire time, `model` the model Countdown passed to the job (`null` for the backend default), `exit` and `outcome` repeat the result line. The cost is read from the `✦ result ... · $X` lines the job prints, so it is what the agent CLI itself reported, rounded as printed (to the cent above $0.10): sessions add up (each tick, a post-tick review), and a later result of the same session, printed as `$X session total`, replaces that session's earlier figure, because `claude` reports a running total. Today the figure comes from `claude`'s result events; `cursor-agent`, `cursor-acp` and `codex` print none and leave `cost_usd` `null`, never 0. Token counts are not printed by the job and stay `null`. A refused fire records `cost_usd: null`. + +`--budget-remaining ` refuses the fire (exit 2, one `countdown: refused: budget: ...` line, an `AGENT_KIT_RESULT` with `outcome` `needs-operator`, `reason` `budget: ...` and `cost_usd` `null`, and a ledger line) when the value is 0 or less, or when `AGENT_KIT_CLAUDE_MAX_BUDGET_USD` is set and the value is below that per-tick cap times the ticks of this fire (`--max-ticks`; one for `--job review`). A value that is not a number, an empty one included, is a usage error (exit 1), so a wrapper whose computation failed never fires unchecked. Countdown keeps no budget itself: a wrapper computes what is left, for example a nightly budget of $20 summed from the ledger over the last 12 hours (requires `jq` and GNU `date`): + +```bash +#!/bin/sh +# countdown-night.sh: one fire with what is left of tonight's $20 budget +repo= +ledger="$repo/.cursor/context/cost-ledger.ndjson" +since=$(date -u -d '12 hours ago' +%Y-%m-%dT%H:%M:%S) +spent=0 +[ -f "$ledger" ] && spent=$(jq -rs --arg since "$since" \ + '[.[] | select(.at >= $since) | .cost_usd // 0] | add // 0' "$ledger") +left=$(awk -v s="$spent" 'BEGIN { printf "%.2f", 20 - s }') +exec countdown --cwd "$repo" --backend claude --budget-remaining="$left" +``` + +A negative remainder (`--budget-remaining=-0.35`) refuses like 0. Set `AGENT_KIT_CLAUDE_MAX_BUDGET_USD` too, so a fire never starts with less than one tick's cap left and a `claude` tick stops at that cap. A fire whose job prints no cost (another backend) counts as 0 in this sum, so budget such backends another way. Review job (`--job review`, `claude` or `cursor-agent` only): the CLI builds a diff pack of the branches not merged into the base (`git log` and `git diff` against the merge base, newest branch first), leaving out the base, the remote default branch, `gate-exit/*` branches and `.cursor/gate-exit/`, so a review never reviews its own notes. It also leaves out, and counts in the pack header: @@ -207,8 +254,8 @@ OnFailure=.service Type=oneshot WorkingDirectory= ExecStart= countdown --backend claude -# Exit 2 is a gate waiting for you, not a failure; only Circuit's Dead (3) or a usage error (1) triggers OnFailure=. -SuccessExitStatus=2 +# Exit 2 (a gate) and 5 (the agent asked a question) wait for you, not failures; only Circuit's Dead (3) or a usage error (1) triggers OnFailure=. +SuccessExitStatus=2 5 ``` ```ini @@ -234,6 +281,16 @@ One fire at a time: Countdown takes no lock of its own. A systemd timer never st Put `` outside the working tree (for example under `$XDG_RUNTIME_DIR` or `/tmp`): an untracked lock file inside `` makes the next fire refuse a dirty tree. Use the same `flock -n ` prefix when you start Countdown by hand on a clone a timer also drives. +Your own headless loop with an allowlist. `agent-kit run-plan` and Countdown start `claude -p` with `--dangerously-skip-permissions --permission-prompts none` plus the kit's deny rules, so a tick never waits on a permission prompt. A wrapper that starts `claude -p` itself under `--permission-mode dontAsk` with a closed `--allowedTools` list (a common setup for a night loop) works only when the agent issues commands that match the list one by one. Allowlist rules match the whole command line, so a compound line is denied even when each part is allowed, and the tick stops before it tests or commits. Put the shapes in the tick prompt and in the allowlist together: + +- Start the session in the worktree root and never `cd`: a rule such as `Bash(git status)` does not match `cd && git status`. +- One command per call: no `&&`, `;`, `||` or pipes. Ask for `git add ` then `git commit -m ` as two calls. +- No subshells, `$(...)`, backticks or redirection into files; write files with the Edit/Write tools. +- Allow by prefix, for example `Bash(git status:*)`, `Bash(git diff:*)`, `Bash(git add:*)`, `Bash(git commit:*)`, `Bash(git push origin :*)`, `Bash(gh pr create:*)` or `Bash(glab mr create:*)`, `Bash(pnpm test:*)`, `Bash(pnpm lint:*)`, `Bash(agent-kit plan-index:*)`, `Bash(agent-kit queue lease)`. Never allow `git push origin main`, `git push --force`, merges into the production branch or `/git-prod`. +- Pass secrets through the environment of the tick only, never in the prompt, the allowlist or a unit file. + +When a tick still stops on a denied command, the transcript names it; add the exact shape to the list instead of widening the rule to `Bash(*)`. + Known limitations of the review job and Ground Control: - A squash or rebase merge is recognised when the base carries each changed file exactly as the branch left it. A branch squash-merged together with conflict resolutions or edits made only on the base side still counts as unmerged and is reviewed until you delete it (or turn on the forge's automatic head-branch deletion); after one completed review the ledger skips it while its tip stays the same. diff --git a/docs/contracts/mission-control-snapshot.schema.json b/docs/contracts/mission-control-snapshot.schema.json index 02a6ad6..a114ca7 100644 --- a/docs/contracts/mission-control-snapshot.schema.json +++ b/docs/contracts/mission-control-snapshot.schema.json @@ -3,7 +3,7 @@ "$id": "https://github.com/agent-kit-startup/agent-kit/blob/main/docs/contracts/mission-control-snapshot.schema.json", "title": "Mission Control snapshot", "description": "Output of dashboard/dashboard-data.mjs (one JSON document per refresh). Versioned by dashboardDataVersion: an added field or collector is a minor bump, a removed or retyped top-level field is a major bump. Only the top level, the runLogs rows, the gateExit tickets, the chats envelopes and sessions, the shipLane envelope and rows, the outcomeLedger summary, the rules rows and the memory.decisionIndex rows are fixed here; nested collector shapes may grow without a bump (additionalProperties stays open).", - "version": "1.13.0", + "version": "1.15.0", "type": "object", "required": [ "_schema", @@ -31,7 +31,7 @@ "properties": { "_schema": { "type": "object", "required": ["version", "fields"] }, "generatedAt": { "type": "string" }, - "dashboardDataVersion": { "type": "string", "const": "1.13.0" }, + "dashboardDataVersion": { "type": "string", "const": "1.15.0" }, "plans": { "type": "array" }, "system": { "type": "object", "required": ["repoRoot"] }, "agents": { "type": "array" }, @@ -209,8 +209,67 @@ "skills": { "type": "array" }, "health": { "type": "object", - "description": "status ok|warning|degraded|not-initialized (error only on the serve empty-checks path); checks[] carry id, label, ok, severity (ok|warning|degraded|not-initialized) and detail; ok means severity === ok (1.13.0).", - "required": ["status", "checks"] + "description": "status ok|warning|degraded|not-initialized (error only on the serve empty-checks path); checks[] carry id, label, ok, severity (ok|warning|degraded|not-initialized) and detail; ok means severity === ok (1.13.0). install is the machine install health `agent-kit doctor` last wrote, outside checks[] and status (1.14.0). updateNotice is the machine update notice (installs behind the CLI, CLI behind npm), check-only, null when current or off (1.15.0).", + "required": ["status", "checks"], + "properties": { + "updateNotice": { + "type": ["object", "null"], + "required": [ + "generatedAt", + "cliVersion", + "npmLatest", + "cliBehind", + "installsBehind", + "oldest", + "label", + "severity", + "detail", + "fix" + ], + "properties": { + "generatedAt": { "type": ["string", "null"] }, + "cliVersion": { "type": ["string", "null"] }, + "npmLatest": { "type": ["string", "null"] }, + "cliBehind": { "type": "boolean" }, + "installsBehind": { "type": "integer", "minimum": 0 }, + "oldest": { + "type": ["object", "null"], + "required": ["kitVersion", "path"], + "properties": { + "kitVersion": { "type": "string" }, + "path": { "type": ["string", "null"] } + } + }, + "label": { "type": "string" }, + "severity": { "const": "warning" }, + "detail": { "type": "string" }, + "fix": { "type": ["string", "null"] } + } + }, + "install": { + "type": ["object", "null"], + "required": ["generatedAt", "status", "checks"], + "properties": { + "generatedAt": { "type": ["string", "null"] }, + "status": { "enum": ["ok", "warning"] }, + "checks": { + "type": "array", + "items": { + "type": "object", + "required": ["id", "label", "ok", "severity", "detail", "fix"], + "properties": { + "id": { "enum": ["global-cli", "node-manager", "home-install", "registry-pin"] }, + "label": { "type": "string" }, + "ok": { "type": "boolean" }, + "severity": { "enum": ["ok", "warning"] }, + "detail": { "type": "string" }, + "fix": { "type": ["string", "null"] } + } + } + } + } + } + } }, "missionControl": { "type": ["object", "null"] }, "devops": { "type": "object", "required": ["pipeline", "deploy"] }, diff --git a/docs/cursor-native-audit.md b/docs/cursor-native-audit.md index 649f35b..e89ee0f 100644 --- a/docs/cursor-native-audit.md +++ b/docs/cursor-native-audit.md @@ -80,7 +80,6 @@ These run on every agent turn in Cursor: | `cursor-skills-n8n.mdc` | n8n workflows, `*workflow*.json` | | `cursor-skills-api.mdc` | api paths, OpenAPI, GraphQL | | `cursor-skills-devops.mdc` | Docker, CI, k8s, Terraform | -| `cursor-skills-groovy.mdc` | `*.groovy` | | `cursor-skills-integrations.mdc` | integrations, webhooks | | `cursor-skills-json.mdc` | `*.json` | | `cursor-skills-mobile.mdc` | mobile paths | @@ -101,7 +100,7 @@ These run on every agent turn in Cursor: ### Rule-mode compliance - Stack/product rules (ClickUp, n8n) correctly use `alwaysApply: false` per decision `2026-07-09_structural-harness-vs-stack`. -- Language CURSOR-SKILLS rules are stack-on-demand via globs - acceptable for dev ergonomics; not structural core. +- Language and stack rules (`cursor-skills-*`) are stack-on-demand via globs - acceptable for dev ergonomics; not structural core. - CLI generator (`packages/cli/src/generator/cursor.ts`) produces a **minimal** rule set (3–4 files) for new projects; it does not copy the full 25-rule workspace. Intentional L0 subset; document parity gap in Phase B cutover. --- diff --git a/docs/drift-inventory.md b/docs/drift-inventory.md index 513645d..91aae32 100644 --- a/docs/drift-inventory.md +++ b/docs/drift-inventory.md @@ -72,7 +72,7 @@ Present in **≥10 / 13** non-SoT workspaces that have `.cursor` (structural loo Present in many workspaces but **not** L0 (belong in L1 packs or L2 skills): -- Rules: `cursor-skills-n8n`, `node`, `sql`, `php`, `python`, `api`, `clickup`, `testing`, `webdesign`, `mobile`, `groovy`, `prompts`, `json`, `devops`, `integrations` +- Rules: `cursor-skills-n8n`, `node`, `sql`, `php`, `python`, `api`, `clickup`, `testing`, `webdesign`, `mobile`, `prompts`, `json`, `devops`, `integrations` - Skills: `n8n-workflows`, `sql-postgres`, `json-data-config`, `prompts-markdown`, `ux-message-flows`, `clickup` (registry community; not L0) These inflate “everyone has 20 rules” without being structural. diff --git a/docs/getting-started.md b/docs/getting-started.md index ec38304..8c5c867 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -128,7 +128,19 @@ Blocked on the global install by a root-owned npm prefix (`EACCES`)? Run `npx -y "npm:@dadado/agent-kit-cli" = { version = "latest", allow_low_downloads = true, minimum_release_age = "0s" } ``` -Then `mise install` and `agent-kit --version`. Remove an older global first (`npm rm -g @dadado/agent-kit-cli`) so only one `agent-kit` is on `PATH`. Both options are needed: a bare `mise use -g npm:@dadado/agent-kit-cli` is refused by mise's low-download guard, and mise's default minimum release age resolves `latest` to an older release. +Then `mise install` and `agent-kit --version`. Remove an older global first (`npm rm -g @dadado/agent-kit-cli`) so only one `agent-kit` is on `PATH`. Both options are needed: a bare `mise use -g npm:@dadado/agent-kit-cli` is refused by mise's low-download guard, and mise's default minimum release age resolves `latest` to an older release. This entry was checked with mise 2026.11.10 on Linux; older mise versions, macOS and Windows are untested, and an older mise that does not know `allow_low_downloads` or `minimum_release_age` may ignore them or reject the line. + +The same trap exists with every per-version node manager. `agent-kit doctor` names yours in its `install:` section and prints the fix for it: + +| Node manager | Why the CLI disappears | Fix | +|--------------|------------------------|-----| +| mise (`node = "latest"`) | Each node patch is a new, empty install directory | The `[tools]` entry above | +| nvm | Globals live in `~/.nvm/versions/node/` | `nvm install --reinstall-packages-from=`, or install under a fixed prefix: `npm i -g --prefix ~/.local @dadado/agent-kit-cli` with `~/.local/bin` on `PATH` | +| nvm-windows | Globals live in `%NVM_HOME%\` | `nvm use ` then `npm i -g @dadado/agent-kit-cli` | +| fnm | Globals live in `fnm/node-versions//installation` | `fnm use ` then `npm i -g @dadado/agent-kit-cli` | +| Volta, Homebrew node, system node | Not affected: globals survive a node upgrade | Nothing to do | + +Only the mise line was run on a real machine (Linux). The nvm, nvm-windows and fnm fixes follow each manager's documented behavior and are untested on macOS and Windows. The table below lists **subcommands**. Prefix each one with `npx @dadado/agent-kit-cli` (or with `agent-kit` after a global install). Most slash commands (`/agent-kit-onboard`, `/start-project`, …) are IDE chat commands and need neither. Typing `/run-plan-all` in zsh is a filesystem path; use `agent-kit run-plan-all` (or `agent-kit run run-plan-all`). @@ -143,6 +155,8 @@ The table below lists **subcommands**. Prefix each one with `npx @dadado/agent-k | `update --check` | Notify-only version compare vs public tags (no L0 writes) | | `cursor-awareness --check` | Opt-in advisory: Cursor changelog vs native-audit inventory (no apply) | | `update` | Explicit apply: pull latest rules/commands; leaves your own files alone | +| `update --all` | Operator-typed only: update every repo in the install index, one `chore/kit-X.Y.Z` branch and one PR/MR per repo, after one plan table and one confirm (`--include-worktrees` to include worktrees) | +| `installs [list\|scan\|prune]` | The per-machine index of kit installs (`~/.config/agent-kit/installs.json`) that the update notice and `update --all` read | | `diff` | Show what changed between what you have and the latest | | `contribute` | Send an improvement you made locally back upstream | | `handoff` | Save your progress to `.cursor/HANDOFF.md` | @@ -219,9 +233,10 @@ Details: [external plan review](external-plan-review.md). Routing ADR: `2026-08- ### Keeping Mission Kit current (consumers) -- **Opt-in check:** set `updateCheck.enabled: true` in `.cursor/context/config.json` (Mission Control Config can toggle it). SessionStart may then nudge when a newer public release exists; interval is `updateCheck.intervalDays` (default 7). +- **Update notice (on by default, check-only):** at most once a day the CLI asks npm for `latest` and compares it with the CLI, and compares every registered install with the CLI. When something is behind, sessionStart prints one line naming the command to run, and Mission Control Health shows one Updates card. It is silent when everything is current, off under `CI`, and off with `updateCheck.enabled: false` in `.cursor/context/config.json` or `AGENT_KIT_NO_UPDATE_CHECK=1` (`NO_UPDATE_NOTIFIER=1` works too). It never applies anything. - **Manual check:** `npx @dadado/agent-kit-cli@latest update --check --json`. - **Apply:** upgrade the CLI first if it is behind the target release (`npm i -g @dadado/agent-kit-cli@`) — `agent-kit update` stamps the manifest with the version of the CLI running it, so a stale binary re-applies the old version. Then run `/update` and confirm with Ask questions (or an explicit terminal `agent-kit update`). An apply whose registry is newer than the binary refuses with the pinned remedy. Never silent L0 overwrite; `updateApply.auto` defaults to `false`. +- **Every repo at once:** `agent-kit installs scan` fills the install index; then, in your own terminal, `agent-kit update --all`. It refuses inside an agent session and without a TTY, stops when the CLI is not the npm `latest`, prints one plan table (current and target version, pre-prod branch and how far behind, dirty kit files, queue lease, skip reason), and asks once. Each repo then gets its pre-prod branch fast-forwarded, a fresh `chore/kit-X.Y.Z` branch with only the kit files committed, a push and one PR (`gh`) or MR (`glab -R host/group/repo`). A repo without a remote gets the branch and commit only. Worktrees, fixtures, the kit's own repo, the home install, a live writer, a diverged pre-prod branch, dirty kit files and a major jump (for example v5 to v6, which needs a single-repo `update`) are skipped with a reason. It never merges: the PRs/MRs are yours to review and merge, and a rerun skips the ones already open. - Not the same as public sync (factory publish) or remote-cache refresh on resolve. ### Agent Personas @@ -272,7 +287,7 @@ To let a plan advance overnight, give a dedicated clone of the repository to `ag 0 3 * * * countdown --cwd --backend claude >/dev/null 2>&1 ``` -`` is the absolute path of the installed binary, `` the clone Countdown owns. The systemd timer and service pair, the caps (`--window-min`, `--stall-min`), the exit codes and the `flock -n` wrapper for cron are in [the countdown detail](consumer-configuration.md#agent-kit-countdown-detail). +`` is the absolute path of the installed binary, `` the clone Countdown owns. The systemd timer and service pair, the caps (`--window-min`, `--stall-min`, `--budget-remaining`), the cost ledger, the exit codes and the `flock -n` wrapper for cron are in [the countdown detail](consumer-configuration.md#agent-kit-countdown-detail). In the morning: diff --git a/docs/install-ubuntu24-bare-metal.md b/docs/install-ubuntu24-bare-metal.md index 539e5d5..e1910ef 100644 --- a/docs/install-ubuntu24-bare-metal.md +++ b/docs/install-ubuntu24-bare-metal.md @@ -62,7 +62,7 @@ Use `@latest` so npx does not reuse a stale cached CLI; pin `@x.y.z` when the pr npx @dadado/agent-kit-cli@latest status ``` -`status` lists the installed version and the L0 tree. Then open the project in Cursor or Claude Code and run `/agent-kit-onboard`, or run `npx @dadado/agent-kit-cli@latest doctor` from the same shell. `npx` leaves no `agent-kit` on `PATH`; run `npm i -g @dadado/agent-kit-cli` once if you want the bare command. +`status` lists the installed version and the L0 tree. Then open the project in Cursor or Claude Code and run `/agent-kit-onboard`, or run `npx @dadado/agent-kit-cli@latest doctor` from the same shell. `npx` leaves no `agent-kit` on `PATH`; run `npm i -g @dadado/agent-kit-cli` once if you want the bare command. With the NodeSource node from step 1 the global survives node upgrades; under mise, nvm or fnm use the install from [Getting started](getting-started.md#how-to-invoke-them) instead, or the next node switch drops it. ## If it fails diff --git a/docs/layers-spec.md b/docs/layers-spec.md index 68555d3..13cdb92 100644 --- a/docs/layers-spec.md +++ b/docs/layers-spec.md @@ -251,7 +251,7 @@ Every layer answers "safe to overwrite?" (above). A separate, size-oriented ques **Loads on glob** (Cursor-native, matched by file pattern, never always-on): -- The 15 globs-lazy rules under `.cursor/rules/cursor-skills-*.mdc`. +- The 14 globs-lazy rules under `.cursor/rules/cursor-skills-*.mdc`. **Budgets** (bytes, lines, and longest line only — never a token count; a token figure is a harness-internal detail the kit cannot pin or verify across hosts) are set per file class in `decisions/2026-09-20_contract-read-budget-and-laziness.md` and enforced as CI tests in `packages/cli/src/docs/size-budgets.test.ts`. In short: a consumer-L0 command stays under 150 lines / 8 KiB / 700 characters per line; its one-hop skill page under 250 lines / 10 KiB (or, for the handful of commands whose full procedure genuinely does not fit a stub-sized page, 400 lines / 48 KiB); the always-loaded classes (`alwaysApply` rule, globs-lazy rule, `.claude` command adapter) stay far smaller since every byte there is paid on every matching session. A split that only relocates bytes without cutting real duplication — as happened once (`#901`, `b142fdd`) — is a regression these tests catch; the numbers above are enforced, not aspirational. diff --git a/docs/marketplace.md b/docs/marketplace.md index 76af960..6b1cf39 100644 --- a/docs/marketplace.md +++ b/docs/marketplace.md @@ -137,7 +137,7 @@ Every channel where a release can reach users, how a new version gets there, and | HOL Registry | The public repository (the registry reads its plugin manifests) | `automatic` | Live since 2026-10-17. Not re-read on 2026-11-20 (the page refuses automated fetches); whether it shows each release is unverified | [hol.org/registry/plugins/agent-kit-startup/agent-kit](https://hol.org/registry/plugins/agent-kit-startup%2Fagent-kit) | | AUR `agent-kit-cli` | `packaging/aur/agent-kit-cli/` (PKGBUILD and `.SRCINFO` pinned to 6.9.0, built and checked 2026-10-24) | `operator-manual` (version bump and push per release) | Not published (2026-11-20): the package name is free on the AUR | none yet | | Homebrew tap | `packaging/homebrew/agent-kit.rb` (formula pinned to 6.9.0, not run here) | `operator-manual` (version and sha256 bump per release) | Not published (2026-11-20): the tap repository `agent-kit-startup/homebrew-tap` does not exist | none yet | -| mise registry | `packaging/mise/agent-kit.toml` (npm backend, no version pin) | `none` once registered (it follows npm) | Not registered (2026-11-20): no `registry/agent-kit.toml` in `jdx/mise`; npm weekly downloads 898 (2026-11-13 to 2026-11-19), under the 1000 that mise asks for | none yet | +| mise registry | `packaging/mise/agent-kit.toml` (npm backend, no version pin) | `none` once registered (it follows npm) | Not registered (2026-11-20): no `registry/agent-kit.toml` in `jdx/mise`; npm weekly downloads 898 (2026-11-13 to 2026-11-19), under the 1000 that mise asks for. Until then, the working entry is `"npm:@dadado/agent-kit-cli" = { version = "latest", allow_low_downloads = true, minimum_release_age = "0s" }` (checked with mise 2026.11.10 on Linux; `agent-kit doctor` prints it) | none yet | | Open VSX (Mission Control extension for Cursor) | Proposed: a generated `packages/` member published by a fail-closed tag job, version in lockstep with the kit release (ADR `2026-11-20_mission-control-cursor-extension-host.md`, point 6) | `automatic` | Not built (2026-11-21): the operator accepted the ADR on 2026-11-21, with the Open VSX namespace `missionkit`; no extension code yet | none yet | | Gemini CLI gallery | Root `gemini-extension.json`, generated by `scripts/sync-public.mjs` from the root `plugin.json` and the release version, plus the generated root `skills/` (see [Gemini CLI extension](#gemini-cli-extension)) | `automatic` once listed (the gallery and `gemini extensions update` read the public repository) | Not live (2026-11-22): the manifest is generated from the next tag on; the `gemini-cli-extension` topic on the public repository is an operator step, and the gallery lists the repository after a tag that carries both | none yet | diff --git a/docs/mission-control-embedding.md b/docs/mission-control-embedding.md index d1ae654..43bde4c 100644 --- a/docs/mission-control-embedding.md +++ b/docs/mission-control-embedding.md @@ -33,7 +33,7 @@ The panel then hands the frozen record to `perform()` instead of writing the cli ## Snapshot contract -`dashboard/dashboard-data.mjs` prints one JSON snapshot per refresh. Its shape is versioned by `dashboardDataVersion` (currently **1.13.0**) and published as `docs/contracts/mission-control-snapshot.schema.json` (JSON Schema 2020-12): every top-level field is required with its type, and the `runLogs` rows, `gateExit` tickets, `chats` envelopes, `shipLane` rows and the `outcomeLedger` summary are fixed; nested collector shapes stay open so collectors can grow. An added field is a minor bump, a removed or retyped top-level field a major bump. A test runs the real script against a scratch repo and checks the output against the schema of its version. +`dashboard/dashboard-data.mjs` prints one JSON snapshot per refresh. Its shape is versioned by `dashboardDataVersion` (currently **1.15.0**) and published as `docs/contracts/mission-control-snapshot.schema.json` (JSON Schema 2020-12): every top-level field is required with its type, and the `runLogs` rows, `gateExit` tickets, `chats` envelopes, `shipLane` rows and the `outcomeLedger` summary are fixed; nested collector shapes stay open so collectors can grow. An added field is a minor bump, a removed or retyped top-level field a major bump. A test runs the real script against a scratch repo and checks the output against the schema of its version. **Run feed without `~/.cursor`.** `runLogs` (1.5.0) lists the newest headless logs the kit writes itself (`.cursor/loop-logs/tick-*.log` from `agent-kit run-plan`, `run-*.log` from `agent-kit run`): `format` (`stream-json`, `codex` or `acp`), `sessionId`, capped `lastText`, `result`, the `LOOP_TICK_RESULT` line, HITL gate ids and reply stamps. The logs are redacted when written and again when read. The runner keeps these logs (and `loop.stop`) under `AGENT_KIT_STATE_ROOT`: `.cursor` by default, or `.agent-kit` for a host that keeps runner output out of `.cursor/` (the `loop-logs/` directory ignores itself in git either way). Plans, HANDOFF and the other agent contract files stay under `.cursor/`. A host that drives the CLI in driver mode (`docs/driver-events-protocol.md`) gets the same information live; `runLogs` is the at-rest view. @@ -81,7 +81,7 @@ A host that draws its own views reads the snapshot (and the CLI JSON commands be - `audience` (1.1.0) is `user` or `meta`; a `meta` command exists to build or ship the kit itself, and a host hides it outside the factory workspace. - The three 1.1.0 fields come from each command file's frontmatter. They can only narrow what a host runs. A catalog without them (1.0.0) reads as `none`, `false` and `user`. -**Run or copy.** A row the host's allowlist accepts may run through the host's own action path; every other row is a copy record for the agent chat input, as in the [action seam](#action-seam). `/git-prod` and `/kit-prod` are never runnable from a host. An engine that predates `agent-kit commands` exits non-zero on the unknown subcommand, and a host that sees that, output that is not JSON, or a `catalogVersion` major it does not support should ask the user to update the engine rather than fall back to a list of its own. +**Run with context, or copy.** A row the host's allowlist accepts may run through the host's own action path, as an interactive session whose first prompt is `/name` plus the context its `context` field names (a goal typed by the user, a plan file, a branch, a PR number or a SHA); every other row is a copy record for the agent chat input, as in the [action seam](#action-seam). `/git-prod` and `/kit-prod` (`interactiveOnly`) are interactive only: a host may open them in a session the user drives, after its own confirmation, and the routine's production gate inside that session is the yes; never headless, from a driver or run-plan tick, or pre-answered. An engine that predates `agent-kit commands` exits non-zero on the unknown subcommand, and a host that sees that, output that is not JSON, or a `catalogVersion` major it does not support should ask the user to update the engine rather than fall back to a list of its own. ## Content security policy readiness diff --git a/docs/multiple-machines.md b/docs/multiple-machines.md index 89ab381..a4ecf06 100644 --- a/docs/multiple-machines.md +++ b/docs/multiple-machines.md @@ -17,7 +17,7 @@ Committed and pushed files sync like any other code: | Uncommitted plan WIP (modified or new `.cursor/plans/*.plan.md`) | Not committed, so other machines never see it. An idle machine can hold it for weeks. | | `.cursor/HANDOFF.md` | The installer adds it to `.gitignore` as kit-owned state. The active plan and next to-do exist on one machine only. | | Claude Code auto-memory | Lives outside the repo at `~/.claude/projects//memory/`. The directory name is derived from the absolute checkout path, so `-Users-me-Documents-repo` and `-home-me-repo` never meet, even for the same repo. User-level memories are also per machine. | -| Runtime context: `.cursor/dogfood/`, `.cursor/context/readiness.json`, `flight-log.json`, `mission-timing.json`, `outcome-ledger.json`, `test-results.json`, `gate-exit.json`, `review-ledger.json`, `plan-index.json` | Machine-local runtime state; the installer adds these to `.gitignore`, and for `gate-exit.json`, `review-ledger.json` and `plan-index.json` the CLI also adds the path to the clone-local `.git/info/exclude` when `.gitignore` does not list it yet. Run logs (`.cursor/loop-logs/`) are local too: the installer adds that pattern, and the runner also drops a `.gitignore` of `*` inside the directory, so logs never show up as untracked files. Audit waits (`.cursor/context/audit-wait/`) are local too, but the installer does not ignore them, so add them to `.gitignore` yourself or they show up as untracked files. | +| Runtime context: `.cursor/dogfood/`, `.cursor/context/readiness.json`, `flight-log.json`, `mission-timing.json`, `outcome-ledger.json`, `test-results.json`, `gate-exit.json`, `review-ledger.json`, `plan-index.json`, `cost-ledger.ndjson` | Machine-local runtime state; the installer adds these to `.gitignore`, and for `gate-exit.json`, `review-ledger.json`, `plan-index.json` and `cost-ledger.ndjson` the CLI also adds the path to the clone-local `.git/info/exclude` when `.gitignore` does not list it yet. Run logs (`.cursor/loop-logs/`) are local too: the installer adds that pattern, and the runner also drops a `.gitignore` of `*` inside the directory, so logs never show up as untracked files. Audit waits (`.cursor/context/audit-wait/`) are local too, but the installer does not ignore them, so add them to `.gitignore` yourself or they show up as untracked files. | | Checkout freshness | A checkout can be days behind its upstream branch and still look current. | Memories that were synced by hand are often machine-relative ("this Mac", `/Users/...` paths, a host since reinstalled with another OS). Treat them as input to curate, not to copy. diff --git a/gemini-extension.json b/gemini-extension.json index b572fd2..e03015f 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,5 +1,5 @@ { "name": "agent-kit", - "version": "6.23.0", + "version": "6.25.0", "description": "Mission Kit core skills: HITL gates, plan backlog and onboarding, QA, external plan review. The full kit (slash commands, plans, HANDOFF, staging-then-prod git flow) installs with npx @dadado/agent-kit-cli@latest install." } diff --git a/package.json b/package.json index 6b351f3..90d3792 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "agent-kit", - "version": "6.23.0", + "version": "6.25.0", "description": "HITL framework for AI-assisted IDEs: plan, handoff, staging-to-prod, memory loop; Cursor-first with partial generators for VS Code and Windsurf.", "private": true, "license": "Apache-2.0", diff --git a/packages/cli/README.md b/packages/cli/README.md index 51fb95a..c42ee4f 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -75,6 +75,7 @@ On an interactive TTY, long-running commands (`init`, `install`, `doctor`, `upda | `agent-kit doctor` | Diagnose repository readiness (`--json` includes an `env` pillar: bin-on-PATH, npm prefix writability, Node version, shell profile) | | `agent-kit setup-global` | Self-heal a root-owned npm global prefix (relocate to `~/.npm-global`, fix `PATH`, reinstall) | | `agent-kit update` | Re-apply L0/packs/skills from the registry | +| `agent-kit installs` | List the kit installs recorded on this machine (`scan [--root ]...` to find them, `prune` to drop gone ones) | | `agent-kit dashboard` | Start Mission Control for this workspace (browser panel) | | `agent-kit mission-control` | ASCII Mission Control TUI (`--once` for one frame) | | `agent-kit add ` | Install a skill or L1 pack | diff --git a/packages/cli/package.json b/packages/cli/package.json index 849c165..0fd0b98 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@dadado/agent-kit-cli", - "version": "6.23.0", + "version": "6.25.0", "description": "Agent Kit CLI: HITL framework install and tooling for AI-assisted IDEs (rules, skills, plan/handoff, context).", "license": "Apache-2.0", "homepage": "https://agent.missionkit.io/", diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts index 76792da..4f68afd 100644 --- a/packages/cli/src/commands/add.ts +++ b/packages/cli/src/commands/add.ts @@ -5,8 +5,15 @@ import { formatSkippedSymlinks, logApplyStats } from "../lifecycle/report.js"; import { REGISTRY_CLI_ARGS, resolveRegistryFromCli } from "../lifecycle/resolve-cli.js"; import { KIT_VERSION } from "../lifecycle/version.js"; import { loadAgentKitManifest } from "../manifest/index.js"; -import { allPacks, allSkills, findPack, findSkill, loadRegistry } from "../registry/client.js"; +import { + allSkills, + findPack, + findSkill, + loadRegistry, + resolvePackSummary, +} from "../registry/client.js"; import { installPack, installSkill } from "../registry/install.js"; +import { UnknownPackError } from "../registry/pack-aliases.js"; import { logger } from "../utils/logger.js"; export const addCommand = defineCommand({ @@ -55,7 +62,7 @@ export const addCommand = defineCommand({ const protectedGlobs = resolveProtectedGlobs(existing); const index = await loadRegistry(registry.root); const asSkill = allSkills(index).find((s) => s.id === args.id); - const asPack = allPacks(index).find((p) => p.id === args.id); + const asPack = resolvePackSummary(index, args.id); const base = existing ? { ...existing } @@ -98,7 +105,13 @@ export const addCommand = defineCommand({ return; } if (args.pack) { - const pack = await findPack(registry.root, args.id); + const pack = await findPack(registry.root, args.id).catch((err: unknown) => { + if (!(err instanceof UnknownPackError)) throw err; + logger.error(err.message); + process.exitCode = 1; + return null; + }); + if (!pack) return; const stats = await installPack(registry.root, args.cwd, pack.id, { protectedGlobs }); logApplyStats(stats); if (skipped(stats)) return; diff --git a/packages/cli/src/commands/countdown.test.ts b/packages/cli/src/commands/countdown.test.ts index d0b626a..b33d7ba 100644 --- a/packages/cli/src/commands/countdown.test.ts +++ b/packages/cli/src/commands/countdown.test.ts @@ -11,10 +11,15 @@ import { readGateExitMarker, writeGateExitMarker, } from "../plan-loop/gate-exit.js"; +import { StreamRenderer } from "../plan-loop/stream-render.js"; import { + COST_LEDGER_RELPATH, COUNTDOWN_EXIT, + COUNTDOWN_RESULT_PREFIX, countdownChildArgs, countdownExitCode, + countdownOutcome, + createCostWatcher, executeCountdown, type JobHandle, type SpawnJob, @@ -144,6 +149,28 @@ describe("countdownExitCode", () => { expect(countdownExitCode({ code: 0, circuitsDead: "window", pendingGrew: false })).toBe(3); expect(countdownExitCode({ code: 4, circuitsDead: "stall", pendingGrew: false })).toBe(3); }); + + it("an agent stop that needs the operator is 5, never folded into 3; a gate wins over it", () => { + const stop = { needsOperator: true }; + expect(countdownExitCode({ code: 0, circuitsDead: null, pendingGrew: false, ...stop })).toBe( + COUNTDOWN_EXIT.needsOperator, + ); + expect(COUNTDOWN_EXIT.needsOperator).toBe(5); + expect(countdownExitCode({ code: 0, circuitsDead: null, pendingGrew: true, ...stop })).toBe(2); + expect(countdownExitCode({ code: 4, circuitsDead: null, pendingGrew: false, ...stop })).toBe(2); + expect(countdownExitCode({ code: 0, circuitsDead: "stall", pendingGrew: false, ...stop })).toBe( + 3, + ); + expect(countdownExitCode({ code: 1, circuitsDead: null, pendingGrew: false, ...stop })).toBe(3); + }); + + it("outcome: ok for 0, needs-operator for 2 and 5, broken for 1 and 3", () => { + expect(countdownOutcome(0)).toBe("ok"); + expect(countdownOutcome(2)).toBe("needs-operator"); + expect(countdownOutcome(5)).toBe("needs-operator"); + expect(countdownOutcome(3)).toBe("broken"); + expect(countdownOutcome(1)).toBe("broken"); + }); }); describe("countdownChildArgs", () => { @@ -761,3 +788,548 @@ describe("executeCountdown: model roles", () => { expect(calls).toEqual([]); }); }); + +/** Every `AGENT_KIT_RESULT` line in the echoed stdout, parsed. */ +function resultLines(echoed: string[]): Array> { + return echoed + .join("") + .split("\n") + .filter((l) => l.startsWith(`${COUNTDOWN_RESULT_PREFIX} `)) + .map((l) => JSON.parse(l.slice(COUNTDOWN_RESULT_PREFIX.length + 1)) as Record); +} + +/** The last non-empty stdout line. */ +function lastLine(echoed: string[]): string { + return echoed.join("").trimEnd().split("\n").at(-1) ?? ""; +} + +/** Commit an active plan with the given to-do statuses (no HANDOFF: first plan wins). */ +async function withPlan(root: string, todos: Array<[string, string]>): Promise { + const plans = path.join(root, ".cursor", "plans"); + await mkdir(plans, { recursive: true }); + const body = todos + .map(([id, status]) => ` - id: ${id}\n content: do ${id}\n status: ${status}`) + .join("\n"); + await writeFile( + path.join(plans, "poc.plan.md"), + `---\nname: poc\ntodos:\n${body}\n---\n\n# poc\n`, + ); + git(root, "add", ".cursor/plans/poc.plan.md"); + git(root, "commit", "-q", "-m", "plan"); +} + +describe("executeCountdown: agent stop and the AGENT_KIT_RESULT line", () => { + const fire = async ( + root: string, + script: (child: ReturnType) => void, + extra: Partial[0]> = {}, + ) => { + const echoed: string[] = []; + const child = fakeChild(); + const { spawnJob, calls } = spawnReturning(child); + const { land, calls: landed } = recordingLand(); + const run = executeCountdown({ + ...base, + cwd: root, + spawnJob, + land, + write: (t: string) => echoed.push(t), + ...extra, + }); + await vi.waitFor(() => expect(calls.length).toBe(1)); + script(child); + const r = await run; + return { r, echoed, landed }; + }; + + it("an agent stop with to-dos left exits 5 and prints one needs-operator line, last on stdout", async () => { + const root = await repo(); + await withPlan(root, [ + ["a1", "completed"], + ["k1", "in_progress"], + ["k2", "pending"], + ]); + const { r, echoed, landed } = await fire(root, (child) => { + child.emit("Active plan: poc.plan.md\nAgent requested st"); + child.emit("op: LOOP_TICK_RESULT: stop - which database? operator decides\n"); + child.emit("Loop finished after 1 tick(s). Pending now: 2.\n"); + child.exit(0); + }); + expect(r.exitCode).toBe(COUNTDOWN_EXIT.needsOperator); + expect(landed).toEqual([]); + const lines = resultLines(echoed); + expect(lines).toHaveLength(1); + expect(lines[0]).toEqual({ + outcome: "needs-operator", + reason: "agent requested stop: which database? operator decides", + repo: "root", + plan: "poc.plan.md", + todo: "k1", + exit: 5, + cost_usd: null, + }); + expect(r.result).toEqual(lines[0]); + expect(lastLine(echoed).startsWith(`${COUNTDOWN_RESULT_PREFIX} {`)).toBe(true); + const log = await readFile(r.logPath ?? "", "utf8"); + expect(log).toContain("exit 5 (needs operator; the agent requested a stop)"); + expect(log).toContain(`${COUNTDOWN_RESULT_PREFIX} {"outcome":"needs-operator"`); + }); + + it("a quoted sentinel in the agent's own output is not an agent stop", async () => { + const root = await repo(); + await withPlan(root, [["k1", "pending"]]); + const { r, echoed } = await fire(root, (child) => { + child.emit('End with "LOOP_TICK_RESULT: stop - "\n'); + child.emit(" Agent requested stop: LOOP_TICK_RESULT: stop - quoted\n"); + child.exit(0); + }); + expect(r.exitCode).toBe(0); + expect(resultLines(echoed)[0]?.outcome).toBe("ok"); + }); + + it("a stop on an exhausted plan stays 0: no to-do left decides, whatever the reason", async () => { + const root = await repo(); + await withPlan(root, [["k1", "completed"]]); + const { r, echoed } = await fire(root, (child) => { + child.emit("Agent requested stop: LOOP_TICK_RESULT: stop - nothing else to say\n"); + child.exit(0); + }); + expect(r.exitCode).toBe(0); + expect(resultLines(echoed)).toEqual([ + { + outcome: "ok", + reason: "plan exhausted: nothing else to say", + repo: "root", + plan: "poc.plan.md", + todo: null, + exit: 0, + cost_usd: null, + }, + ]); + expect(await readFile(r.logPath ?? "", "utf8")).toContain("exit 0 (completed; plan exhausted)"); + }); + + it("an exhausted-sounding reason with to-dos left is still 5", async () => { + for (const reason of ["no implementable to-dos, operator must decide", "plan exhausted"]) { + const root = await repo(); + await withPlan(root, [["k1", "pending"]]); + const { r } = await fire(root, (child) => { + child.emit(`Agent requested stop: LOOP_TICK_RESULT: stop - ${reason}\n`); + child.exit(0); + }); + expect(r.exitCode).toBe(COUNTDOWN_EXIT.needsOperator); + expect(r.result.reason).toBe(`agent requested stop: ${reason}`); + } + }); + + it("with no readable plan the stop reason decides", async () => { + const exhausted = await repo(); + const a = await fire(exhausted, (child) => { + child.emit("Agent requested stop: LOOP_TICK_RESULT: stop - plan exhausted\n"); + child.exit(0); + }); + expect(a.r.exitCode).toBe(0); + expect(a.r.result).toMatchObject({ outcome: "ok", plan: null }); + + const question = await repo(); + const b = await fire(question, (child) => { + child.emit("Agent requested stop: LOOP_TICK_RESULT: stop - which database?\n"); + child.exit(0); + }); + expect(b.r.exitCode).toBe(COUNTDOWN_EXIT.needsOperator); + expect(b.r.result).toMatchObject({ outcome: "needs-operator", plan: null, todo: null }); + }); + + it("--job dispatch --slash run-plan (the tick alias) maps a stop to 5 too", async () => { + const root = await repo(); + await withPlan(root, [["k1", "pending"]]); + const { r } = await fire( + root, + (child) => { + child.emit("Agent requested stop: LOOP_TICK_RESULT: stop - ask\n"); + child.exit(0); + }, + { job: "dispatch", slash: "run-plan" }, + ); + expect(r.exitCode).toBe(COUNTDOWN_EXIT.needsOperator); + expect(r.result.plan).toBe("poc.plan.md"); + }); + + it("a completed tick without a stop is ok / 0", async () => { + const root = await repo(); + const { r, echoed } = await fire(root, (child) => { + child.emit("tick done\n"); + child.exit(0); + }); + expect(r.exitCode).toBe(0); + expect(resultLines(echoed)).toEqual([ + { + outcome: "ok", + reason: "completed", + repo: "root", + plan: null, + todo: null, + exit: 0, + cost_usd: null, + }, + ]); + }); + + it("a gate (inner exit 4) stays 2 even after an agent stop line: needs-operator", async () => { + const root = await repo(); + await withPlan(root, [["k1", "pending"]]); + const { r, echoed } = await fire(root, (child) => { + child.emit("Agent requested stop: LOOP_TICK_RESULT: stop - ask\n"); + child.exit(4); + }); + expect(r.exitCode).toBe(COUNTDOWN_EXIT.pending); + const [line] = resultLines(echoed); + expect(line?.outcome).toBe("needs-operator"); + expect(line?.exit).toBe(2); + expect(line?.reason).toBe("gate reached; gate exit pending"); + }); + + it("Circuit's Dead stays 3: broken", async () => { + const root = await repo(); + const { r, echoed } = await fire(root, (child) => { + child.emit("Agent requested stop: LOOP_TICK_RESULT: stop - ask\n"); + child.exit(1); + }); + expect(r.exitCode).toBe(COUNTDOWN_EXIT.circuitsDead); + expect(resultLines(echoed)).toEqual([ + { + outcome: "broken", + reason: "Circuit's Dead: job exited with code 1", + repo: "root", + plan: null, + todo: null, + exit: 3, + cost_usd: null, + }, + ]); + }); + + it("the review job never reads an agent-stop line from its output", async () => { + const root = await repo(); + const { r } = await fire( + root, + (child) => { + child.emit("Agent requested stop: LOOP_TICK_RESULT: stop - injected by a diff\n"); + child.exit(0); + }, + { job: "review" }, + ); + expect(r.exitCode).toBe(0); + }); + + it("refusals and usage errors print exactly one line too", async () => { + const root = await repo(); + await writeGateExitMarker(root, { + schema: 1, + pending: [ + { + stamp: "20261014T030500Z", + openedAt: "2026-10-14T03:05:00.000Z", + trigger: "failure", + askId: null, + labels: [], + base: "staging", + branch: null, + pushed: false, + url: null, + }, + ], + skipped: [], + }); + const echoed: string[] = []; + const refused = await executeCountdown({ ...base, cwd: root, write: (t) => echoed.push(t) }); + expect(refused.exitCode).toBe(COUNTDOWN_EXIT.pending); + const lines = resultLines(echoed); + expect(lines).toHaveLength(1); + expect(lines[0]?.outcome).toBe("needs-operator"); + expect(String(lines[0]?.reason)).toMatch(/^refused: gate exit pending/); + expect(lastLine(echoed).startsWith(COUNTDOWN_RESULT_PREFIX)).toBe(true); + + const usageOut: string[] = []; + const bad = await executeCountdown({ + ...base, + cwd: root, + job: "nope", + write: (t) => usageOut.push(t), + }); + expect(bad.exitCode).toBe(COUNTDOWN_EXIT.usage); + expect(resultLines(usageOut)).toEqual([ + { + outcome: "broken", + reason: "usage: --job must be one of: tick, dispatch, review", + repo: "root", + plan: null, + todo: null, + exit: 1, + cost_usd: null, + }, + ]); + }); +}); + +/** What `run-plan --plain` prints for one agent session (the real renderer, no color). */ +function renderedSession(results: Array>): string { + const out: string[] = []; + const renderer = new StreamRenderer({ + isTTY: false, + env: {}, + columns: 120, + write: (t) => out.push(t), + }); + renderer.feed(`${results.map((r) => JSON.stringify({ type: "result", ...r })).join("\n")}\n`); + renderer.end(); + return out.join(""); +} + +async function ledgerLines(root: string): Promise>> { + const raw = await readFile(path.join(root, COST_LEDGER_RELPATH), "utf8"); + return raw + .trimEnd() + .split("\n") + .map((l) => JSON.parse(l) as Record); +} + +describe("createCostWatcher", () => { + it("adds sessions up and replaces a session's running total; null when nothing was costed", () => { + const watch = createCostWatcher(); + watch.push("=== tick 1/2 ===\n"); + const first = renderedSession([ + { subtype: "success", total_cost_usd: 0.8, num_turns: 10 }, + { subtype: "success", total_cost_usd: 1.35, num_turns: 5 }, + ]); + // Split mid-line: chunking never changes the figure. + watch.push(first.slice(0, 7)); + watch.push(first.slice(7)); + watch.push(renderedSession([{ subtype: "success", total_cost_usd: 0.0123 }])); + watch.push(renderedSession([{ subtype: "error_max_turns", is_error: true }])); + expect(watch.costUsd()).toBe(1.3623); + + const none = createCostWatcher(); + none.push(renderedSession([{ subtype: "success", num_turns: 3 }])); + none.push("✦ result success\n ✦ result success · $9.00\n"); + expect(none.costUsd()).toBeNull(); + }); + + it("a session-total line below the previous cost is added, so printed text never lowers the figure", () => { + const watch = createCostWatcher(); + watch.push(renderedSession([{ subtype: "success", total_cost_usd: 5 }])); + watch.push("✦ result x · $0.00 session total\n"); + expect(watch.costUsd()).toBe(5); + const inflated = createCostWatcher(); + inflated.push(renderedSession([{ subtype: "success", total_cost_usd: 5 }])); + inflated.push("✦ result x · $1.00 session total\n"); + expect(inflated.costUsd()).toBe(6); + }); +}); + +describe("executeCountdown: cost ledger and --budget-remaining", () => { + const fire = async ( + root: string, + script: (child: ReturnType) => void, + extra: Partial[0]> = {}, + ) => { + const echoed: string[] = []; + const child = fakeChild(); + const { spawnJob, calls } = spawnReturning(child); + const { land } = recordingLand(); + const run = executeCountdown({ + ...base, + cwd: root, + spawnJob, + land, + write: (t: string) => echoed.push(t), + ...extra, + }); + await vi.waitFor(() => expect(calls.length).toBe(1)); + script(child); + const r = await run; + return { r, echoed }; + }; + + it("sums the sessions' printed cost into cost_usd, the last field of AGENT_KIT_RESULT", async () => { + const root = await repo(); + await withPlan(root, [["k2", "in_progress"]]); + const { r, echoed } = await fire( + root, + (child) => { + child.emit("=== tick 1/2 - pending: 1 ===\n"); + child.emit( + renderedSession([ + { subtype: "success", total_cost_usd: 0.8 }, + { subtype: "success", total_cost_usd: 1.35 }, + ]), + ); + child.emit("=== tick 2/2 - pending: 1 ===\n"); + child.emit(renderedSession([{ subtype: "success", total_cost_usd: 0.5 }])); + child.exit(0); + }, + { maxTicks: "2", model: "sonnet" }, + ); + expect(r.exitCode).toBe(0); + expect(r.result.cost_usd).toBe(1.85); + expect(Object.keys(r.result).at(-1)).toBe("cost_usd"); + expect(lastLine(echoed)).toMatch(/^AGENT_KIT_RESULT \{.*,"cost_usd":1\.85\}$/); + const [entry] = await ledgerLines(root); + expect(Object.keys(entry ?? {})).toEqual([ + "at", + "repo", + "plan", + "todo", + "job", + "backend", + "model", + "cost_usd", + "input_tokens", + "output_tokens", + "exit", + "outcome", + ]); + expect(entry).toEqual({ + at: "2026-10-15T03:00:00.000Z", + repo: "root", + plan: "poc.plan.md", + todo: "k2", + job: "tick", + backend: "claude", + model: "sonnet", + cost_usd: 1.85, + input_tokens: null, + output_tokens: null, + exit: 0, + outcome: "ok", + }); + }); + + it("cost_usd is null when the job printed no cost, and the ledger only appends", async () => { + const root = await repo(); + for (const out of ["tick done\n", renderedSession([{ subtype: "success", num_turns: 2 }])]) { + const { r, echoed } = await fire(root, (child) => { + child.emit(out); + child.exit(0); + }); + expect(r.result.cost_usd).toBeNull(); + expect(lastLine(echoed)).toMatch(/,"cost_usd":null\}$/); + } + const lines = await ledgerLines(root); + expect(lines).toHaveLength(2); + expect(lines.map((l) => [l.cost_usd, l.model, l.exit])).toEqual([ + [null, null, 0], + [null, null, 0], + ]); + // The ledger never dirties the tree (the next fire would refuse it). + expect(git(root, "status", "--porcelain")).toBe(""); + }); + + it("a ledger write failure prints one warning and keeps the exit code", async () => { + const root = await repo(); + await mkdir(path.join(root, COST_LEDGER_RELPATH), { recursive: true }); + const { r, echoed } = await fire(root, (child) => { + child.emit(renderedSession([{ subtype: "success", total_cost_usd: 0.25 }])); + child.exit(0); + }); + expect(r.exitCode).toBe(0); + const out = echoed.join("").trimEnd().split("\n"); + const warnings = out.filter((l) => l.startsWith("countdown: warning: cost ledger not written")); + expect(warnings).toHaveLength(1); + expect(out.at(-2)).toBe(warnings[0]); + expect(lastLine(echoed)).toMatch(/^AGENT_KIT_RESULT .*"exit":0,"cost_usd":0\.25\}$/); + expect(resultLines(echoed)).toHaveLength(1); + }); + + it("--budget-remaining <= 0 refuses with exit 2 before the job starts, and records it", async () => { + for (const budget of ["0", "-0.35"]) { + const root = await repo(); + const echoed: string[] = []; + const spawnJob = vi.fn(); + const r = await executeCountdown({ + ...base, + cwd: root, + spawnJob, + budgetRemaining: budget, + write: (t) => echoed.push(t), + }); + expect(r.exitCode).toBe(COUNTDOWN_EXIT.pending); + expect(spawnJob).not.toHaveBeenCalled(); + const out = echoed.join(""); + expect(out.match(/^countdown: refused: budget: /gm)).toHaveLength(1); + const lines = resultLines(echoed); + expect(lines).toHaveLength(1); + expect(lines[0]?.outcome).toBe("needs-operator"); + expect(String(lines[0]?.reason)).toMatch(/^budget: .*nothing left$/); + expect(lines[0]?.cost_usd).toBeNull(); + expect(lastLine(echoed).startsWith(COUNTDOWN_RESULT_PREFIX)).toBe(true); + const ledger = await ledgerLines(root); + expect(ledger).toHaveLength(1); + expect(ledger[0]).toMatchObject({ exit: 2, outcome: "needs-operator", cost_usd: null }); + } + }); + + it("--budget-remaining below the per-tick cap (times the ticks) refuses; covering it runs", async () => { + const root = await repo(); + const env = { ...GIT_ENV, AGENT_KIT_CLAUDE_MAX_BUDGET_USD: "2" }; + for (const [budget, ticks] of [ + ["1.5", "1"], + ["3", "2"], + ] as const) { + const echoed: string[] = []; + const spawnJob = vi.fn(); + const r = await executeCountdown({ + ...base, + cwd: root, + env, + spawnJob, + maxTicks: ticks, + budgetRemaining: budget, + write: (t) => echoed.push(t), + }); + expect(r.exitCode).toBe(COUNTDOWN_EXIT.pending); + expect(spawnJob).not.toHaveBeenCalled(); + expect(r.result.reason).toMatch( + /^budget: \$\d+\.\d\d remaining is below the cap of this fire/, + ); + expect(resultLines(echoed)).toHaveLength(1); + } + const { r } = await fire( + root, + (child) => { + child.emit(renderedSession([{ subtype: "success", total_cost_usd: 1.2 }])); + child.exit(0); + }, + { env, budgetRemaining: "2" }, + ); + expect(r.exitCode).toBe(0); + expect(r.result.cost_usd).toBe(1.2); + expect((await ledgerLines(root)).map((l) => l.exit)).toEqual([2, 2, 0]); + }); + + it("a --budget-remaining that is not a number is a usage error (exit 1), not recorded", async () => { + const root = await repo(); + for (const budget of ["abc", "5abc", "", " "]) { + const echoed: string[] = []; + const r = await executeCountdown({ + ...base, + cwd: root, + budgetRemaining: budget, + write: (t) => echoed.push(t), + }); + expect(r.exitCode).toBe(COUNTDOWN_EXIT.usage); + expect(resultLines(echoed)).toEqual([ + { + outcome: "broken", + reason: "usage: --budget-remaining must be a number (USD)", + repo: "root", + plan: null, + todo: null, + exit: 1, + cost_usd: null, + }, + ]); + } + await expect(readFile(path.join(root, COST_LEDGER_RELPATH), "utf8")).rejects.toThrow(); + }); +}); diff --git a/packages/cli/src/commands/countdown.ts b/packages/cli/src/commands/countdown.ts index a7ed7be..c53ea3a 100644 --- a/packages/cli/src/commands/countdown.ts +++ b/packages/cli/src/commands/countdown.ts @@ -1,10 +1,12 @@ import { spawn } from "node:child_process"; -import { appendFile } from "node:fs/promises"; +import { appendFile, mkdir } from "node:fs/promises"; import path from "node:path"; import { defineCommand } from "citty"; +import { parsePlanFrontmatter } from "../plan-index/plan-index.js"; import { CLAUDE_MAX_BUDGET_USD_ENV, CLAUDE_MAX_TURNS_ENV, + claudeRunCaps, RedactingStreamBuffer, redactSecrets, } from "../plan-loop/backends.js"; @@ -16,6 +18,7 @@ import { promoteBlockedMessage, unknownSlashMessage, } from "../plan-loop/dispatch.js"; +import { isPlanExhaustedReason } from "../plan-loop/external-review.js"; import { defaultExec, type ExecFn, @@ -37,6 +40,7 @@ import { resolveReviewJobRole, resolveWorkerRole, } from "../plan-loop/model-roles.js"; +import { countPendingTodos, readPlan, resolveActivePlanPath } from "../plan-loop/plan-state.js"; import { parseReviewPackMaxBytes, REVIEW_BACKENDS, @@ -44,6 +48,9 @@ import { REVIEW_PACK_SLASH, reviewBackendMessage, } from "../plan-loop/review-job.js"; +import { parseAgentStopLine } from "../plan-loop/sentinel.js"; +import { parseResultLine } from "../plan-loop/stream-render.js"; +import { ensurePathIgnored } from "../utils/git-local-exclude.js"; import { ensureLoopLogsDir, runnerStatePaths } from "../utils/kit-paths.js"; import { logger } from "../utils/logger.js"; @@ -64,12 +71,219 @@ import { logger } from "../utils/logger.js"; export const COUNTDOWN_EXIT = { completed: 0, usage: 1, - /** A gate exit is pending, or the run reached a gate. */ + /** + * A gate exit is pending, the run reached a gate, or `--budget-remaining` + * does not cover the job: waits for the operator. + */ pending: 2, /** Circuit's Dead: failed, stalled, over the window, dirty tree, fetch failed. */ circuitsDead: 3, + /** + * Needs operator: the tick ended because the agent requested a stop (a + * question, nothing implementable) while to-dos remain. A stop on an + * exhausted plan stays 0. + */ + needsOperator: 5, } as const; +/** Prefix of the one machine-readable line Countdown prints last on stdout. */ +export const COUNTDOWN_RESULT_PREFIX = "AGENT_KIT_RESULT"; + +export type CountdownOutcome = "ok" | "needs-operator" | "broken"; + +/** + * The `AGENT_KIT_RESULT` payload. Field order is the printed order; a later + * field (for example a cost) is appended, never inserted. + */ +export interface CountdownResultRecord { + outcome: CountdownOutcome; + reason: string; + /** Workspace basename. */ + repo: string; + /** Active plan file basename, or null when there is none (or the job is not a tick). */ + plan: string | null; + /** The single in_progress to-do id after the run, or null when not exactly one. */ + todo: string | null; + exit: number; + /** + * What the job's agent sessions reported spending, in USD (as printed by the + * job, so rounded to cents above $0.10), or null when nothing was reported + * (no job ran, or a backend that reports no cost). Never a guess. + */ + cost_usd: number | null; +} + +/** 0 ok; 2 and 5 wait for the operator; 3 and a usage error (1) are broken. */ +export function countdownOutcome(exitCode: number): CountdownOutcome { + if (exitCode === COUNTDOWN_EXIT.completed) return "ok"; + if (exitCode === COUNTDOWN_EXIT.pending || exitCode === COUNTDOWN_EXIT.needsOperator) { + return "needs-operator"; + } + return "broken"; +} + +export function formatCountdownResultLine(record: CountdownResultRecord): string { + return `${COUNTDOWN_RESULT_PREFIX} ${JSON.stringify(record)}`; +} + +/** + * The last agent stop the child `run-plan` printed, read from its whole + * (line-buffered, redacted) output lines. Null when the run had none. + */ +export function createAgentStopWatcher(): { + push(text: string): void; + reason(): string | null; +} { + let last: string | null = null; + let partial = ""; + return { + push(text) { + const lines = (partial + text).split("\n"); + partial = lines.pop() ?? ""; + for (const line of lines) { + const hit = parseAgentStopLine(line); + if (hit !== null) last = hit; + } + }, + reason() { + const hit = partial ? parseAgentStopLine(partial) : null; + return hit ?? last; + }, + }; +} + +/** + * The job's spend, read from the result lines its agent sessions printed + * (`parseResultLine`). Sessions add up (ticks, a post-tick review); within one + * session a `session total` cost replaces the session's previous one, since + * claude reports a running total. A running total never shrinks, so a + * `session total` line below the previous cost is added instead: a line the + * agent prints itself can inflate the figure, never lower it. Null when no + * result line carried a cost. + */ +export function createCostWatcher(): { + push(text: string): void; + costUsd(): number | null; +} { + let total = 0; + let seen = false; + let last: number | null = null; + let partial = ""; + const take = (line: string) => { + const hit = parseResultLine(line); + if (hit === null || hit.costUsd === null) return; + const replaces = hit.sessionTotal && last !== null && hit.costUsd >= last; + total += replaces && last !== null ? hit.costUsd - last : hit.costUsd; + last = hit.costUsd; + seen = true; + }; + return { + push(text) { + const lines = (partial + text).split("\n"); + partial = lines.pop() ?? ""; + for (const line of lines) take(line); + }, + costUsd() { + if (partial) { + take(partial); + partial = ""; + } + return seen ? Math.round(total * 1e6) / 1e6 : null; + }, + }; +} + +/** Gitignored per-fire spend ledger (KIT_OWNED_IGNORE_PATTERNS), append-only NDJSON. */ +export const COST_LEDGER_RELPATH = ".cursor/context/cost-ledger.ndjson"; + +/** One ledger line. Field order is the written order; null where unknown. */ +export interface CostLedgerEntry { + /** ISO 8601 time of the fire. */ + at: string; + repo: string; + plan: string | null; + todo: string | null; + job: string; + backend: string | null; + /** The model Countdown passed to the job, or null for the backend's default. */ + model: string | null; + cost_usd: number | null; + /** Not printed by the job today: always null. */ + input_tokens: number | null; + output_tokens: number | null; + exit: number; + outcome: CountdownOutcome; +} + +export function formatCostLedgerLine(entry: CostLedgerEntry): string { + return `${JSON.stringify(entry)}\n`; +} + +/** + * Append one line to the cost ledger. The ledger must never dirty the tree + * (the next fire would refuse it), so a repository whose ignore rules miss it + * gets a clone-local `.git/info/exclude` line first; when that fails nothing + * is written. Returns null on success, else a one-line reason. Never throws. + */ +export async function appendCostLedger(opts: { + root: string; + env: NodeJS.ProcessEnv; + exec: ExecFn; + entry: CostLedgerEntry; +}): Promise { + try { + const git = (args: readonly string[]) => + opts.exec("git", args, { cwd: opts.root, env: opts.env }); + if (!(await ensurePathIgnored(git, opts.root, COST_LEDGER_RELPATH))) { + return `${COST_LEDGER_RELPATH} is not ignored by git and could not be added to .git/info/exclude`; + } + const file = path.join(opts.root, COST_LEDGER_RELPATH); + await mkdir(path.dirname(file), { recursive: true }); + await appendFile(file, formatCostLedgerLine(opts.entry), "utf8"); + return null; + } catch (err) { + return String(err instanceof Error ? err.message : err); + } +} + +/** + * Parse `--budget-remaining`: null when not given, a number (any sign), or a + * usage message for a value that is not a number (an empty value included: + * a wrapper whose computation came out empty must not run unchecked). + */ +export function parseBudgetRemaining(raw: string | number | undefined): number | null | string { + if (raw === undefined) return null; + const text = String(raw).trim(); + const value = Number(text); + if (!text || !Number.isFinite(value)) return "--budget-remaining must be a number (USD)"; + return value; +} + +function usd(value: number): string { + return `${value < 0 ? "-" : ""}$${Math.abs(value).toFixed(2)}`; +} + +/** + * Why a fire with `remaining` USD left must not start, or null when it may: + * nothing left, or less than the per-tick cap (`AGENT_KIT_CLAUDE_MAX_BUDGET_USD`) + * times the ticks this fire may run. + */ +export function budgetRefusal(input: { + remaining: number; + capUsd: number | undefined; + ticks: number; +}): string | null { + if (input.remaining <= 0) return `budget: ${usd(input.remaining)} remaining; nothing left`; + if (input.capUsd === undefined) return null; + const need = input.capUsd * input.ticks; + if (input.remaining >= need) return null; + const per = + input.ticks === 1 + ? `${CLAUDE_MAX_BUDGET_USD_ENV}=${input.capUsd}` + : `${CLAUDE_MAX_BUDGET_USD_ENV}=${input.capUsd} x ${input.ticks} ticks`; + return `budget: ${usd(input.remaining)} remaining is below the cap of this fire (${usd(need)}, ${per})`; +} + export const COUNTDOWN_JOBS = ["tick", "dispatch", "review"] as const; export type CountdownJob = (typeof COUNTDOWN_JOBS)[number]; @@ -189,16 +403,22 @@ export async function superviseJob( /** * Countdown exit code from the child's end: 0 completed; 2 when the child * stopped at a gate (inner `--no-hitl` exit 4) or left a new gate exit - * pending; 3 (Circuit's Dead) for a window overrun, a stall, a signal or any - * other failure. Countdown never returns 4 itself. + * pending; 5 (needs operator) when a tick that exited 0 ended on an agent + * stop while to-dos remain (`needsOperator`); 3 (Circuit's Dead) for a + * window overrun, a stall, a signal or any other failure. A pending gate + * wins over an agent stop. Countdown never returns 4 itself. */ export function countdownExitCode(input: { code: number | null; circuitsDead: CircuitsDeadCause | null; pendingGrew: boolean; + needsOperator?: boolean; }): number { if (input.circuitsDead) return COUNTDOWN_EXIT.circuitsDead; - if (input.code === 0) return input.pendingGrew ? COUNTDOWN_EXIT.pending : 0; + if (input.code === 0) { + if (input.pendingGrew) return COUNTDOWN_EXIT.pending; + return input.needsOperator ? COUNTDOWN_EXIT.needsOperator : COUNTDOWN_EXIT.completed; + } if (input.code === HITL_UNANSWERED_EXIT_CODE) return COUNTDOWN_EXIT.pending; return COUNTDOWN_EXIT.circuitsDead; } @@ -347,6 +567,8 @@ export interface ExecuteCountdownInput { includeReviewed?: boolean; windowMin: string | number; stallMin: string | number; + /** `--budget-remaining `: refuse (exit 2) when it does not cover the fire. */ + budgetRemaining?: string | number; env?: NodeJS.ProcessEnv; now?: Date; exec?: ExecFn; @@ -364,6 +586,23 @@ export interface ExecuteCountdownResult { exitCode: number; error?: string; logPath?: string; + /** What the `AGENT_KIT_RESULT` line printed. */ + result: CountdownResultRecord; +} + +/** One run's end before the result line is added. */ +interface CountdownEnd { + exitCode: number; + error?: string; + logPath?: string; + reason: string; + plan?: string | null; + todo?: string | null; + /** Validated job and the backend / model it ran with (ledger fields). */ + job?: string; + backend?: string | null; + model?: string | null; + costUsd?: number | null; } function positive(raw: string | number, flag: string, integer: boolean): number | string { @@ -374,17 +613,86 @@ function positive(raw: string | number, flag: string, integer: boolean): number return value; } +/** + * One Countdown fire. Every path, usage errors and refusals included, ends + * with exactly one `AGENT_KIT_RESULT {...}` line, the last one written to + * stdout (and to the run log when there is one). Every fire except a usage + * error first appends one line to the cost ledger; a ledger failure prints + * one warning line and never changes the exit code. + */ export async function executeCountdown( input: ExecuteCountdownInput, ): Promise { + const write = input.write ?? ((text: string) => process.stdout.write(text)); + const root = path.resolve(input.cwd); + const env = input.env ?? process.env; + const now = input.now ?? new Date(); + const end = await runCountdown({ ...input, write, now }); + const red = (text: string) => redactSecrets(text, gateExitRedactions(env)); + const result: CountdownResultRecord = { + outcome: countdownOutcome(end.exitCode), + reason: red(end.reason).replace(/\s+/g, " ").trim(), + repo: path.basename(root), + plan: end.plan ?? null, + todo: end.todo ?? null, + exit: end.exitCode, + cost_usd: end.costUsd ?? null, + }; + if (end.exitCode !== COUNTDOWN_EXIT.usage && end.job) { + const failed = await appendCostLedger({ + root, + env, + exec: input.exec ?? defaultExec, + entry: { + at: now.toISOString(), + repo: result.repo, + plan: result.plan, + todo: result.todo, + job: end.job, + backend: end.backend ?? null, + model: end.model ?? null, + cost_usd: result.cost_usd, + input_tokens: null, + output_tokens: null, + exit: result.exit, + outcome: result.outcome, + }, + }); + if (failed !== null) { + const warning = `${red(`countdown: warning: cost ledger not written: ${failed}`).replace(/\s+/g, " ").trim()}\n`; + write(warning); + if (end.logPath) await appendFile(end.logPath, warning, "utf8").catch(() => undefined); + } + } + const line = `${formatCountdownResultLine(result)}\n`; + write(line); + if (end.logPath) await appendFile(end.logPath, line, "utf8").catch(() => undefined); + return { + exitCode: end.exitCode, + ...(end.error ? { error: end.error } : {}), + ...(end.logPath ? { logPath: end.logPath } : {}), + result, + }; +} + +/** The single in_progress to-do id of a plan, or null when there is not exactly one. */ +function inProgressTodo(raw: string): string | null { + const active = parsePlanFrontmatter(raw).todos.filter((t) => t.status === "in_progress"); + return active.length === 1 ? (active[0]?.id ?? null) : null; +} + +async function runCountdown( + input: ExecuteCountdownInput & { write: (text: string) => void }, +): Promise { const root = path.resolve(input.cwd); const env = input.env ?? process.env; const exec = input.exec ?? defaultExec; const now = input.now ?? new Date(); - const write = input.write ?? ((text: string) => process.stdout.write(text)); - const usage = (error: string): ExecuteCountdownResult => ({ + const write = input.write; + const usage = (error: string): CountdownEnd => ({ exitCode: COUNTDOWN_EXIT.usage, error, + reason: `usage: ${error}`, }); // Promotion is refused before anything else, exactly as `agent-kit run` refuses it. @@ -407,6 +715,8 @@ export async function executeCountdown( const windowMin = positive(input.windowMin, "--window-min", false); const stallMin = positive(input.stallMin, "--stall-min", false); for (const v of [maxTicks, windowMin, stallMin]) if (typeof v === "string") return usage(v); + const budget = parseBudgetRemaining(input.budgetRemaining); + if (typeof budget === "string") return usage(budget); const packRaw = input.maxPackBytes === undefined ? "" : String(input.maxPackBytes).trim(); if (job !== "review" && packRaw) return usage("--max-pack-bytes only applies to --job review"); @@ -509,11 +819,44 @@ export async function executeCountdown( job === "tick" ? "run-plan" : job === "review" ? `run ${REVIEW_PACK_SLASH}` : `run ${slash}`; say(`fire ${gateExitStamp(now)}: job ${job} (${jobLabel}) on ${detected.id}`); for (const note of rolesNotes) say(note); + // A run-plan tick (the tick job, or `--job dispatch --slash run-plan`, + // which aliases it): its plan is resolved before the child can move it. + const runsTick = job === "tick" || (job === "dispatch" && classifySlash(slash) === "run-plan"); + const planPath = runsTick ? await resolveActivePlanPath(root).catch(() => null) : null; + const plan = planPath ? path.basename(planPath) : null; + const ledger = { job, backend: detected.id, model: model ?? null }; + // The budget is checked before the fetch: a refused fire touches nothing. + if (budget !== null) { + const refusal = budgetRefusal({ + remaining: budget, + capUsd: claudeRunCaps(env).caps.maxBudgetUsd, + ticks: job === "review" ? 1 : (maxTicks as number), + }); + if (refusal !== null) { + say(`refused: ${refusal} (exit ${COUNTDOWN_EXIT.pending})`); + await openLog().catch(() => undefined); + return { + exitCode: COUNTDOWN_EXIT.pending, + reason: refusal, + plan, + ...ledger, + costUsd: null, + ...(logPath ? { logPath } : {}), + }; + } + say(`budget: ${usd(budget)} remaining`); + } const preflight = await countdownPreflight({ root, env, exec, now, log: say }); if (!preflight.ok) { say(`refused: ${preflight.reason} (exit ${preflight.exitCode})`); await openLog().catch(() => undefined); - return { exitCode: preflight.exitCode, ...(logPath ? { logPath } : {}) }; + return { + exitCode: preflight.exitCode, + reason: `refused: ${preflight.reason}`, + plan, + ...ledger, + ...(logPath ? { logPath } : {}), + }; } await openLog(); const capLines = [CLAUDE_MAX_TURNS_ENV, CLAUDE_MAX_BUDGET_USD_ENV] @@ -548,8 +891,16 @@ export async function executeCountdown( // Line-buffered redaction: a secret split across two output chunks is // still elided whole (per-chunk redaction would miss it). const jobOut = new RedactingStreamBuffer(redactions); + // Only a `run-plan` tick prints the agent-stop line; other jobs' output + // (the review pack derives from untrusted diff content) is never read for + // it. Cost is read from every job: the spend is real, and injected text can + // only inflate the figure (see createCostWatcher), never lower it. + const stopWatch = runsTick ? createAgentStopWatcher() : null; + const costWatch = createCostWatcher(); const emitJob = (out: string) => { if (!out) return; + stopWatch?.push(out); + costWatch.push(out); write(out); toLog(out); }; @@ -578,19 +929,33 @@ export async function executeCountdown( const after = await readGateExitMarker(root); const pendingAfter = after.kind === "ok" ? after.marker.pending.length : preflight.pendingBefore; const pendingGrew = pendingAfter > preflight.pendingBefore; + + // An agent stop is "needs operator" unless the plan is exhausted. The + // pending count decides when the plan is readable: a reason such as "no + // implementable to-dos" with to-dos left is exactly the operator case. + // Only an unreadable plan falls back on the reason text. + const stopReason = stopWatch?.reason() ?? null; + const planRaw = planPath ? await readPlan(planPath).catch(() => null) : null; + const todosLeft = planRaw === null ? null : countPendingTodos(planRaw); + const todo = planRaw === null ? null : inProgressTodo(planRaw); + const planExhausted = + stopReason !== null && + (todosLeft === null ? isPlanExhaustedReason(stopReason) : todosLeft === 0); const exitCode = countdownExitCode({ code: end.code, circuitsDead: end.circuitsDead, pendingGrew, + needsOperator: stopReason !== null && !planExhausted, }); // The child lands its own gate stops and failures (`--land-on-gate`); a // killed or crashed child that left no entry is landed here, so Circuit's // Dead is never swallowed. + const deadReason = end.circuitsDead + ? `Circuit's Dead: ${end.circuitsDead === "window" ? `window of ${windowMin} min exceeded` : `no stream event for ${stallMin} min`}` + : `Circuit's Dead: job exited with ${end.code === null ? `signal ${end.signal ?? "unknown"}` : `code ${end.code}`}`; if (exitCode === COUNTDOWN_EXIT.circuitsDead && !pendingGrew) { - const reason = end.circuitsDead - ? `Circuit's Dead: ${end.circuitsDead === "window" ? `window of ${windowMin} min exceeded` : `no stream event for ${stallMin} min`}` - : `Circuit's Dead: job exited with ${end.code === null ? `signal ${end.signal ?? "unknown"}` : `code ${end.code}`}`; + const reason = deadReason; const outcome: GateExitOutcome = { trigger: "failure", exitCode, @@ -607,22 +972,42 @@ export async function executeCountdown( } const meaning = exitCode === 0 - ? "completed" + ? stopReason !== null + ? "completed; plan exhausted" + : "completed" : exitCode === COUNTDOWN_EXIT.pending ? job === "review" && end.code === 0 ? "review findings landed; gate exit pending" : "gate reached; gate exit pending" - : "Circuit's Dead"; + : exitCode === COUNTDOWN_EXIT.needsOperator + ? "needs operator; the agent requested a stop" + : "Circuit's Dead"; say(`exit ${exitCode} (${meaning})`); await logChain; - return { exitCode, ...(logPath ? { logPath } : {}) }; + const reason = + exitCode === COUNTDOWN_EXIT.needsOperator + ? `agent requested stop: ${stopReason ?? ""}` + : exitCode === COUNTDOWN_EXIT.circuitsDead + ? deadReason + : exitCode === 0 && stopReason !== null + ? `plan exhausted: ${stopReason}` + : meaning; + return { + exitCode, + reason, + plan, + todo, + ...ledger, + costUsd: costWatch.costUsd(), + ...(logPath ? { logPath } : {}), + }; } export const countdownCommand = defineCommand({ meta: { name: "countdown", description: - "Countdown: one-shot launcher for a cron/systemd timer. Runs one headless job (tick, dispatch or review) with --no-hitl --land-on-gate; refused while a gate exit is pending. Exit 0 done, 2 gate or findings pending, 3 Circuit's Dead. Never git-prod.", + "Countdown: one-shot launcher for a cron/systemd timer. Runs one headless job (tick, dispatch or review) with --no-hitl --land-on-gate; refused while a gate exit is pending or when --budget-remaining does not cover it. Exit 0 done, 2 gate, findings or budget pending, 3 Circuit's Dead, 5 the agent requested a stop (needs operator). Each fire appends one line to .cursor/context/cost-ledger.ndjson; the last stdout line is AGENT_KIT_RESULT {json}. Never git-prod.", }, args: { cwd: { @@ -677,6 +1062,10 @@ export const countdownCommand = defineCommand({ description: `Minutes with no stream event before the job is stopped as Circuit's Dead (default: ${COUNTDOWN_DEFAULT_STALL_MIN})`, default: String(COUNTDOWN_DEFAULT_STALL_MIN), }, + "budget-remaining": { + type: "string", + description: `USD left in your budget (for example computed from .cursor/context/cost-ledger.ndjson). Refuses the fire with exit 2 when it is <= 0, or below ${CLAUDE_MAX_BUDGET_USD_ENV} times the ticks of this fire when that env is set; not a number (or empty) is a usage error`, + }, }, async run({ args }) { const result = await executeCountdown({ @@ -690,6 +1079,9 @@ export const countdownCommand = defineCommand({ ...(args["include-reviewed"] ? { includeReviewed: true } : {}), windowMin: String(args["window-min"]), stallMin: String(args["stall-min"]), + ...(args["budget-remaining"] !== undefined + ? { budgetRemaining: String(args["budget-remaining"]) } + : {}), forwardSignals: true, }); if (result.error) logger.error(result.error); diff --git a/packages/cli/src/commands/diff.ts b/packages/cli/src/commands/diff.ts index 9257bb4..d87a1c5 100644 --- a/packages/cli/src/commands/diff.ts +++ b/packages/cli/src/commands/diff.ts @@ -2,6 +2,8 @@ import { defineCommand } from "citty"; import { diffAgainstRegistry, summarizeDiff } from "../lifecycle/diff.js"; import { REGISTRY_CLI_ARGS, resolveRegistryFromCli } from "../lifecycle/resolve-cli.js"; import { loadAgentKitManifest } from "../manifest/index.js"; +import { canonicalizePackIds } from "../registry/client.js"; +import { formatUnknownPack } from "../registry/pack-aliases.js"; import { logger } from "../utils/logger.js"; export const diffCommand = defineCommand({ @@ -39,6 +41,11 @@ export const diffCommand = defineCommand({ try { logger.info(`Registry: ${registry.root} (${registry.source})`); + const packIds = await canonicalizePackIds(registry.root, manifest.packs); + for (const { from, to } of packIds.rewrites) { + logger.info(`Pack id '${from}' is a legacy id for '${to}'; agent-kit update rewrites it.`); + } + for (const id of packIds.unknown) logger.warn(formatUnknownPack(id, packIds.knownIds)); const entries = await diffAgainstRegistry(registry.root, args.cwd, manifest); const summary = summarizeDiff(entries); diff --git a/packages/cli/src/commands/doctor.test.ts b/packages/cli/src/commands/doctor.test.ts index 84d9b36..6092bd0 100644 --- a/packages/cli/src/commands/doctor.test.ts +++ b/packages/cli/src/commands/doctor.test.ts @@ -2,7 +2,8 @@ import { mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { printDoctorSummary, runDoctor } from "./doctor.js"; +import { listInstalls } from "../installs/index.js"; +import { doctorCommand, printDoctorSummary, printInstallHealth, runDoctor } from "./doctor.js"; import { statusCommand } from "./status.js"; describe("doctor runtime CLI warn", () => { @@ -141,3 +142,103 @@ describe("doctor / status in a workspace parent", () => { expect(parsed).toHaveProperty("manifest"); }); }); + +describe("runDoctor — install health (c2)", () => { + afterEach(() => vi.restoreAllMocks()); + + it("runs the four checks on injected inputs, writes the MC snapshot and prints the mise line", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "agent-kit-doctor-install-")); + const home = await mkdtemp(path.join(os.tmpdir(), "agent-kit-doctor-home-")); + // Home-level install fixture: an old manifest plus hooks under ~/.cursor. + await mkdir(path.join(home, ".cursor"), { recursive: true }); + await writeFile(path.join(home, ".cursor", "agent-kit.json"), '{"version":"3.0.0"}\n'); + await writeFile(path.join(home, ".cursor", "hooks.json"), "{}\n"); + // mise path fixture: the CLI on PATH lives in a versioned node dir. + const miseBin = path.join(home, ".local/share/mise/installs/node/26.8.2/bin"); + await mkdir(miseBin, { recursive: true }); + await writeFile(path.join(miseBin, "agent-kit"), "#!/bin/sh\n", { mode: 0o755 }); + const fetchNpmLatest = vi.fn(async () => ({ + packageName: "@dadado/agent-kit-cli" as const, + version: "99.0.0", + })); + + const result = await runDoctor(root, { + fetchNpmLatest, + installHealth: { + env: { PATH: miseBin }, + platform: "linux", + homeDir: home, + nodeExecPath: path.join(home, ".local/share/mise/installs/node/26.13.1/bin/node"), + }, + }); + expect(fetchNpmLatest).toHaveBeenCalledTimes(1); + const by = Object.fromEntries(result.install.checks.map((c) => [c.id, c])); + expect(by["node-manager"]?.severity).toBe("warning"); + expect(by["home-install"]?.severity).toBe("warning"); + expect(by["home-install"]?.detail).toContain("~/.cursor/agent-kit.json, ~/.cursor/hooks.json"); + expect(result.install.status).toBe("warning"); + + const snapshot = JSON.parse( + await readFile(path.join(root, ".cursor", "context", "install-health.json"), "utf8"), + ) as { version: number; status: string; checks: Array<{ id: string; detail: string }> }; + expect(snapshot.version).toBe(1); + expect(snapshot.status).toBe("warning"); + expect(JSON.stringify(snapshot)).not.toContain(home); + + const lines: string[] = []; + vi.spyOn(console, "log").mockImplementation((line: string) => { + lines.push(line); + }); + printInstallHealth(result.install); + expect(lines).toContain( + ' add: "npm:@dadado/agent-kit-cli" = { version = "latest", allow_low_downloads = true, minimum_release_age = "0s" }', + ); + }); + + it("does not hit npm without a fetcher (default) and reports the check as not run", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "agent-kit-doctor-nofetch-")); + const home = await mkdtemp(path.join(os.tmpdir(), "agent-kit-doctor-home-")); + const fetchSpy = vi.spyOn(globalThis, "fetch"); + const result = await runDoctor(root, { + installHealth: { env: { PATH: "" }, platform: "linux", homeDir: home }, + }); + expect(fetchSpy).not.toHaveBeenCalled(); + const globalCli = result.install.checks.find((c) => c.id === "global-cli"); + expect(globalCli?.severity).toBe("info"); + }); +}); + +describe("doctorCommand install registry feed", () => { + it("records a folder holding a kit manifest and skips one without", async () => { + const previousCi = process.env.CI; + process.env.CI = "1"; // no npm lookup + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + const installed = await mkdtemp(path.join(os.tmpdir(), "ak-doctor-feed-")); + await mkdir(path.join(installed, ".cursor"), { recursive: true }); + await writeFile( + path.join(installed, ".cursor", "agent-kit.json"), + JSON.stringify({ schemaVersion: 1, version: "6.1.0" }), + ); + const bare = await mkdtemp(path.join(os.tmpdir(), "ak-doctor-bare-")); + const run = doctorCommand.run as unknown as (ctx: { + args: Record; + }) => Promise; + for (const cwd of [installed, bare]) { + await run({ + args: { _: [], cwd, json: true, "fix-safe": false, "refresh-profile": false }, + }); + } + const rows = await listInstalls(); + const real = async (p: string) => (await import("node:fs/promises")).realpath(p); + const installedKey = await real(installed); + const bareKey = await real(bare); + expect(rows.find((e) => e.path === installedKey)).toMatchObject({ kitVersion: "6.1.0" }); + expect(rows.some((e) => e.path === bareKey)).toBe(false); + } finally { + log.mockRestore(); + if (previousCi === undefined) delete process.env.CI; + else process.env.CI = previousCi; + } + }, 30_000); +}); diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.ts index f61e0b8..d2ba3bb 100644 --- a/packages/cli/src/commands/doctor.ts +++ b/packages/cli/src/commands/doctor.ts @@ -1,13 +1,31 @@ import path from "node:path"; import { defineCommand } from "citty"; +import { feedInstallsRegistry } from "../installs/index.js"; import { assessHooksHealth, type HooksHealthReport } from "../invariants/hooks-health.js"; -import { warnIfRunningCliBehindNpm } from "../lifecycle/check-updates.js"; +import { + CLI_NPM_PACKAGES, + type CliNpmLatest, + fetchLatestCliNpmVersion, + warnIfRunningCliBehindNpm, +} from "../lifecycle/check-updates.js"; +import { loadContextConfig } from "../lifecycle/context-config.js"; +import { cachedCliNpmLatest } from "../lifecycle/update-notice.js"; import { KIT_VERSION } from "../lifecycle/version.js"; +import { loadAgentKitManifest } from "../manifest/index.js"; import { assessEnvironment, type EnvironmentReport, MIN_NODE_VERSION_LABEL, + readBinVersion, + resolveBinOnPath, } from "../readiness/env-checks.js"; +import { + assessInstallHealth, + type InstallHealthGatherOptions, + type InstallHealthReport, + npmLatestCheckAllowed, + writeInstallHealthSnapshot, +} from "../readiness/install-health.js"; import { createReadinessReport } from "../scanner/readiness.js"; import { executeSafeReadinessFixes, refreshRepositoryProfile } from "../scanner/safe-fixes.js"; import { runScanner } from "../scanner/scan.js"; @@ -27,6 +45,12 @@ export interface DoctorResult { safeChanges: SafeReadinessChange[]; hooks: HooksHealthReport; env: EnvironmentReport; + /** + * Machine install health: global CLI vs npm latest, per-version node + * manager, stale home-level install, stale registry pin. Read-only; also + * written to `.cursor/context/install-health.json` for Mission Control. + */ + install: InstallHealthReport; /** Present only when `--refresh-profile` ran: whether the on-disk profile changed. */ profileRefreshed?: boolean; /** @@ -78,10 +102,85 @@ async function readDeferredEssentials( .map((item) => ({ checkId: item.checkId, reason: item.reason })); } -export async function runDoctor( - cwd: string, - options: { fixSafe?: boolean; refreshProfile?: boolean; generatedAt?: string } = {}, -): Promise { +export interface DoctorOptions { + fixSafe?: boolean; + refreshProfile?: boolean; + generatedAt?: string; + /** + * npm `latest` lookup for the global-CLI check. Absent = not checked (the + * default, so tests and library callers never touch the network); the + * command passes the real fetcher unless CI or `updateCheck.enabled: false`. + */ + fetchNpmLatest?: () => Promise; + /** Test seams for the install checks (env, platform, home, fs readers). */ + installHealth?: Partial< + Pick< + InstallHealthGatherOptions, + | "env" + | "platform" + | "homeDir" + | "nodeExecPath" + | "realpathImpl" + | "readFileImpl" + | "existsImpl" + > + >; +} + +/** Global CLI on PATH under any of its binary names (`agent-kit`, then `missionkit`). */ +async function resolveCliBin( + env: EnvironmentReport, + procEnv: NodeJS.ProcessEnv, + platform: NodeJS.Platform, +): Promise<{ binPath: string | null; binVersion: string | null }> { + // The environment pillar already resolved `agent-kit` against the real PATH. + if (procEnv === process.env && env.binPath) { + return { binPath: env.binPath, binVersion: env.binVersion }; + } + for (const pkg of CLI_NPM_PACKAGES) { + const hit = await resolveBinOnPath(pkg.bin, procEnv, platform).catch(() => null); + if (hit) { + return { binPath: hit, binVersion: await readBinVersion(hit).catch(() => null) }; + } + } + return { binPath: null, binVersion: null }; +} + +async function runInstallHealth( + rootDir: string, + env: EnvironmentReport, + options: DoctorOptions, +): Promise { + const seams = options.installHealth ?? {}; + const procEnv = seams.env ?? process.env; + const platform = seams.platform ?? process.platform; + let latest: CliNpmLatest | null = null; + const checked = options.fetchNpmLatest !== undefined; + if (options.fetchNpmLatest) { + latest = await options.fetchNpmLatest().catch(() => null); + } + const manifest = await loadAgentKitManifest(rootDir).catch(() => null); + const bin = await resolveCliBin(env, procEnv, platform); + return assessInstallHealth({ + cwd: rootDir, + cliVersion: KIT_VERSION, + npm: { checked, latest }, + binPath: bin.binPath, + binVersion: bin.binVersion, + manifest: manifest + ? { + version: manifest.version, + registryUrl: manifest.registry?.url ?? null, + registryRef: manifest.registry?.ref ?? null, + } + : null, + ...seams, + env: procEnv, + platform, + }); +} + +export async function runDoctor(cwd: string, options: DoctorOptions = {}): Promise { const rootDir = path.resolve(cwd); const hooks = await assessHooksHealth(rootDir); const workspaceParent = await detectWorkspaceParent(rootDir); @@ -93,11 +192,14 @@ export async function runDoctor( generatorVersion: KIT_VERSION, generatedAt: options.generatedAt, }); + const env = await assessEnvironment(); return { report, safeChanges: [], hooks, - env: await assessEnvironment(), + env, + // Machine-level checks still run; nothing is written in a parent folder. + install: await runInstallHealth(rootDir, env, options), deferredEssentials: [], workspaceParent, }; @@ -105,6 +207,8 @@ export async function runDoctor( // Environment pillar is read-only diagnostics; --fix-safe never runs env // self-heal (that's the future setup-global command), it just reports. const env = await assessEnvironment(); + const install = await runInstallHealth(rootDir, env, options); + await writeInstallHealthSnapshot(rootDir, install, options.generatedAt).catch(() => undefined); if (options.fixSafe) { const execution = await executeSafeReadinessFixes(rootDir, { generatorVersion: KIT_VERSION, @@ -116,6 +220,7 @@ export async function runDoctor( safeChanges: execution.changes, hooks, env, + install, deferredEssentials: await readDeferredEssentials(rootDir, execution.after), }; } @@ -136,6 +241,7 @@ export async function runDoctor( safeChanges: [], hooks, env, + install, profileRefreshed: refresh.changed, deferredEssentials: await readDeferredEssentials(rootDir, report), }; @@ -152,10 +258,23 @@ export async function runDoctor( safeChanges: [], hooks, env, + install, deferredEssentials: await readDeferredEssentials(rootDir, report), }; } +const INSTALL_SEVERITY_LABEL = { ok: "ok", warning: "WARN", info: "info" } as const; + +export function printInstallHealth(install: InstallHealthReport): void { + console.log("install:"); + for (const item of install.checks) { + console.log(` - ${item.label}: ${INSTALL_SEVERITY_LABEL[item.severity]} (${item.detail})`); + if (item.fix && item.severity !== "ok") { + console.log(` ${item.fixKind === "config-line" ? "add" : "fix"}: ${item.fix}`); + } + } +} + export function printDoctorSummary(result: DoctorResult, rootDir: string): void { if (result.workspaceParent) { for (const line of workspaceParentAdvisoryLines(rootDir, result.workspaceParent, "doctor")) { @@ -215,6 +334,8 @@ export function printDoctorSummary(result: DoctorResult, rootDir: string): void }`, ); + printInstallHealth(result.install); + // Check for ALLOW_MAIN_PUSH environment variable if (process.env.ALLOW_MAIN_PUSH === "1") { console.log("⚠️ WARNING: ALLOW_MAIN_PUSH=1 is set in environment"); @@ -258,14 +379,27 @@ export const doctorCommand = defineCommand({ }, async run({ args }) { if (!args.json) { - await warnIfRunningCliBehindNpm(args.cwd, { warn: (message) => logger.warn(message) }); + // npm latest comes from the machine notice cache (one lookup a day); no + // config.json stamp, so a consumer repo gains no new file. + await warnIfRunningCliBehindNpm(args.cwd, { + warn: (message) => logger.warn(message), + stamp: false, + fetchLatest: async () => (await cachedCliNpmLatest())?.version ?? null, + }); } + const npmAllowed = npmLatestCheckAllowed( + process.env, + await loadContextConfig(path.resolve(args.cwd)).catch(() => null), + ); const run = () => runDoctor(args.cwd, { fixSafe: args["fix-safe"], refreshProfile: args["refresh-profile"], + fetchNpmLatest: npmAllowed ? () => fetchLatestCliNpmVersion() : undefined, }); const result = args.json ? await run() : await withCliProgress("doctor", run); + // Silent and fail-open; adds a row only when this folder holds a kit manifest. + await feedInstallsRegistry(path.resolve(args.cwd)); if (args.json) { console.log(JSON.stringify(result, null, 2)); return; diff --git a/packages/cli/src/commands/handoff.test.ts b/packages/cli/src/commands/handoff.test.ts index 2816551..de8728b 100644 --- a/packages/cli/src/commands/handoff.test.ts +++ b/packages/cli/src/commands/handoff.test.ts @@ -163,7 +163,7 @@ describe("handoff regenerate", () => { const plan = (name: string, status: string) => `---\nname: ${name}\ntodos:\n - id: t1\n content: "Do ${name}"\n status: ${status}\n---\n`; - it("keeps Run queue, Backlog plans and Parked plans verbatim and the HANDOFF-named plan", async () => { + it("keeps Run queue, prior outcomes, Backlog plans and Parked plans verbatim and the HANDOFF-named plan", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "agent-kit-handoff-regen-")); const plansDir = path.join(root, ".cursor", "plans"); await mkdir(plansDir, { recursive: true }); @@ -176,6 +176,8 @@ describe("handoff regenerate", () => { "- **Queue status:** running", "- **Queue outcomes:**", " - mmm.plan.md: completed (shipped v1.2.3)", + "- **Queue outcomes anteriores:**", + " old.plan.md: deferred-operator (gate: merge #1)", "- **Backlog plans:**", " - `aaa.plan.md`", " - `zzz.plan.md` (next)", diff --git a/packages/cli/src/commands/handoff.ts b/packages/cli/src/commands/handoff.ts index c8e6179..9588a14 100644 --- a/packages/cli/src/commands/handoff.ts +++ b/packages/cli/src/commands/handoff.ts @@ -78,6 +78,8 @@ const PRESERVED_FIELDS = [ "Queue cursor", "Queue status", "Queue outcomes", + // Rows displaced by run-plan-all-consolidate.sh --rewrite-queue (HITL evidence). + "Queue outcomes anteriores", "Backlog plans", "Parked plans", ]; diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.ts index 50f01ed..4c175bf 100644 --- a/packages/cli/src/commands/init.test.ts +++ b/packages/cli/src/commands/init.test.ts @@ -7,6 +7,12 @@ import { initCommand } from "./init.js"; const mockConfirmProjectRoot = vi.hoisted(() => vi.fn()); const mockPerformInstall = vi.hoisted(() => vi.fn()); const mockAssessEnvironment = vi.hoisted(() => vi.fn()); +const mockFeedInstalls = vi.hoisted(() => vi.fn(async (_root: string) => undefined)); + +vi.mock("../installs/index.js", async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, feedInstallsRegistry: (root: string) => mockFeedInstalls(root) }; +}); vi.mock("../utils/terminal.js", async (importOriginal) => { const mod = await importOriginal(); @@ -63,6 +69,7 @@ describe("initCommand project-root guard", () => { mockConfirmProjectRoot.mockReset(); mockPerformInstall.mockReset(); mockAssessEnvironment.mockReset(); + mockFeedInstalls.mockClear(); process.exitCode = undefined; }); @@ -78,6 +85,7 @@ describe("initCommand project-root guard", () => { // so a blank no-git folder got L0 written into it with no confirmation. expect(mockPerformInstall).not.toHaveBeenCalled(); expect(process.exitCode).toBe(1); + expect(mockFeedInstalls).not.toHaveBeenCalled(); expect(consoleErrorSpy).toHaveBeenCalled(); } finally { consoleErrorSpy.mockRestore(); @@ -97,6 +105,7 @@ describe("initCommand project-root guard", () => { await runInit("/tmp/confirmed-project"); expect(mockPerformInstall).toHaveBeenCalledWith({ cwd: "/tmp/confirmed-project" }); expect(process.exitCode).toBeUndefined(); + expect(mockFeedInstalls).toHaveBeenCalledWith("/tmp/confirmed-project"); }); it("prints the smart epilogue (not a bare `agent-kit` next step) after a successful install", async () => { diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index cd67e35..300fb75 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -1,5 +1,6 @@ import { intro, outro } from "@clack/prompts"; import { defineCommand } from "citty"; +import { feedInstallsRegistry } from "../installs/index.js"; import { syncPathCliToRuntime } from "../lifecycle/path-cli.js"; import { logApplyStats, SkippedSymlinkError } from "../lifecycle/report.js"; import { KIT_VERSION } from "../lifecycle/version.js"; @@ -75,6 +76,7 @@ export const initCommand = defineCommand({ const result = await withCliProgress("init", () => runInitCompatibility(projectRoot)); const pending = result.readiness.pendingActions.length; logger.success(`L0 and readiness prepared in ${result.projectRoot}`); + await feedInstallsRegistry(result.projectRoot); const nextStep = nextStepAfterInstall(pending); const env = await assessEnvironment(); const sync = await syncPathCliToRuntime({ runtimeVersion: KIT_VERSION, env }); diff --git a/packages/cli/src/commands/install.test.ts b/packages/cli/src/commands/install.test.ts index e610295..b97263f 100644 --- a/packages/cli/src/commands/install.test.ts +++ b/packages/cli/src/commands/install.test.ts @@ -322,6 +322,8 @@ describe("installCommand stale CLI guard", () => { // Refusing must not have written a capped manifest, and the registry lock is released. expect(existsSync(path.join(project, ".cursor", "agent-kit.json"))).toBe(false); expect(unlock).toHaveBeenCalled(); + const { listInstalls } = await import("../installs/index.js"); + expect((await listInstalls()).some((e) => e.path.endsWith(path.basename(project)))).toBe(false); }, 15_000); it("--allow-stale-cli gets past the guard", async () => { @@ -332,5 +334,12 @@ describe("installCommand stale CLI guard", () => { const stderr = await runInstall(project, { "allow-stale-cli": true }); expect(stderr).not.toContain("older than the registry"); + // Success feeds the machine install registry (the vitest setup's scratch file). + const { realpath } = await import("node:fs/promises"); + const { listInstalls } = await import("../installs/index.js"); + const key = await realpath(project); + expect((await listInstalls()).find((e) => e.path === key)).toMatchObject({ + kitVersion: KIT_VERSION, + }); }, 15_000); }); diff --git a/packages/cli/src/commands/install.ts b/packages/cli/src/commands/install.ts index 84eadc3..bf3d5cd 100644 --- a/packages/cli/src/commands/install.ts +++ b/packages/cli/src/commands/install.ts @@ -2,6 +2,7 @@ import path from "node:path"; import { defineCommand } from "citty"; import { bold, cyan, green, options as koloristOptions } from "kolorist"; import { applyPersonalization, readRepositoryProfile } from "../generator/personalization.js"; +import { feedInstallsRegistry } from "../installs/index.js"; import { assessClaudeCommandAdapters } from "../invariants/hooks-health.js"; import { type ApplyStats, buildManifest, mergeStats, saveManifest } from "../lifecycle/apply.js"; import { warnIfRunningCliBehindNpm } from "../lifecycle/check-updates.js"; @@ -20,10 +21,16 @@ import { StaleCliError, } from "../lifecycle/stale-cli.js"; import { installL0, syncFromManifest } from "../lifecycle/sync.js"; +import { cachedCliNpmLatest } from "../lifecycle/update-notice.js"; import { KIT_VERSION, pinnedCliSpec } from "../lifecycle/version.js"; import { DOMAIN_PACK_IDS, loadAgentKitManifest } from "../manifest/index.js"; import { assessEnvironment, type EnvironmentReport } from "../readiness/env-checks.js"; -import { loadRegistry } from "../registry/client.js"; +import { canonicalizePackIds, loadRegistry } from "../registry/client.js"; +import { + formatPackIdRewrite, + legacyPackIdTarget, + UnknownPackError, +} from "../registry/pack-aliases.js"; import { createReadinessReport } from "../scanner/readiness.js"; import { executeSafeReadinessFixes } from "../scanner/safe-fixes.js"; import { runScanner } from "../scanner/scan.js"; @@ -214,10 +221,20 @@ export async function performInstall(options: InstallOptions): Promise 0 ? packs : existing?.packs, + ); + const unknownFlagPack = packs.find((id) => packIds.unknown.includes(id)); + if (unknownFlagPack) throw new UnknownPackError(unknownFlagPack, packIds.knownIds); + const draft = buildManifest({ version: KIT_VERSION, profile: options.profile ?? existing?.profile ?? "default", - packs: packs.length > 0 ? packs : existing?.packs, + packs: packIds.packs, skills: existing?.skills, protected: existing?.protected, personalization: existing?.personalization, @@ -235,6 +252,7 @@ export async function performInstall(options: InstallOptions): Promise 0) throw new SkippedSymlinkError(stats); const manifestPath = await saveManifest(projectRoot, draft); + for (const rewrite of packIds.rewrites) logger.info(formatPackIdRewrite(rewrite)); const readinessExecution = await executeSafeReadinessFixes(projectRoot, { generatorVersion: KIT_VERSION, }); @@ -364,11 +382,20 @@ export const installCommand = defineCommand({ } logger.info(`Installing into: ${projectRoot}`); logger.info(`CLI v${KIT_VERSION}`); - await warnIfRunningCliBehindNpm(projectRoot, { warn: (message) => logger.warn(message) }); + // npm latest comes from the machine notice cache (one lookup a day); no + // config.json stamp, so a consumer repo gains no new file. + await warnIfRunningCliBehindNpm(projectRoot, { + warn: (message) => logger.warn(message), + stamp: false, + fetchLatest: async () => (await cachedCliNpmLatest())?.version ?? null, + }); const packs = parsePackList(args.pack); for (const id of packs) { - if (!DOMAIN_PACK_IDS.includes(id as (typeof DOMAIN_PACK_IDS)[number])) { + if ( + !DOMAIN_PACK_IDS.includes(id as (typeof DOMAIN_PACK_IDS)[number]) && + !legacyPackIdTarget(id) + ) { logger.warn(`Pack '${id}' is not in the known L1 list; will still try registry.`); } } @@ -396,6 +423,7 @@ export const installCommand = defineCommand({ console.log(`\n${result.claudeSessionStartInstructions}\n`); } if (result.claudeAdapterHint) logger.info(result.claudeAdapterHint); + await feedInstallsRegistry(result.projectRoot); } catch (err) { if (err instanceof StaleCliError) { const profile = typeof args.profile === "string" && args.profile ? `${args.profile} ` : ""; @@ -409,6 +437,11 @@ export const installCommand = defineCommand({ process.exitCode = 1; return; } + if (err instanceof UnknownPackError) { + logger.error(err.message); + process.exitCode = 1; + return; + } if (err instanceof SkippedSymlinkError) { logApplyStats(err.stats); logger.error(err.message); diff --git a/packages/cli/src/commands/installs.ts b/packages/cli/src/commands/installs.ts new file mode 100644 index 0000000..7dce9b1 --- /dev/null +++ b/packages/cli/src/commands/installs.ts @@ -0,0 +1,237 @@ +import { homedir } from "node:os"; +import path from "node:path"; +import { defineCommand } from "citty"; +import { + DEFAULT_SCAN_DEPTH, + DEFAULT_SCAN_MAX_DIRS, + type InstallEntry, + InstallsRegistryError, + listInstalls, + pruneMissingInstalls, + recordInstalls, + resolveInstallsFile, + scanForInstalls, +} from "../installs/index.js"; +import { logger } from "../utils/logger.js"; + +/** Every `--root ` / `--root=` value (citty keeps only the last one). */ +export function collectRepeatedFlag(rawArgs: readonly string[], flag: string): string[] { + const values: string[] = []; + const long = `--${flag}`; + for (let i = 0; i < rawArgs.length; i += 1) { + const arg = rawArgs[i] as string; + if (arg === long) { + const value = rawArgs[i + 1]; + if (value !== undefined && !value.startsWith("--")) { + values.push(value); + i += 1; + } + } else if (arg.startsWith(`${long}=`)) { + values.push(arg.slice(long.length + 1)); + } + } + return values.filter((v) => v.trim() !== ""); +} + +function parsePositiveInt(value: unknown, fallback: number, name: string): number { + if (value === undefined || value === "") return fallback; + const n = Number(value); + if (!Number.isInteger(n) || n < 0) { + throw new Error(`--${name} must be a non-negative integer (got ${String(value)})`); + } + return n; +} + +const EMPTY_LIST = + "No installs recorded yet. Run `agent-kit installs scan` or any install, update or doctor."; + +export function renderInstallsTable( + entries: readonly InstallEntry[], + home = homedir(), + empty = EMPTY_LIST, +): string { + if (entries.length === 0) return empty; + const display = (p: string) => + p === home ? "~" : p.startsWith(`${home}${path.sep}`) ? `~${p.slice(home.length)}` : p; + const rows = entries.map((e) => [ + e.kind, + e.kitVersion ?? "?", + display(e.path), + e.remote ?? "(no remote)", + e.lastSeen.slice(0, 10), + ]); + const header = ["KIND", "KIT", "PATH", "REMOTE", "SEEN"]; + const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length))); + const fmt = (r: string[]) => + r + .map((c, i) => (i === r.length - 1 ? c : c.padEnd(widths[i] ?? 0))) + .join(" ") + .trimEnd(); + return [fmt(header), ...rows.map(fmt)].join("\n"); +} + +function reportRegistryError(err: unknown): boolean { + if (err instanceof InstallsRegistryError) { + logger.error(err.message); + process.exitCode = 1; + return true; + } + return false; +} + +async function printInstallsList(json: boolean): Promise { + let entries: InstallEntry[]; + try { + entries = await listInstalls(); + } catch (err) { + if (reportRegistryError(err)) return; + throw err; + } + if (json) { + process.stdout.write( + `${JSON.stringify({ file: resolveInstallsFile(), installs: entries }, null, 2)}\n`, + ); + return; + } + process.stdout.write(`${renderInstallsTable(entries)}\n`); +} + +const listCommand = defineCommand({ + meta: { name: "list", description: "List the installs recorded on this machine (default)" }, + args: { + json: { type: "boolean", description: "Print the rows as JSON", default: false }, + }, + run({ args }) { + return printInstallsList(args.json); + }, +}); + +const scanCommand = defineCommand({ + meta: { + name: "scan", + description: + "Find kit installs (.cursor/agent-kit.json) under bounded roots and record them (default root: $HOME)", + }, + args: { + root: { + type: "string", + description: "Directory to walk; repeat for several roots (default: $HOME)", + }, + depth: { + type: "string", + description: `Maximum directory depth below each root (default ${DEFAULT_SCAN_DEPTH})`, + }, + "max-dirs": { + type: "string", + description: `Stop after visiting this many directories (default ${DEFAULT_SCAN_MAX_DIRS})`, + }, + json: { type: "boolean", description: "Print the result as JSON", default: false }, + }, + async run({ args, rawArgs }) { + const roots = collectRepeatedFlag(rawArgs, "root"); + const scanRoots = roots.length > 0 ? roots.map((r) => path.resolve(r)) : [homedir()]; + let maxDepth: number; + let maxDirs: number; + try { + maxDepth = parsePositiveInt(args.depth, DEFAULT_SCAN_DEPTH, "depth"); + maxDirs = parsePositiveInt(args["max-dirs"], DEFAULT_SCAN_MAX_DIRS, "max-dirs"); + } catch (err) { + logger.error((err as Error).message); + process.exitCode = 2; + return; + } + // The walk runs outside the lock; the upsert re-reads the file under it and + // re-checks each manifest, so a row pruned meanwhile is never resurrected. + const scan = await scanForInstalls(scanRoots, { maxDepth, maxDirs }); + let written: InstallEntry[]; + try { + written = await recordInstalls(scan.found); + } catch (err) { + if (reportRegistryError(err)) return; + throw err; + } + if (args.json) { + process.stdout.write( + `${JSON.stringify( + { + roots: scanRoots, + visited: scan.visited, + truncated: scan.truncated, + recorded: written, + }, + null, + 2, + )}\n`, + ); + return; + } + process.stdout.write( + `${renderInstallsTable(written, homedir(), "No kit installs (.cursor/agent-kit.json) found.")}\n`, + ); + logger.info( + `Scanned ${scan.visited} directories under ${scanRoots.join(", ")} (depth ${maxDepth}); recorded ${written.length} install(s) in ${resolveInstallsFile()}.`, + ); + if (scan.truncated) { + logger.warn( + `Stopped at ${maxDirs} directories; pass --root for a narrower folder or --max-dirs to raise the cap.`, + ); + } + }, +}); + +const pruneCommand = defineCommand({ + meta: { + name: "prune", + description: "Remove recorded installs whose folder or .cursor/agent-kit.json is gone", + }, + args: { + json: { type: "boolean", description: "Print the removed rows as JSON", default: false }, + }, + async run({ args }) { + let removed: InstallEntry[]; + try { + removed = await pruneMissingInstalls(); + } catch (err) { + if (reportRegistryError(err)) return; + throw err; + } + if (args.json) { + process.stdout.write(`${JSON.stringify({ removed }, null, 2)}\n`); + return; + } + if (removed.length === 0) { + logger.info("Nothing to prune: every recorded install still exists."); + return; + } + for (const entry of removed) console.log(`pruned ${entry.path}`); + }, +}); + +const SUBCOMMANDS = new Set(["list", "scan", "prune"]); + +/** + * Machine install registry (`~/.config/agent-kit/installs.json`, ADR 2026-08-02 + * amend 2026-11-26). An index of where the kit is installed; never writes + * inside a repo. + */ +export const installsCommand = defineCommand({ + meta: { + name: "installs", + description: + "List, scan and prune the kit installs recorded on this machine (~/.config/agent-kit/installs.json)", + }, + args: { + json: { type: "boolean", description: "Print the rows as JSON", default: false }, + }, + subCommands: { + list: listCommand, + scan: scanCommand, + prune: pruneCommand, + }, + async run({ args, rawArgs }) { + // citty also invokes the parent's run after a subcommand. + const first = rawArgs.find((a) => !a.startsWith("-")); + if (first && SUBCOMMANDS.has(first)) return; + await printInstallsList(args.json); + }, +}); diff --git a/packages/cli/src/commands/update-all.test.ts b/packages/cli/src/commands/update-all.test.ts new file mode 100644 index 0000000..4280a6b --- /dev/null +++ b/packages/cli/src/commands/update-all.test.ts @@ -0,0 +1,408 @@ +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, realpath, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { KIT_VERSION } from "../lifecycle/version.js"; +import { detectAgentSession, operatorOnlyRefusal } from "../utils/agent-session.js"; +import { updateCommand } from "./update.js"; +import { + forgeCreateArgv, + type GitRunner, + parsePorcelainZ, + parseRemote, + runUpdateAll, + type UpdateAllOptions, +} from "./update-all.js"; + +const KIT_FILE = ".cursor/rules/kit.mdc"; + +// The registry sync is mocked: it writes one kit file, like a real apply would. +const mockSyncFromManifest = vi.hoisted(() => + vi.fn(async (_registryRoot: string, projectRoot: string, _manifest: unknown) => { + const { writeFile: write } = await import("node:fs/promises"); + const { join } = await import("node:path"); + await write(join(projectRoot, ".cursor", "rules", "kit.mdc"), "kit content vNEXT\n", "utf8"); + return { + written: [".cursor/rules/kit.mdc"], + removed: [], + collisions: [], + skippedProtected: [], + missing: [], + unchanged: [], + preservedCustomized: [], + skippedSymlink: [], + }; + }), +); + +vi.mock("../lifecycle/sync.js", () => ({ + syncFromManifest: mockSyncFromManifest, +})); + +function git(cwd: string, ...args: string[]): string { + return execFileSync("git", args, { cwd, encoding: "utf8", env: gitTestEnv() }).trim(); +} + +function gitTestEnv(): NodeJS.ProcessEnv { + const env = { ...process.env }; + for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR"]) + delete env[key]; + return env; +} + +const OPERATOR_TERMINAL = { env: {}, stdinIsTTY: true, stdoutIsTTY: true }; +const BEHIND_VERSION = `${KIT_VERSION.split(".")[0]}.0.0`; + +interface Fleet { + base: string; + bare: string; + kit: string; + installsFile: string; + repos: { current: string; behind: string; dirty: string }; +} + +async function makeRepo(fleet: { base: string; bare: string }, name: string, version: string) { + const bareRepo = path.join(fleet.bare, "acme", `${name}.git`); + await mkdir(bareRepo, { recursive: true }); + git(bareRepo, "init", "--quiet", "--bare", "-b", "staging"); + const repo = path.join(fleet.base, "repos", name); + await mkdir(path.join(repo, ".cursor", "rules"), { recursive: true }); + git(repo, "init", "--quiet", "-b", "staging"); + git(repo, "config", "user.name", "Fixture"); + git(repo, "config", "user.email", "fixture@example.invalid"); + git(repo, "config", "commit.gpgsign", "false"); + // A github.com origin that resolves to the local bare repo: forge detection + // reads the raw URL, every fetch/push goes to the bare repo. + git(repo, "config", `url.${fleet.bare}/.insteadOf`, "https://github.com/"); + git(repo, "remote", "add", "origin", `https://github.com/acme/${name}.git`); + await writeFile( + path.join(repo, ".cursor", "agent-kit.json"), + `${JSON.stringify( + { + schemaVersion: 1, + version, + packs: [], + skills: [], + protected: [], + registry: { url: "https://github.com/agent-kit-startup/agent-kit", ref: "main" }, + installedAt: "2026-11-01T00:00:00.000Z", + }, + null, + 2, + )}\n`, + "utf8", + ); + await writeFile(path.join(repo, KIT_FILE), "kit content old\n", "utf8"); + await writeFile(path.join(repo, "README.md"), `# ${name}\n`, "utf8"); + git(repo, "add", "-A"); + git(repo, "commit", "--quiet", "-m", "init"); + git(repo, "push", "--quiet", "-u", "origin", "staging"); + git(repo, "remote", "set-head", "origin", "staging"); + return realpath(repo); +} + +async function makeFleet(): Promise { + const base = await realpath(await mkdtemp(path.join(tmpdir(), "ak-update-all-"))); + const bare = path.join(base, "bare"); + const fleet = { base, bare }; + const current = await makeRepo(fleet, "current", KIT_VERSION); + const behind = await makeRepo(fleet, "behind", BEHIND_VERSION); + const dirty = await makeRepo(fleet, "dirty", BEHIND_VERSION); + await writeFile(path.join(dirty, KIT_FILE), "operator edit in progress\n", "utf8"); + + const kit = path.join(base, "kit"); + await mkdir(path.join(kit, "registry"), { recursive: true }); + await writeFile(path.join(kit, "registry", "registry.json"), "{}\n", "utf8"); + await mkdir(path.join(kit, "packages", "cli"), { recursive: true }); + await writeFile( + path.join(kit, "packages", "cli", "package.json"), + JSON.stringify({ version: KIT_VERSION }), + "utf8", + ); + + const installsFile = path.join(base, "installs.json"); + const row = (p: string, kitVersion: string) => ({ + path: p, + remote: null, + kitVersion, + cliVersion: KIT_VERSION, + lastSeen: "2026-11-26T00:00:00.000Z", + kind: "repo", + }); + await writeFile( + installsFile, + JSON.stringify({ + schemaVersion: 1, + installs: [ + row(current, KIT_VERSION), + row(behind, BEHIND_VERSION), + row(dirty, BEHIND_VERSION), + ], + }), + "utf8", + ); + return { base, bare, kit, installsFile, repos: { current, behind, dirty } }; +} + +function fleetOptions(fleet: Fleet, extra: Partial = {}): UpdateAllOptions { + return { + terminal: OPERATOR_TERMINAL, + npmLatest: async () => KIT_VERSION, + confirm: vi.fn(async () => true), + forge: vi.fn(async () => "https://github.com/acme/behind/pull/1"), + installsFile: fleet.installsFile, + // Fixture repos live under the temp dir; classify them as plain repos. + inspect: { tmpRoots: [], home: path.join(fleet.base, "home") }, + home: path.join(fleet.base, "home"), + applyOptions: { registry: fleet.kit }, + out: () => undefined, + ...extra, + }; +} + +describe("operator-only refusal", () => { + it("names the agent marker that is set", () => { + expect(detectAgentSession({ CLAUDECODE: "1" })?.key).toBe("CLAUDECODE"); + expect(detectAgentSession({ CURSOR_AGENT: "1" })?.label).toBe("Cursor agent session"); + expect(detectAgentSession({ AGENT_KIT_QUEUE_LEASE_SESSION: "abc" })?.label).toBe( + "Agent Kit plan loop", + ); + expect(detectAgentSession({ CLAUDECODE: "0", CURSOR_AGENT: "" })).toBeNull(); + }); + + it("refuses without a TTY even when no agent env is set", () => { + expect(operatorOnlyRefusal("x", { env: {}, stdinIsTTY: false, stdoutIsTTY: true })).toMatch( + /needs an interactive terminal/, + ); + expect(operatorOnlyRefusal("x", OPERATOR_TERMINAL)).toBeNull(); + }); + + it("refuses inside an agent session before any git or network call", async () => { + const gitSpy = vi.fn(async () => ""); + const npmLatest = vi.fn(async () => KIT_VERSION); + const result = await runUpdateAll({ + terminal: { env: { CLAUDECODE: "1" }, stdinIsTTY: true, stdoutIsTTY: true }, + git: gitSpy, + npmLatest, + out: () => undefined, + }); + expect(result.status).toBe("refused"); + expect(result.reason).toMatch(/operator-only.*Claude Code agent session/); + expect(gitSpy).not.toHaveBeenCalled(); + expect(npmLatest).not.toHaveBeenCalled(); + }); + + describe("through the command", () => { + let originalExitCode: typeof process.exitCode; + beforeEach(() => { + originalExitCode = process.exitCode; + }); + afterEach(() => { + process.exitCode = originalExitCode; + }); + + it("exits 1 under the test runner (no TTY or agent env), --yes does not lift it", async () => { + const errors: string[] = []; + const spy = vi.spyOn(console, "error").mockImplementation((...a) => { + errors.push(a.join(" ")); + }); + const { logger } = await import("../utils/logger.js"); + const errSpy = vi.spyOn(logger, "error").mockImplementation((m: string) => { + errors.push(m); + }); + try { + await ( + updateCommand.run as unknown as (ctx: { args: Record }) => Promise + )({ args: { _: [], all: true, yes: true, "include-worktrees": false, check: false } }); + } finally { + spy.mockRestore(); + errSpy.mockRestore(); + } + expect(process.exitCode).toBe(1); + expect(errors.join("\n")).toMatch(/agent-kit update --all is operator-only/); + }); + }); +}); + +describe("porcelain parsing", () => { + it("keeps the path when the runner trimmed the first entry's leading space", () => { + expect(parsePorcelainZ("M .cursor/a.json\0?? .cursor/new file.md\0M AGENTS.md\0")).toEqual([ + ".cursor/a.json", + ".cursor/new file.md", + "AGENTS.md", + ]); + }); +}); + +describe("remote parsing", () => { + it("reads github, gitlab and scp forms", () => { + expect(parseRemote("https://github.com/acme/app.git")).toMatchObject({ + forge: "github", + repoPath: "acme/app", + }); + expect(parseRemote("git@gitlab.example.com:group/sub/app.git")).toMatchObject({ + forge: "gitlab", + host: "gitlab.example.com", + repoPath: "group/sub/app", + }); + expect(parseRemote("ssh://git@git.internal:2222/team/app")).toMatchObject({ + forge: "none", + repoPath: "team/app", + }); + expect(parseRemote("/srv/git/app.git")).toBeNull(); + }); + + it("builds a glab call with -R host/group/repo and an explicit target branch", () => { + const remote = parseRemote("git@gitlab.example.com:group/app.git"); + const argv = forgeCreateArgv(remote as NonNullable, { + head: "chore/kit-1.2.3", + base: "staging", + title: "t", + body: "b", + }); + expect(argv?.cmd).toBe("glab"); + expect(argv?.args).toEqual( + expect.arrayContaining(["-R", "gitlab.example.com/group/app", "--target-branch", "staging"]), + ); + }); +}); + +describe("update --all over three fixture repos", () => { + it("stops at the preflight when the CLI is behind npm", async () => { + const fleet = await makeFleet(); + const options = fleetOptions(fleet, { npmLatest: async () => "999.0.0" }); + const result = await runUpdateAll(options); + expect(result.status).toBe("preflight-stop"); + expect(result.reason).toMatch(/behind npm latest v999\.0\.0/); + expect(options.confirm).not.toHaveBeenCalled(); + }); + + it("plans once, confirms once, opens one branch + PR for the behind repo and skips the others", async () => { + const fleet = await makeFleet(); + const lines: string[] = []; + const options = fleetOptions(fleet, { out: (l) => lines.push(l) }); + const result = await runUpdateAll(options); + + expect(result.status).toBe("done"); + expect(options.confirm).toHaveBeenCalledTimes(1); + const byPath = new Map(result.results.map((r) => [r.row.path, r])); + expect(byPath.get(fleet.repos.current)?.row.skip).toMatch(/^current/); + expect(byPath.get(fleet.repos.dirty)?.row.skip).toMatch(/dirty kit files \(1\)/); + expect(byPath.get(fleet.repos.behind)?.row.skip).toBeNull(); + expect(byPath.get(fleet.repos.behind)?.outcome).toEqual({ + status: "opened", + branch: `chore/kit-${KIT_VERSION}`, + url: "https://github.com/acme/behind/pull/1", + }); + + // One PR, against the pre-prod branch, for the right repository. + expect(options.forge).toHaveBeenCalledTimes(1); + const [cmd, args] = (options.forge as ReturnType).mock.calls[0] as [ + string, + string[], + ]; + expect(cmd).toBe("gh"); + expect(args).toEqual( + expect.arrayContaining([ + "--repo", + "acme/behind", + "--base", + "staging", + "--head", + `chore/kit-${KIT_VERSION}`, + ]), + ); + + // The branch reached origin with only the kit paths, and the repo is back on staging. + const behind = fleet.repos.behind; + expect(git(behind, "branch", "--show-current")).toBe("staging"); + const bareBehind = path.join(fleet.bare, "acme", "behind.git"); + expect(git(bareBehind, "branch", "--list", `chore/kit-${KIT_VERSION}`)).toContain( + `chore/kit-${KIT_VERSION}`, + ); + const files = git(behind, "show", "--name-only", "--format=", `chore/kit-${KIT_VERSION}`) + .split("\n") + .sort(); + expect(files).toEqual([".cursor/agent-kit.json", KIT_FILE]); + const subject = git(behind, "log", "-1", "--format=%s", `chore/kit-${KIT_VERSION}`); + expect(subject).toBe(`chore(agent-kit): update kit to v${KIT_VERSION}`); + expect(git(behind, "status", "--porcelain")).toBe(""); + + // The other two are untouched: no branch, dirty edit still in place. + expect(git(fleet.repos.dirty, "branch", "--list", "chore/*")).toBe(""); + expect(await readFile(path.join(fleet.repos.dirty, KIT_FILE), "utf8")).toBe( + "operator edit in progress\n", + ); + expect(git(fleet.repos.current, "branch", "--list", "chore/*")).toBe(""); + + // The summary table names the PR link. + expect(lines.join("\n")).toContain("https://github.com/acme/behind/pull/1"); + + // A rerun is idempotent: the existing branch is a skip, no second PR, no confirm. + const again = fleetOptions(fleet); + const rerun = await runUpdateAll(again); + expect(rerun.status).toBe("nothing-to-do"); + const behindRow = rerun.rows.find((r) => r.path === behind); + expect(behindRow?.skip).toMatch(/already exists/); + expect(again.confirm).not.toHaveBeenCalled(); + expect(again.forge).not.toHaveBeenCalled(); + }, 60_000); + + it("keeps going past a repo whose push fails, cleans it up, and retries it on a rerun", async () => { + const fleet = await makeFleet(); + const rejecting = await makeRepo(fleet, "rejecting", BEHIND_VERSION); + const hook = path.join(fleet.bare, "acme", "rejecting.git", "hooks", "pre-receive"); + await writeFile(hook, "#!/bin/sh\necho rejected by fixture >&2\nexit 1\n", { mode: 0o755 }); + // A repo with no remote: branch + commit only, no PR. + const local = await makeRepo(fleet, "local", BEHIND_VERSION); + git(local, "remote", "remove", "origin"); + const body = JSON.parse(await readFile(fleet.installsFile, "utf8")); + for (const p of [rejecting, local]) { + body.installs.push({ + path: p, + remote: null, + kitVersion: BEHIND_VERSION, + cliVersion: KIT_VERSION, + lastSeen: "2026-11-26T00:00:00.000Z", + kind: "repo", + }); + } + await writeFile(fleet.installsFile, JSON.stringify(body), "utf8"); + + const options = fleetOptions(fleet); + const result = await runUpdateAll(options); + const outcome = (p: string) => result.results.find((r) => r.row.path === p)?.outcome; + expect(outcome(rejecting)).toMatchObject({ status: "error" }); + expect((outcome(rejecting) as { note: string }).note).toMatch(/push failed/); + expect(outcome(fleet.repos.behind)).toMatchObject({ status: "opened" }); + expect(outcome(local)).toMatchObject({ + status: "committed", + branch: `chore/kit-${KIT_VERSION}`, + }); + expect(options.forge).toHaveBeenCalledTimes(1); + + // The failed repo is back on staging, clean, with no kit branch left behind. + expect(git(rejecting, "branch", "--show-current")).toBe("staging"); + expect(git(rejecting, "status", "--porcelain")).toBe(""); + expect(git(rejecting, "branch", "--list", "chore/*")).toBe(""); + // The no-remote repo keeps its committed branch and is back on staging. + expect(git(local, "branch", "--show-current")).toBe("staging"); + expect(git(local, "branch", "--list", "chore/*")).toContain(`chore/kit-${KIT_VERSION}`); + + // A rerun retries the failed repo only. + const again = fleetOptions(fleet); + const rerun = await runUpdateAll(again); + expect(rerun.rows.filter((r) => !r.skip).map((r) => r.path)).toEqual([rejecting]); + expect(again.confirm).toHaveBeenCalledTimes(1); + }, 60_000); + + it("changes nothing when the operator declines the batch confirm", async () => { + const fleet = await makeFleet(); + const options = fleetOptions(fleet, { confirm: vi.fn(async () => false) }); + const result = await runUpdateAll(options); + expect(result.status).toBe("declined"); + expect(git(fleet.repos.behind, "branch", "--list", "chore/*")).toBe(""); + expect(options.forge).not.toHaveBeenCalled(); + }, 60_000); +}); diff --git a/packages/cli/src/commands/update-all.ts b/packages/cli/src/commands/update-all.ts new file mode 100644 index 0000000..c73a150 --- /dev/null +++ b/packages/cli/src/commands/update-all.ts @@ -0,0 +1,823 @@ +/** + * `agent-kit update --all`: operator-typed only, one branch and one PR/MR per + * repository (ADR 2026-11-26_update-all-operator-only-branch-mr-per-repo). + * + * Flow: operator-only refusal (no TTY, agent session) -> CLI-vs-npm preflight + * -> one plan table from the machine install registry -> one batch confirm -> + * per repo, sequentially: fast-forward the pre-prod branch, fresh branch + * `chore/kit-X.Y.Z`, update apply (kit files win by being written), commit + * only the kit paths by name, push, open the PR/MR -> summary table. + * + * Never merges, never rebases, never force-pushes, never `git restore` / + * `checkout --theirs`. One repo failing does not stop the others; a rerun is + * idempotent (an existing `chore/kit-X.Y.Z` branch is a skip, not a retry). + */ + +import { execFile } from "node:child_process"; +import { homedir } from "node:os"; +import path from "node:path"; +import { promisify } from "node:util"; +import { confirm, isCancel } from "@clack/prompts"; +import { + type InspectOptions, + type InstallKind, + InstallsRegistryError, + inspectInstall, + listInstalls, +} from "../installs/index.js"; +import { checkRunningCliVsNpmLatest, compareSemver } from "../lifecycle/check-updates.js"; +import { MANAGED_HASHES_REL } from "../lifecycle/overlay.js"; +import { isProtectedPath, resolveProtectedGlobs } from "../lifecycle/protected.js"; +import { KIT_VERSION } from "../lifecycle/version.js"; +import { loadAgentKitManifest } from "../manifest/index.js"; +import { MANIFEST_RELATIVE_PATH } from "../manifest/types.js"; +import { inspectQueueLease } from "../plan-loop/queue-lease.js"; +import { detectProvider } from "../scanner/detect-git.js"; +import { type OperatorTerminalProbe, operatorOnlyRefusal } from "../utils/agent-session.js"; +import { logger } from "../utils/logger.js"; +import { type ApplyUpdateOptions, type ApplyUpdateResult, applyUpdateAtRoot } from "./update.js"; + +const execFileAsync = promisify(execFile); + +/** Top-level paths the kit writes (L0 targets, packs, skills, adapters); dirt is looked for here. */ +export const KIT_PATHSPECS = [ + ".cursor", + ".claude", + "autogit", + "git-hooks", + "AGENTS.md", + "CLAUDE.md", +] as const; + +export const UPDATE_ALL_COMMAND = "agent-kit update --all"; + +export type ForgeKind = "github" | "gitlab" | "none"; + +export interface RemoteInfo { + /** Raw `remote.origin.url` (never printed: may carry credentials). */ + url: string; + host: string; + /** `group/sub/repo`, without `.git`. */ + repoPath: string; + forge: ForgeKind; +} + +/** Parse `https://host/group/repo(.git)`, `ssh://git@host:22/group/repo`, `git@host:group/repo`. */ +export function parseRemote(url: string): RemoteInfo | null { + const trimmed = url.trim(); + if (!trimmed) return null; + let host: string; + let repoPath: string; + const scp = /^[^/@\s]+@([^:/\s]+):(.+)$/.exec(trimmed); + if (scp && !trimmed.includes("://")) { + host = scp[1] as string; + repoPath = scp[2] as string; + } else { + try { + const parsed = new URL(trimmed); + if (!parsed.hostname) return null; + host = parsed.hostname; + repoPath = parsed.pathname; + } catch { + return null; + } + } + repoPath = repoPath + .replace(/^\/+/, "") + .replace(/\/+$/, "") + .replace(/\.git$/, ""); + if (!repoPath.includes("/")) return null; + const lower = host.toLowerCase(); + const forge: ForgeKind = + lower === "github.com" ? "github" : lower.includes("gitlab") ? "gitlab" : "none"; + return { url: trimmed, host, repoPath, forge }; +} + +/** Argv of the PR/MR create call, or null when the forge is not one we drive. */ +export function forgeCreateArgv( + remote: RemoteInfo, + opts: { head: string; base: string; title: string; body: string }, +): { cmd: string; args: string[] } | null { + if (remote.forge === "github") { + return { + cmd: "gh", + args: [ + "pr", + "create", + "--repo", + remote.repoPath, + "--base", + opts.base, + "--head", + opts.head, + "--title", + opts.title, + "--body", + opts.body, + ], + }; + } + if (remote.forge === "gitlab") { + return { + cmd: "glab", + args: [ + "mr", + "create", + "-R", + `${remote.host}/${remote.repoPath}`, + "--source-branch", + opts.head, + "--target-branch", + opts.base, + "--title", + opts.title, + "--description", + opts.body, + "--yes", + ], + }; + } + return null; +} + +export type GitRunner = (args: readonly string[], cwd: string) => Promise; +export type ForgeRunner = (cmd: string, args: readonly string[], cwd: string) => Promise; + +/** Child env for git: never inherit a caller's repo override. */ +function cleanGitEnv(): NodeJS.ProcessEnv { + const env = { ...process.env }; + for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE"]) { + delete env[key]; + } + return env; +} + +function execError(err: unknown): Error { + const e = err as { stderr?: string; message?: string }; + const detail = (e.stderr ?? "").trim().split("\n").filter(Boolean).pop(); + return new Error(detail || e.message || String(err)); +} + +export const defaultGit: GitRunner = async (args, cwd) => { + try { + const { stdout } = await execFileAsync("git", [...args], { + cwd, + env: cleanGitEnv(), + encoding: "utf8", + maxBuffer: 16 * 1024 * 1024, + timeout: 120_000, + }); + return stdout.trim(); + } catch (err) { + throw execError(err); + } +}; + +export const defaultForge: ForgeRunner = async (cmd, args, cwd) => { + try { + const { stdout } = await execFileAsync(cmd, [...args], { + cwd, + encoding: "utf8", + timeout: 120_000, + }); + return stdout.trim(); + } catch (err) { + throw execError(err); + } +}; + +async function gitOk(git: GitRunner, args: readonly string[], cwd: string): Promise { + try { + return await git(args, cwd); + } catch { + return null; + } +} + +export interface PlanRow { + path: string; + kind: InstallKind | "missing"; + currentVersion: string | null; + targetVersion: string; + /** Pre-prod branch: `staging` when it exists, else the default branch. */ + preProd: string | null; + /** Commits the local pre-prod branch is behind origin (null when unknown or absent). */ + behind: number | null; + /** Modified or untracked non-protected paths under the kit pathspecs. */ + dirtyKitFiles: string[]; + /** Queue-lease holder line, or null when free/stale/own. */ + leaseHolder: string | null; + remote: RemoteInfo | null; + /** Local pre-prod branch exists (fast-forwarded before branching). */ + hasLocalPreProd: boolean; + /** Null when the row is updated; else why it is skipped. */ + skip: string | null; + /** Only meaningful for `skip === null`. */ + branch: string; +} + +export interface PlanOptions { + targetVersion?: string; + includeWorktrees?: boolean; + inspect?: InspectOptions; + git?: GitRunner; + /** Network reads (fetch, ls-remote). Off only in unit tests of the classifier. */ + fetch?: boolean; +} + +function kitBranchName(version: string): string { + return `chore/kit-${version}`; +} + +function majorOf(version: string): number | null { + const m = /^(\d+)\./.exec(version.trim()); + return m ? Number(m[1]) : null; +} + +/** + * NUL-separated `git status --porcelain -z` paths (renames disabled). The + * runner trims its output, which eats the leading space of a ` M path` first + * entry, so the status column is matched instead of sliced. + */ +export function parsePorcelainZ(out: string): string[] { + return out + .split("\0") + .filter(Boolean) + .map((entry) => /^[ MTADRCU?!]{1,2} (.+)$/s.exec(entry)?.[1] ?? entry); +} + +async function kitStatusPaths(git: GitRunner, root: string): Promise { + const out = await git( + [ + "status", + "--porcelain", + "-z", + "--no-renames", + "--untracked-files=all", + "--", + ...KIT_PATHSPECS, + ], + root, + ); + return parsePorcelainZ(out); +} + +async function resolvePreProd( + git: GitRunner, + root: string, + hasRemote: boolean, +): Promise<{ preProd: string | null; hasLocal: boolean }> { + const localStaging = await gitOk( + git, + ["rev-parse", "--verify", "--quiet", "refs/heads/staging"], + root, + ); + if (hasRemote) { + const remoteStaging = await gitOk( + git, + ["rev-parse", "--verify", "--quiet", "refs/remotes/origin/staging"], + root, + ); + let preProd: string | null = remoteStaging ? "staging" : null; + if (!preProd) { + const head = await gitOk(git, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], root); + preProd = head ? head.replace(/^origin\//, "") : null; + } + if (!preProd) { + for (const candidate of ["main", "master"]) { + if ( + await gitOk( + git, + ["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${candidate}`], + root, + ) + ) { + preProd = candidate; + break; + } + } + } + if (!preProd) return { preProd: null, hasLocal: false }; + const local = await gitOk( + git, + ["rev-parse", "--verify", "--quiet", `refs/heads/${preProd}`], + root, + ); + return { preProd, hasLocal: Boolean(local) }; + } + if (localStaging) return { preProd: "staging", hasLocal: true }; + for (const candidate of ["main", "master"]) { + if (await gitOk(git, ["rev-parse", "--verify", "--quiet", `refs/heads/${candidate}`], root)) { + return { preProd: candidate, hasLocal: true }; + } + } + return { preProd: null, hasLocal: false }; +} + +/** Build one plan row. Read-only apart from `git fetch` of the pre-prod branch. */ +export async function planRow(installPath: string, options: PlanOptions = {}): Promise { + const git = options.git ?? defaultGit; + const target = options.targetVersion ?? KIT_VERSION; + const branch = kitBranchName(target); + const row: PlanRow = { + path: installPath, + kind: "missing", + currentVersion: null, + targetVersion: target, + preProd: null, + behind: null, + dirtyKitFiles: [], + leaseHolder: null, + remote: null, + hasLocalPreProd: false, + skip: null, + branch, + }; + const record = await inspectInstall(installPath, options.inspect); + if (!record) { + row.skip = "no kit manifest any more (run agent-kit installs prune)"; + return row; + } + row.kind = record.kind; + row.currentVersion = record.kitVersion; + const kindSkip: Partial> = { + home: "home-level install (run agent-kit update in ~ by hand)", + fixture: "fixture (not its own repository)", + factory: "factory (the kit's own repository)", + }; + if (kindSkip[record.kind]) { + row.skip = kindSkip[record.kind] as string; + return row; + } + if (record.kind === "worktree" && !options.includeWorktrees) { + row.skip = "worktree (--include-worktrees to update it)"; + return row; + } + if (!record.kitVersion) { + row.skip = "manifest has no version (run agent-kit update in it by hand)"; + return row; + } + let cmp: number; + try { + cmp = compareSemver(record.kitVersion, target); + } catch { + row.skip = `unreadable version ${record.kitVersion} (run agent-kit update in it by hand)`; + return row; + } + if (cmp === 0) { + row.skip = `current (v${target})`; + return row; + } + if (cmp > 0) { + row.skip = `ahead of this CLI (v${record.kitVersion})`; + return row; + } + const fromMajor = majorOf(record.kitVersion); + const toMajor = majorOf(target); + if (fromMajor !== null && toMajor !== null && fromMajor < toMajor) { + row.skip = `major jump v${record.kitVersion} → v${target} (run a single-repo agent-kit update)`; + return row; + } + + const inside = await gitOk(git, ["rev-parse", "--is-inside-work-tree"], installPath); + if (inside !== "true") { + row.skip = "not a git repository"; + return row; + } + + const lease = inspectQueueLease(installPath); + if (lease.kind === "held") { + row.leaseHolder = `session ${lease.lease.session} (pid ${lease.lease.dispatcher.pid})`; + } + + const rawUrl = await gitOk(git, ["config", "--get", "remote.origin.url"], installPath); + row.remote = rawUrl ? parseRemote(rawUrl) : null; + if (rawUrl && !row.remote) { + row.skip = "origin URL not understood (update this repo by hand)"; + return row; + } + if (row.remote && row.remote.forge === "none") { + // Self-hosted GitLab under another hostname: same rule as the scanner + // (repository profile `git.provider`, else `.gitlab-ci.yml`). + const detected = await detectProvider(installPath, row.remote.url); + if (detected.provider === "gitlab") row.remote = { ...row.remote, forge: "gitlab" }; + else if (detected.provider === "github") row.remote = { ...row.remote, forge: "github" }; + } + + if (row.remote && options.fetch !== false) { + // Probe the pre-prod branch names on origin, then fetch the one we use. + await gitOk(git, ["fetch", "--quiet", "origin"], installPath); + } + const pre = await resolvePreProd(git, installPath, Boolean(row.remote)); + row.preProd = pre.preProd; + row.hasLocalPreProd = pre.hasLocal; + if (!row.preProd) { + row.skip = "no pre-prod branch found (staging, main or master)"; + return row; + } + + if (row.remote && row.hasLocalPreProd) { + const counts = await gitOk( + git, + [ + "rev-list", + "--left-right", + "--count", + `refs/heads/${row.preProd}...refs/remotes/origin/${row.preProd}`, + ], + installPath, + ); + const [ahead, behind] = (counts ?? "").split(/\s+/).map(Number); + if (Number.isFinite(behind)) row.behind = behind as number; + if (Number.isFinite(ahead) && (ahead as number) > 0) { + row.skip = `diverged (local ${row.preProd} has ${ahead} commit(s) not on origin)`; + return row; + } + } + + const manifest = await loadAgentKitManifest(installPath); + const protectedGlobs = resolveProtectedGlobs(manifest); + row.dirtyKitFiles = (await kitStatusPaths(git, installPath)).filter( + (p) => !isProtectedPath(p, protectedGlobs), + ); + + if (row.leaseHolder) { + row.skip = `live writer holds the queue lease (${row.leaseHolder})`; + return row; + } + if (row.dirtyKitFiles.length > 0) { + row.skip = `dirty kit files (${row.dirtyKitFiles.length}): commit or stash them first`; + return row; + } + const localBranch = await gitOk( + git, + ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`], + installPath, + ); + const remoteBranch = row.remote + ? await gitOk( + git, + ["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`], + installPath, + ) + : null; + if (localBranch || remoteBranch) { + row.skip = `branch ${branch} already exists (merge or close its PR/MR, then delete it)`; + return row; + } + return row; +} + +function displayPath(p: string, home: string): string { + return p === home ? "~" : p.startsWith(`${home}${path.sep}`) ? `~${p.slice(home.length)}` : p; +} + +function renderTable(header: string[], rows: string[][]): string { + const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length))); + const fmt = (r: string[]) => + r + .map((c, i) => (i === r.length - 1 ? c : c.padEnd(widths[i] ?? 0))) + .join(" ") + .trimEnd(); + return [fmt(header), ...rows.map(fmt)].join("\n"); +} + +export function renderPlanTable(rows: readonly PlanRow[], home = homedir()): string { + return renderTable( + ["REPO", "KIT", "PRE-PROD", "DIRTY", "LEASE", "ACTION"], + rows.map((r) => [ + displayPath(r.path, home), + `${r.currentVersion ?? "?"} → ${r.targetVersion}`, + r.preProd ? `${r.preProd}${r.behind ? ` (behind ${r.behind})` : ""}` : "-", + String(r.dirtyKitFiles.length), + r.leaseHolder ? "held" : "free", + r.skip ? `skip: ${r.skip}` : `update on ${r.branch}`, + ]), + ); +} + +export type RowOutcome = + | { status: "opened"; branch: string; url: string } + | { status: "pushed"; branch: string; note: string } + | { status: "committed"; branch: string; note: string } + | { status: "current"; note: string } + | { status: "skipped"; note: string } + | { status: "error"; note: string }; + +export interface ExecuteOptions { + git?: GitRunner; + forge?: ForgeRunner; + apply?: (root: string) => Promise; +} + +async function currentRef( + git: GitRunner, + root: string, +): Promise<{ branch: string | null; sha: string }> { + const branch = (await gitOk(git, ["branch", "--show-current"], root)) || null; + const sha = await git(["rev-parse", "HEAD"], root); + return { branch, sha }; +} + +async function switchBack( + git: GitRunner, + root: string, + start: { branch: string | null; sha: string }, +) { + if (start.branch) await git(["switch", start.branch], root); + else await git(["switch", "--detach", start.sha], root); +} + +/** Whole-tree status paths (untracked included), for before/after comparison. */ +async function treeStatusPaths(git: GitRunner, root: string): Promise { + return parsePorcelainZ( + await git(["status", "--porcelain", "-z", "--no-renames", "--untracked-files=all"], root), + ); +} + +/** + * Update one planned repository. It returns to the starting branch and drops + * the local kit branch whenever the tree holds nothing of its own, so an + * existing `chore/kit-X.Y.Z` always means "reached origin" (or a no-remote + * commit) and a rerun retries every other failure. It stays on the kit branch + * only when its own writes are left uncommitted, so nothing is carried onto + * the operator's branch and nothing is restored or discarded. + */ +export async function executeRow(row: PlanRow, options: ExecuteOptions = {}): Promise { + if (row.skip) return { status: "skipped", note: row.skip }; + const git = options.git ?? defaultGit; + const forge = options.forge ?? defaultForge; + const apply = options.apply ?? ((root: string) => applyUpdateAtRoot(root, {})); + const root = row.path; + const preProd = row.preProd as string; + const branch = row.branch; + let start: { branch: string | null; sha: string }; + let before: Set; + try { + start = await currentRef(git, root); + before = new Set(await treeStatusPaths(git, root)); + } catch (err) { + return { status: "error", note: `cannot read the repository state: ${(err as Error).message}` }; + } + const newDirt = async () => (await treeStatusPaths(git, root)).filter((p) => !before.has(p)); + + let onKitBranch = false; + /** Leave the kit branch: back to the start, local branch dropped unless kept. */ + const leave = async (keepBranch: boolean) => { + await switchBack(git, root, start); + onKitBranch = false; + if (!keepBranch) await gitOk(git, ["branch", "-D", branch], root); + }; + + try { + let base = preProd; + if (row.remote) { + await git(["fetch", "--quiet", "origin", preProd], root); + if (row.hasLocalPreProd) { + await git(["switch", preProd], root); + try { + await git(["merge", "--ff-only", `refs/remotes/origin/${preProd}`], root); + } catch (err) { + await switchBack(git, root, start); + return { + status: "error", + note: `${preProd} cannot fast-forward from origin (diverged): ${(err as Error).message}`, + }; + } + } else { + base = `refs/remotes/origin/${preProd}`; + } + } + await git(["switch", "--no-track", "-c", branch, base], root); + onKitBranch = true; + + const result = await apply(root); + if (result.status !== "applied") { + const reason = + result.status === "no-manifest" ? "no kit manifest on the pre-prod branch" : result.reason; + const leftover = await newDirt(); + if (leftover.length === 0) { + await leave(false); + return { status: "error", note: `update refused: ${reason}` }; + } + return { + status: "error", + note: `update failed: ${reason}; left on ${branch} with ${leftover.length} uncommitted path(s) to inspect`, + }; + } + + const candidates = new Set([ + ...result.stats.written, + ...result.stats.removed, + MANIFEST_RELATIVE_PATH, + MANAGED_HASHES_REL, + ]); + const changed = (await newDirt()).filter((p) => candidates.has(p)); + if (changed.length === 0) { + const stray = await newDirt(); + if (stray.length > 0) { + return { + status: "error", + note: `the apply changed ${stray.length} path(s) it did not report; left on ${branch} to inspect`, + }; + } + await leave(false); + return { status: "current", note: `${preProd} already carries v${result.toVersion}` }; + } + + const message = `chore(agent-kit): update kit to v${result.toVersion}`; + await git(["add", "--", ...changed], root); + await git(["commit", "--quiet", "--only", "-m", message, "--", ...changed], root); + const stray = await newDirt(); + if (stray.length > 0) { + return { + status: "error", + note: `committed on ${branch}, but ${stray.length} other new path(s) appeared (${stray.slice(0, 3).join(", ")}); left on ${branch}, not pushed`, + }; + } + + if (!row.remote) { + await leave(true); + return { status: "committed", branch, note: "no remote: branch + commit only" }; + } + + try { + await git(["push", "--quiet", "-u", "origin", branch], root); + } catch (err) { + await leave(false); + return { status: "error", note: `push failed: ${(err as Error).message}` }; + } + await leave(true); + + const body = [ + `Agent Kit v${result.fromVersion} → v${result.toVersion}, opened by \`${UPDATE_ALL_COMMAND}\`.`, + "", + `Only kit-managed paths are committed (${changed.length} file(s)); L3 protected paths are untouched.`, + "Review and merge it yourself; nothing was merged.", + ].join("\n"); + const argv = forgeCreateArgv(row.remote, { head: branch, base: preProd, title: message, body }); + if (!argv) { + return { + status: "pushed", + branch, + note: `pushed; open the PR/MR on ${row.remote.host} by hand`, + }; + } + try { + const out = await forge(argv.cmd, argv.args, root); + const url = + out + .split("\n") + .find((l) => /^https?:\/\//.test(l.trim())) + ?.trim() ?? out.trim(); + return { status: "opened", branch, url }; + } catch (err) { + return { + status: "pushed", + branch, + note: `pushed, but ${argv.cmd} failed: ${(err as Error).message}; open the PR/MR by hand`, + }; + } + } catch (err) { + const message = (err as Error).message; + if (!onKitBranch) { + await switchBack(git, root, start).catch(() => undefined); + return { status: "error", note: message }; + } + const leftover = await newDirt().catch(() => ["(status unreadable)"]); + if (leftover.length === 0) { + await leave(false).catch(() => undefined); + return { status: "error", note: message }; + } + return { status: "error", note: `${message} (left on ${branch} with uncommitted changes)` }; + } +} + +export function renderSummaryTable( + results: readonly { row: PlanRow; outcome: RowOutcome }[], + home = homedir(), +): string { + return renderTable( + ["REPO", "RESULT", "DETAIL"], + results.map(({ row, outcome }) => [ + displayPath(row.path, home), + outcome.status, + outcome.status === "opened" ? outcome.url : outcome.note, + ]), + ); +} + +export interface UpdateAllOptions extends ExecuteOptions { + includeWorktrees?: boolean; + /** Registry flags forwarded to each apply (`--registry`, `--url`, `--ref`, `--refresh`). */ + applyOptions?: ApplyUpdateOptions; + /** TTY and env probe for the operator-only refusal. */ + terminal?: OperatorTerminalProbe; + /** npm latest for the preflight (tests); fetched when undefined. */ + npmLatest?: () => Promise; + confirm?: (message: string) => Promise; + targetVersion?: string; + inspect?: InspectOptions; + installsFile?: string; + home?: string; + out?: (line: string) => void; +} + +export interface UpdateAllResult { + status: "refused" | "preflight-stop" | "nothing-to-do" | "declined" | "done"; + reason?: string; + rows: PlanRow[]; + results: { row: PlanRow; outcome: RowOutcome }[]; +} + +async function defaultConfirm(message: string): Promise { + const ok = await confirm({ message, initialValue: false }); + return !isCancel(ok) && ok === true; +} + +/** The whole `update --all` run. Returns the outcome; the command maps it to an exit code. */ +export async function runUpdateAll(options: UpdateAllOptions = {}): Promise { + const out = options.out ?? ((line: string) => console.log(line)); + const home = options.home ?? homedir(); + const empty = { rows: [], results: [] }; + + // 1. Operator-only: checked before any registry read, network or git call. + const refusal = operatorOnlyRefusal(UPDATE_ALL_COMMAND, options.terminal); + if (refusal) { + logger.error(refusal); + return { status: "refused", reason: refusal, ...empty }; + } + + // 2. Preflight: the apply stamps this CLI's version, so a CLI behind npm + // would stamp an old version across the fleet. Prefs and env opt-outs do + // not lift this stop: it is a safety check, not a notice. + const cli = await checkRunningCliVsNpmLatest(process.cwd(), { + respectPrefs: false, + fetchLatest: options.npmLatest, + }); + if (cli.status !== "up-to-date") { + const reason = + cli.status === "behind" + ? `${cli.message} Update the CLI first, then run ${UPDATE_ALL_COMMAND} again.` + : cli.status === "ahead" + ? `${cli.message} ${UPDATE_ALL_COMMAND} only stamps released versions; install the npm release first.` + : `Cannot confirm this CLI matches npm latest (${cli.message}); ${UPDATE_ALL_COMMAND} stops rather than guess.`; + logger.error(reason); + return { status: "preflight-stop", reason, ...empty }; + } + + // 3. Plan table from the machine install registry. + let entries: Awaited>; + try { + entries = await listInstalls(options.installsFile ? { file: options.installsFile } : {}); + } catch (err) { + const reason = err instanceof InstallsRegistryError ? err.message : String(err); + logger.error(reason); + return { status: "preflight-stop", reason, ...empty }; + } + if (entries.length === 0) { + const reason = "No installs recorded. Run `agent-kit installs scan` first."; + logger.warn(reason); + return { status: "nothing-to-do", reason, ...empty }; + } + const rows: PlanRow[] = []; + for (const entry of entries) { + rows.push( + await planRow(entry.path, { + targetVersion: options.targetVersion, + includeWorktrees: options.includeWorktrees, + inspect: options.inspect, + git: options.git, + }), + ); + } + out(renderPlanTable(rows, home)); + const todo = rows.filter((r) => !r.skip); + if (todo.length === 0) { + out("Nothing to update."); + return { status: "nothing-to-do", rows, results: [] }; + } + + // 4. One batch confirm (never lifted by --yes). + const ask = options.confirm ?? defaultConfirm; + const ok = await ask( + `Update ${todo.length} repositor${todo.length === 1 ? "y" : "ies"}: one branch ${todo[0]?.branch} and one PR/MR each (nothing is merged)?`, + ); + if (!ok) { + out("Cancelled; nothing was changed."); + return { status: "declined", rows, results: [] }; + } + + // 5. Sequential per repo; one failure does not stop the others. + const apply = + options.apply ?? ((root: string) => applyUpdateAtRoot(root, { ...options.applyOptions })); + const results: { row: PlanRow; outcome: RowOutcome }[] = []; + for (const row of rows) { + if (!row.skip) out(`\n▸ ${displayPath(row.path, home)}`); + const outcome = await executeRow(row, { git: options.git, forge: options.forge, apply }); + results.push({ row, outcome }); + } + out(""); + out(renderSummaryTable(results, home)); + return { status: "done", rows, results }; +} diff --git a/packages/cli/src/commands/update-legacy-pack.test.ts b/packages/cli/src/commands/update-legacy-pack.test.ts new file mode 100644 index 0000000..860de35 --- /dev/null +++ b/packages/cli/src/commands/update-legacy-pack.test.ts @@ -0,0 +1,222 @@ +import { copyFile, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { UnknownPackError } from "../registry/pack-aliases.js"; +import { diffCommand } from "./diff.js"; +import { performInstall } from "./install.js"; +import { updateCommand } from "./update.js"; + +// Real syncFromManifest against the repo's own registry; only the PATH CLI +// sync is stubbed so the test never touches a global npm install. +vi.mock("../lifecycle/path-cli.js", async (importOriginal) => ({ + ...(await importOriginal()), + syncPathCliToRuntime: async () => ({ status: "current", upgraded: false, lines: [] }), +})); + +const here = path.dirname(fileURLToPath(import.meta.url)); +const KIT_ROOT = path.resolve(here, "../../../.."); +const FIXTURE = path.join(here, "../lifecycle/fixtures/agent-kit-manifest-v3.0.0.json"); + +type Run = (ctx: { args: Record }) => Promise; + +async function v3Consumer(extraPacks: string[] = []): Promise { + const root = await mkdtemp(path.join(tmpdir(), "ak-update-legacy-pack-")); + await mkdir(path.join(root, ".cursor"), { recursive: true }); + const target = path.join(root, ".cursor", "agent-kit.json"); + await copyFile(FIXTURE, target); + if (extraPacks.length > 0) { + const manifest = JSON.parse(await readFile(target, "utf8")); + manifest.packs = [...manifest.packs, ...extraPacks]; + await writeFile(target, JSON.stringify(manifest, null, 2), "utf8"); + } + return root; +} + +const updateArgs = (cwd: string) => ({ + _: [], + cwd, + check: false, + json: false, + "respect-prefs": false, + stamp: false, + "seed-overlay": false, + "allow-stale-cli": true, + yes: true, + "force-root": true, + registry: KIT_ROOT, + url: undefined, + ref: undefined, + refresh: false, +}); + +const diffArgs = (cwd: string) => ({ + _: [], + cwd, + all: false, + registry: KIT_ROOT, + url: undefined, + ref: undefined, + refresh: false, +}); + +function captureOutput(): { lines: string[]; restore: () => void } { + const lines: string[] = []; + const push = (...parts: unknown[]) => { + lines.push(parts.map(String).join(" ")); + }; + const log = vi.spyOn(console, "log").mockImplementation(push); + const err = vi.spyOn(console, "error").mockImplementation(push); + return { + lines, + restore: () => { + log.mockRestore(); + err.mockRestore(); + }, + }; +} + +describe("v3.0.0 manifest with legacy pack ids", () => { + const originalExitCode = process.exitCode; + const originalEnv = { HOME: process.env.HOME, XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME }; + + beforeEach(async () => { + const home = await mkdtemp(path.join(tmpdir(), "ak-update-legacy-pack-home-")); + process.env.HOME = home; + process.env.XDG_CONFIG_HOME = path.join(home, ".config"); + }); + + afterEach(() => { + process.exitCode = originalExitCode; + for (const [key, value] of Object.entries(originalEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }); + + it("update rewrites packs to the canonical ids and prints one line per rewrite", async () => { + const consumer = await v3Consumer(); + const out = captureOutput(); + try { + await (updateCommand.run as unknown as Run)({ + args: { + _: [], + cwd: consumer, + check: false, + json: false, + "respect-prefs": false, + stamp: false, + "seed-overlay": false, + "allow-stale-cli": true, + yes: true, + "force-root": true, + registry: KIT_ROOT, + url: undefined, + ref: undefined, + refresh: false, + }, + }); + } finally { + out.restore(); + } + + expect(process.exitCode ?? 0).toBe(0); + const saved = JSON.parse(await readFile(path.join(consumer, ".cursor/agent-kit.json"), "utf8")); + expect(saved.packs).toEqual(["clean-code", "context-management", "project-management"]); + const rewrites = out.lines.filter((l) => l.includes("legacy L1 pack id")); + expect(rewrites).toHaveLength(2); + expect(rewrites[0]).toContain("Pack id 'gestao-contexto' renamed to 'context-management'"); + expect(rewrites[1]).toContain("Pack id 'gestao-projeto' renamed to 'project-management'"); + expect(out.lines.join("\n")).toContain("Update complete"); + }, 60_000); + + it("diff resolves legacy ids instead of throwing and names the rewrite", async () => { + const consumer = await v3Consumer(); + const out = captureOutput(); + try { + await (diffCommand.run as unknown as Run)({ + args: { + _: [], + cwd: consumer, + all: false, + registry: KIT_ROOT, + url: undefined, + ref: undefined, + refresh: false, + }, + }); + } finally { + out.restore(); + } + + const text = out.lines.join("\n"); + expect(text).toContain("Pack id 'gestao-contexto' is a legacy id for 'context-management'"); + expect(text).toContain("Summary:"); + expect(text).not.toContain("pack:gestao"); + }, 60_000); + + it("install --pack with an unknown id fails with the named error before any write", async () => { + const consumer = await v3Consumer(); + const before = await readFile(path.join(consumer, ".cursor/agent-kit.json"), "utf8"); + const out = captureOutput(); + const err = await performInstall({ + cwd: consumer, + pack: "clean-code,ghost-pack", + registry: KIT_ROOT, + allowStaleCli: true, + }) + .catch((e: unknown) => e) + .finally(() => out.restore()); + expect(err).toBeInstanceOf(UnknownPackError); + expect((err as Error).message).toContain("Unknown pack 'ghost-pack'"); + expect(await readFile(path.join(consumer, ".cursor/agent-kit.json"), "utf8")).toBe(before); + }, 60_000); + + it("install on a v3.0.0 manifest rewrites legacy pack ids and prints one line per rewrite", async () => { + const consumer = await v3Consumer(); + const out = captureOutput(); + try { + await performInstall({ cwd: consumer, registry: KIT_ROOT, allowStaleCli: true }); + } finally { + out.restore(); + } + const saved = JSON.parse(await readFile(path.join(consumer, ".cursor/agent-kit.json"), "utf8")); + expect(saved.packs).toEqual(["clean-code", "context-management", "project-management"]); + expect(out.lines.filter((l) => l.includes("legacy L1 pack id"))).toHaveLength(2); + }, 60_000); + + it("update warns once for an unknown pack id, keeps it, and exits 0", async () => { + const consumer = await v3Consumer(["ghost-pack"]); + const out = captureOutput(); + try { + await (updateCommand.run as unknown as Run)({ args: updateArgs(consumer) }); + } finally { + out.restore(); + } + expect(process.exitCode ?? 0).toBe(0); + const warnings = out.lines.filter((l) => l.includes("Unknown pack 'ghost-pack'")); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain("Next:"); + const saved = JSON.parse(await readFile(path.join(consumer, ".cursor/agent-kit.json"), "utf8")); + expect(saved.packs).toEqual([ + "clean-code", + "context-management", + "ghost-pack", + "project-management", + ]); + }, 60_000); + + it("diff names an unknown pack id and lists it as missing-registry", async () => { + const consumer = await v3Consumer(["ghost-pack"]); + const out = captureOutput(); + try { + await (diffCommand.run as unknown as Run)({ args: diffArgs(consumer) }); + } finally { + out.restore(); + } + const text = out.lines.join("\n"); + expect(text).toContain("Unknown pack 'ghost-pack'"); + expect(text).toMatch(/missing-registry\s+pack:ghost-pack/); + }, 60_000); +}); diff --git a/packages/cli/src/commands/update-retired-skills.test.ts b/packages/cli/src/commands/update-retired-skills.test.ts new file mode 100644 index 0000000..70fbe92 --- /dev/null +++ b/packages/cli/src/commands/update-retired-skills.test.ts @@ -0,0 +1,180 @@ +import { mkdir, mkdtemp, readFile, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { contentHash, MANAGED_HASHES_REL } from "../lifecycle/overlay.js"; +import { updateCommand } from "./update.js"; + +// Real syncFromManifest against the repo's own registry; only the PATH CLI +// sync is stubbed so the test never touches a global npm install. +vi.mock("../lifecycle/path-cli.js", async (importOriginal) => ({ + ...(await importOriginal()), + syncPathCliToRuntime: async () => ({ status: "current", upgraded: false, lines: [] }), +})); + +const here = path.dirname(fileURLToPath(import.meta.url)); +const KIT_ROOT = path.resolve(here, "../../../.."); + +type Run = (ctx: { args: Record }) => Promise; + +const GROOVY_SKILL = ".cursor/skills/community/cursor-skills-groovy/SKILL.md"; +const GROOVY_RULE = ".cursor/rules/cursor-skills-groovy.mdc"; +const NODE_SKILL = ".cursor/skills/community/cursor-skills-node/SKILL.md"; +const GENERAL_RULE = ".cursor/rules/cursor-skills-general.mdc"; +const DEVOPS_RULE = ".cursor/rules/cursor-skills-devops.mdc"; + +const OLD_NODE = "synthetic body standing in for the pre-rewrite node skill\n"; +const OLD_GROOVY = "synthetic body standing in for the retired groovy skill\n"; + +async function put(root: string, rel: string, body: string): Promise { + await mkdir(path.dirname(path.join(root, rel)), { recursive: true }); + await writeFile(path.join(root, rel), body, "utf8"); +} + +async function exists(root: string, rel: string): Promise { + try { + await stat(path.join(root, rel)); + return true; + } catch { + return false; + } +} + +/** A consumer installed before the rewrite: old files recorded in the managed-hash ledger. */ +async function consumerBeforeRewrite(groovyBody: string): Promise { + const root = await mkdtemp(path.join(tmpdir(), "ak-update-retired-")); + await put( + root, + ".cursor/agent-kit.json", + JSON.stringify({ + schemaVersion: 1, + version: "6.0.0", + packs: ["devops"], + skills: ["cursor-skills-node", "cursor-skills-groovy"], + protected: [], + }), + ); + await put(root, NODE_SKILL, OLD_NODE); + await put(root, GROOVY_SKILL, groovyBody); + await put(root, GENERAL_RULE, "old general\n"); + await put(root, DEVOPS_RULE, "old devops\n"); + await put( + root, + MANAGED_HASHES_REL, + JSON.stringify({ + schemaVersion: 1, + hashes: { + [NODE_SKILL]: contentHash(OLD_NODE), + [GROOVY_SKILL]: contentHash(OLD_GROOVY), + }, + }), + ); + return root; +} + +function captureOutput(): { lines: string[]; restore: () => void } { + const lines: string[] = []; + const push = (...parts: unknown[]) => { + lines.push(parts.map(String).join(" ")); + }; + const log = vi.spyOn(console, "log").mockImplementation(push); + const err = vi.spyOn(console, "error").mockImplementation(push); + return { + lines, + restore: () => { + log.mockRestore(); + err.mockRestore(); + }, + }; +} + +async function runUpdate(cwd: string): Promise { + const out = captureOutput(); + try { + await (updateCommand.run as unknown as Run)({ + args: { + _: [], + cwd, + check: false, + json: false, + "respect-prefs": false, + stamp: false, + "seed-overlay": false, + "allow-stale-cli": true, + yes: true, + "force-root": true, + registry: KIT_ROOT, + url: undefined, + ref: undefined, + refresh: false, + }, + }); + } finally { + out.restore(); + } + return out.lines.join("\n"); +} + +describe("update after the cursor-skills clean-room rewrite", () => { + const originalExitCode = process.exitCode; + const originalEnv = { HOME: process.env.HOME, XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME }; + + beforeEach(async () => { + const home = await mkdtemp(path.join(tmpdir(), "ak-update-retired-home-")); + process.env.HOME = home; + process.env.XDG_CONFIG_HOME = path.join(home, ".config"); + }); + + afterEach(() => { + process.exitCode = originalExitCode; + for (const [key, value] of Object.entries(originalEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }); + + it("replaces the old files in place, removes unedited groovy and drops it from the manifest", async () => { + const consumer = await consumerBeforeRewrite(OLD_GROOVY); + const text = await runUpdate(consumer); + + expect(process.exitCode ?? 0).toBe(0); + // Same names, new kit-authored content; no second copy under another name. + const nodeNow = await readFile(path.join(consumer, NODE_SKILL), "utf8"); + expect(nodeNow).toBe( + await readFile( + path.join(KIT_ROOT, "registry/skills/community/cursor-skills-node/SKILL.md"), + "utf8", + ), + ); + expect(nodeNow).not.toContain("CURSOR-SKILLS"); + for (const rel of [GENERAL_RULE, DEVOPS_RULE]) { + const body = await readFile(path.join(consumer, rel), "utf8"); + expect(body).toBe(await readFile(path.join(KIT_ROOT, rel), "utf8")); + } + // Groovy: file and directory gone, ledger entry gone, manifest id dropped, one line printed. + expect(await exists(consumer, GROOVY_SKILL)).toBe(false); + expect(await exists(consumer, path.dirname(GROOVY_SKILL))).toBe(false); + expect(await exists(consumer, GROOVY_RULE)).toBe(false); + const ledger = JSON.parse(await readFile(path.join(consumer, MANAGED_HASHES_REL), "utf8")); + expect(ledger.hashes[GROOVY_SKILL]).toBeUndefined(); + const saved = JSON.parse(await readFile(path.join(consumer, ".cursor/agent-kit.json"), "utf8")); + expect(saved.skills).toEqual(["cursor-skills-node"]); + expect(text).toContain("Skill 'cursor-skills-groovy' was retired from the registry"); + expect(text).toContain(`- ${GROOVY_SKILL}`); + expect(text).not.toContain("not found in registry"); + expect(text).toContain("Update complete"); + }, 60_000); + + it("keeps an edited groovy skill and reports it instead of deleting it", async () => { + const edited = "# my own groovy notes\n"; + const consumer = await consumerBeforeRewrite(edited); + const text = await runUpdate(consumer); + + expect(process.exitCode ?? 0).toBe(0); + expect(await readFile(path.join(consumer, GROOVY_SKILL), "utf8")).toBe(edited); + expect(text).toContain(GROOVY_SKILL); + const saved = JSON.parse(await readFile(path.join(consumer, ".cursor/agent-kit.json"), "utf8")); + expect(saved.skills).toEqual(["cursor-skills-node"]); + }, 60_000); +}); diff --git a/packages/cli/src/commands/update.test.ts b/packages/cli/src/commands/update.test.ts index ba6f8a3..8f53ddb 100644 --- a/packages/cli/src/commands/update.test.ts +++ b/packages/cli/src/commands/update.test.ts @@ -1,7 +1,8 @@ -import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, realpath, writeFile } from "node:fs/promises"; import { hostname, tmpdir } from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { listInstalls, resolveInstallsFile } from "../installs/index.js"; import { KIT_VERSION } from "../lifecycle/version.js"; import { procStart, @@ -394,6 +395,24 @@ describe("updateCommand", () => { expect(process.exitCode).not.toBe(1); }, 15_000); + it("records the repo in the machine install registry only after a successful apply", async () => { + const consumer = await makeConsumer(); + const key = await realpath(consumer); + const rowFor = async () => (await listInstalls()).find((e) => e.path === key); + const spy = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + await run(applyArgs(consumer, await makeKit("999.0.0"))); + } finally { + spy.mockRestore(); + } + expect(await rowFor()).toBeUndefined(); + + await run(applyArgs(consumer, await makeKit(null))); + // The vitest setup points the registry at a scratch file, never the real one. + expect(resolveInstallsFile()).toBe(process.env.AGENT_KIT_INSTALLS_FILE); + expect(await rowFor()).toMatchObject({ kitVersion: KIT_VERSION, kind: "fixture" }); + }, 15_000); + it("reports the version transition on success", async () => { const consumer = await makeConsumer(); const kit = await makeKit("1.0.0"); diff --git a/packages/cli/src/commands/update.ts b/packages/cli/src/commands/update.ts index 0d56423..395108c 100644 --- a/packages/cli/src/commands/update.ts +++ b/packages/cli/src/commands/update.ts @@ -10,18 +10,22 @@ import { planClaudeSettingsDrift, writeClaudeSessionStartHook, } from "../generator/claude-session-start-hook.js"; -import { buildManifest, saveManifest } from "../lifecycle/apply.js"; +import { feedInstallsRegistry } from "../installs/index.js"; +import { type ApplyStats, buildManifest, saveManifest } from "../lifecycle/apply.js"; import { checkForUpdates } from "../lifecycle/check-updates.js"; import { seedManagedHashLedger } from "../lifecycle/overlay.js"; import { syncPathCliToRuntime } from "../lifecycle/path-cli.js"; import { isProtectedPath, resolveProtectedGlobs } from "../lifecycle/protected.js"; import { formatSkippedSymlinks, logApplyStats } from "../lifecycle/report.js"; import { REGISTRY_CLI_ARGS, resolveRegistryFromCli } from "../lifecycle/resolve-cli.js"; +import { dropRetiredSkillIds, formatRetiredSkillDrop } from "../lifecycle/retired.js"; import { detectStaleCli, formatRerunFlags, formatStaleCliRefusal } from "../lifecycle/stale-cli.js"; import { syncFromManifest } from "../lifecycle/sync.js"; import { KIT_VERSION } from "../lifecycle/version.js"; import { loadAgentKitManifest } from "../manifest/index.js"; import { formatQueueLeaseRefusal, inspectQueueLease } from "../plan-loop/queue-lease.js"; +import { canonicalizePackIds } from "../registry/client.js"; +import { formatPackIdRewrite } from "../registry/pack-aliases.js"; import { logger } from "../utils/logger.js"; import { confirmProjectRoot, isNonInteractive, RootRefusedError } from "../utils/terminal.js"; import { withCliProgress } from "../welcome/visual-kit.js"; @@ -98,10 +102,46 @@ export const updateCommand = defineCommand({ "Also apply the ledger-aware Claude settings merge (.claude/settings.json + ledger) and generate the .claude/commands/* pointer adapters with install --claude authority; operator opt-in, never from hooks or plan-loop", default: false, }, + all: { + type: "boolean", + description: + "Operator-typed only: update every repo in the machine install registry, one branch chore/kit-X.Y.Z and one PR/MR per repo after one plan table and one confirm; refuses without a TTY or inside an agent session; never merges", + default: false, + }, + "include-worktrees": { + type: "boolean", + description: "With --all: also update linked git worktrees (excluded by default)", + default: false, + }, ...NON_INTERACTIVE_ROOT_ARGS, ...REGISTRY_CLI_ARGS, }, async run({ args }) { + if (args.all) { + if (args.check) { + logger.error( + "--all and --check do not combine; use agent-kit installs list to see versions.", + ); + process.exitCode = 1; + return; + } + // Lazy: update-all imports applyUpdateAtRoot from this module. + const { runUpdateAll } = await import("./update-all.js"); + const result = await runUpdateAll({ + includeWorktrees: args["include-worktrees"], + applyOptions: { + registry: args.registry, + url: args.url, + ref: args.ref, + refresh: args.refresh, + }, + }); + const failed = result.results.some((r) => r.outcome.status === "error"); + if (result.status === "refused" || result.status === "preflight-stop" || failed) { + process.exitCode = 1; + } + return; + } if (args.check) { const result = await checkForUpdates(args.cwd, { respectPrefs: Boolean(args["respect-prefs"]), @@ -145,152 +185,205 @@ export const updateCommand = defineCommand({ throw err; } - const existing = await loadAgentKitManifest(projectRoot, { onWarning: logger.warn }); - if (!existing) { - logger.warn("No .cursor/agent-kit.json — run agent-kit install first."); - return; - } - - // Live-writer check (ADR 2026-07-26 Amend 2026-11-16): another session - // holding the queue lease may be reading or writing L0 right now. Same - // verdict as `agent-kit queue lease`; free, stale and own session proceed. - const lease = inspectQueueLease(projectRoot); - if (lease.kind === "held" && !args.force) { - logger.error( - formatQueueLeaseRefusal(lease, { - what: "another live session writes this workspace, so update will not rewrite L0", - next: "run agent-kit update again (--force applies anyway; operator choice)", - }), - ); - process.exitCode = 1; - return; - } - - const registry = await resolveRegistryFromCli({ - cwd: projectRoot, + const result = await applyUpdateAtRoot(projectRoot, { registry: args.registry, url: args.url, ref: args.ref, refresh: args.refresh, - manifest: existing, + force: args.force, + allowStaleCli: args["allow-stale-cli"], + seedOverlay: args["seed-overlay"], + claude: args.claude, + rerun: formatRerunFlags(args, UPDATE_RERUN_FLAGS), + syncPathCli: true, }); - try { - logger.info(`Registry: ${registry.root} (${registry.source})`); + if (result.status === "refused" || result.status === "failed") process.exitCode = 1; + }, +}); - // The manifest version below is this binary's KIT_VERSION, so an apply - // can never deliver a version newer than the CLI running it. Refuse - // rather than write a capped manifest and report success -- that is the - // shape that makes an operator re-run `update` expecting a bump. The - // guard is deliberately not lifted by --yes: non-interactive and hook - // paths are exactly where a silent capped write does the most damage. - const stale = await detectStaleCli(registry.root, { warn: logger.warn }); - if (stale && !args["allow-stale-cli"]) { - const refusal = formatStaleCliRefusal({ - command: "update", - stale, - rerun: formatRerunFlags(args, UPDATE_RERUN_FLAGS), - }); - logger.error(refusal.error); - console.error(refusal.recovery); - process.exitCode = 1; - return; - } +export interface ApplyUpdateOptions { + registry?: string; + url?: string; + ref?: string; + refresh?: boolean; + /** Apply even while another live writer holds the queue lease (operator choice). */ + force?: boolean; + allowStaleCli?: boolean; + seedOverlay?: boolean; + claude?: boolean; + /** Flags repeated in a stale-CLI refusal's re-run line. */ + rerun?: string; + /** Sync the PATH CLI to this runtime after the apply (single-repo update only). */ + syncPathCli?: boolean; +} + +export type ApplyUpdateResult = + | { status: "applied"; fromVersion: string; toVersion: string; stats: ApplyStats } + | { status: "no-manifest" } + /** Lease held or stale CLI: nothing was written. */ + | { status: "refused"; reason: string } + /** Partial apply (symlink outside the project): the manifest was not stamped. */ + | { status: "failed"; reason: string }; - const next = buildManifest({ - version: KIT_VERSION, - profile: existing.profile, - packs: existing.packs, - skills: existing.skills, - protected: existing.protected, - // Restamp generatorVersion with the CLI that ran this apply so the two - // version fields in the manifest stop disagreeing after an update. The - // personalization result file itself is not regenerated here. - personalization: existing.personalization - ? { ...existing.personalization, generatorVersion: KIT_VERSION } - : undefined, - registryUrl: registry.url ?? existing.registry?.url, - registryRef: registry.ref ?? existing.registry?.ref, +/** + * The update apply for one confirmed absolute project root. Logs the same + * lines as `agent-kit update` and returns the outcome instead of setting + * `process.exitCode`, so `update --all` can run it per repository. It never + * prompts and never confirms the root: callers do that first. + */ +export async function applyUpdateAtRoot( + projectRoot: string, + options: ApplyUpdateOptions = {}, +): Promise { + const existing = await loadAgentKitManifest(projectRoot, { onWarning: logger.warn }); + if (!existing) { + logger.warn("No .cursor/agent-kit.json — run agent-kit install first."); + return { status: "no-manifest" }; + } + + // Live-writer check (ADR 2026-07-26 Amend 2026-11-16): another session + // holding the queue lease may be reading or writing L0 right now. Same + // verdict as `agent-kit queue lease`; free, stale and own session proceed. + const lease = inspectQueueLease(projectRoot); + if (lease.kind === "held" && !options.force) { + const reason = formatQueueLeaseRefusal(lease, { + what: "another live session writes this workspace, so update will not rewrite L0", + next: "run agent-kit update again (--force applies anyway; operator choice)", + }); + logger.error(reason); + return { status: "refused", reason }; + } + + const registry = await resolveRegistryFromCli({ + cwd: projectRoot, + registry: options.registry, + url: options.url, + ref: options.ref, + refresh: options.refresh, + manifest: existing, + }); + try { + logger.info(`Registry: ${registry.root} (${registry.source})`); + + // The manifest version below is this binary's KIT_VERSION, so an apply + // can never deliver a version newer than the CLI running it. Refuse + // rather than write a capped manifest and report success -- that is the + // shape that makes an operator re-run `update` expecting a bump. The + // guard is deliberately not lifted by --yes: non-interactive and hook + // paths are exactly where a silent capped write does the most damage. + const stale = await detectStaleCli(registry.root, { warn: logger.warn }); + if (stale && !options.allowStaleCli) { + const refusal = formatStaleCliRefusal({ + command: "update", + stale, + rerun: options.rerun ?? "", }); - // Preserve optional metadata from existing manifest - if (existing.overrides?.length) next.overrides = existing.overrides; - if (existing.unknownFields) next.unknownFields = existing.unknownFields; - if (next.version === existing.version && existing.installedAt) { - next.installedAt = existing.installedAt; - } + logger.error(refusal.error); + console.error(refusal.recovery); + return { status: "refused", reason: refusal.error }; + } - if (args["seed-overlay"]) { - await seedManagedHashLedger(projectRoot); - logger.info("Seeded managed-hash ledger from current local overlay files."); - } - const stats = await withCliProgress("update", () => - syncFromManifest(registry.root, projectRoot, next), - ); - if (stats.skippedSymlink.length > 0) { - // Some kit content did not land; stamping the new version would claim - // it did. Keep the manifest as-is and fail loudly. + // Legacy pack ids (ADR 2026-07-19_l1-pack-ids-english) are rewritten to + // the id the registry ships; unknown ids stay and sync warns about them. + const packIds = await canonicalizePackIds(registry.root, existing.packs); + // Skills the registry retired (ADR 2026-11-26 third-party skill license policy). + const retiredSkills = dropRetiredSkillIds(existing.skills); + const next = buildManifest({ + version: KIT_VERSION, + profile: existing.profile, + packs: packIds.packs, + skills: retiredSkills.skills, + protected: existing.protected, + // Restamp generatorVersion with the CLI that ran this apply so the two + // version fields in the manifest stop disagreeing after an update. The + // personalization result file itself is not regenerated here. + personalization: existing.personalization + ? { ...existing.personalization, generatorVersion: KIT_VERSION } + : undefined, + registryUrl: registry.url ?? existing.registry?.url, + registryRef: registry.ref ?? existing.registry?.ref, + }); + // Preserve optional metadata from existing manifest + if (existing.overrides?.length) next.overrides = existing.overrides; + if (existing.unknownFields) next.unknownFields = existing.unknownFields; + if (next.version === existing.version && existing.installedAt) { + next.installedAt = existing.installedAt; + } + + if (options.seedOverlay) { + await seedManagedHashLedger(projectRoot); + logger.info("Seeded managed-hash ledger from current local overlay files."); + } + const stats = await withCliProgress("update", () => + syncFromManifest(registry.root, projectRoot, next), + ); + if (stats.skippedSymlink.length > 0) { + // Some kit content did not land; stamping the new version would claim + // it did. Keep the manifest as-is and fail loudly. + logApplyStats(stats); + const reason = formatSkippedSymlinks(stats.skippedSymlink); + logger.error(reason); + return { status: "failed", reason }; + } + if (options.claude) { + // Scoped opt-in: install --claude authority over settings.json + ledger only. + // manifest.protected is never edited. + const claude = await writeClaudeSessionStartHook(projectRoot, { authorized: true }); + if (claude.status === "skipped-symlink") { logApplyStats(stats); - logger.error(formatSkippedSymlinks(stats.skippedSymlink)); - process.exitCode = 1; - return; + const reason = `Claude settings not written: ${CLAUDE_SETTINGS_REL}, .claude/ or the ledger resolves outside the project (symlink). Nothing was changed there.`; + logger.error(reason); + return { status: "failed", reason }; } - if (args.claude) { - // Scoped opt-in: install --claude authority over settings.json + ledger only. - // manifest.protected is never edited. - const claude = await writeClaudeSessionStartHook(projectRoot, { authorized: true }); - if (claude.status === "skipped-symlink") { - logApplyStats(stats); - logger.error( - `Claude settings not written: ${CLAUDE_SETTINGS_REL}, .claude/ or the ledger resolves outside the project (symlink). Nothing was changed there.`, - ); - process.exitCode = 1; - return; - } - if (claude.status === "unavailable") { - logger.warn(claude.instructions ?? `${CLAUDE_SETTINGS_REL} could not be merged.`); - } else { - console.log(`Claude settings ${claude.status}: ${claude.relativePath}`); - const changed = formatPermissionsChanged(claude.permissionChanges ?? [], { - mergeAllowWithoutGuard: claude.mergeAllowWithoutGuard ?? [], - }); - for (const line of changed) console.log(line); - } - // Adopt the command adapters without reapplying L0: writes only - // .claude/commands/* (plus the shared managed-hash ledger), overlay-safe. - const adapters = await generateClaudeCommandAdapters(projectRoot); - const skipped = adapters.filter((a) => a.status === "skipped-symlink"); - if (skipped.length > 0) { - logApplyStats(stats); - logger.error( - `Claude command adapters not written for: ${skipped.map((a) => a.relativePath).join(", ")} (symlink outside the project). Nothing was changed there.`, - ); - process.exitCode = 1; - return; - } - if (adapters.length > 0) console.log(formatClaudeAdapterSummary(adapters)); + if (claude.status === "unavailable") { + logger.warn(claude.instructions ?? `${CLAUDE_SETTINGS_REL} could not be merged.`); } else { - // Report-only: never writes settings.json or the ledger (`--claude` is the opt-in). - const drift = await planClaudeSettingsDrift(projectRoot); - if (drift) { - const protectedPath = isProtectedPath(CLAUDE_SETTINGS_REL, resolveProtectedGlobs(next)); - for (const line of formatClaudeSettingsDrift(drift, { protectedPath })) console.log(line); - } + console.log(`Claude settings ${claude.status}: ${claude.relativePath}`); + const changed = formatPermissionsChanged(claude.permissionChanges ?? [], { + mergeAllowWithoutGuard: claude.mergeAllowWithoutGuard ?? [], + }); + for (const line of changed) console.log(line); } - await saveManifest(projectRoot, next); - logApplyStats(stats); - // State the version actually written: a run that changes no version is a - // legitimate outcome, but it must not read the same as one that bumps. - const transition = - next.version === existing.version - ? `unchanged at v${next.version}` - : `v${existing.version} → v${next.version}`; - logger.success(`Update complete: ${transition} (L3 protected paths left untouched).`); + // Adopt the command adapters without reapplying L0: writes only + // .claude/commands/* (plus the shared managed-hash ledger), overlay-safe. + const adapters = await generateClaudeCommandAdapters(projectRoot); + const skipped = adapters.filter((a) => a.status === "skipped-symlink"); + if (skipped.length > 0) { + logApplyStats(stats); + const reason = `Claude command adapters not written for: ${skipped.map((a) => a.relativePath).join(", ")} (symlink outside the project). Nothing was changed there.`; + logger.error(reason); + return { status: "failed", reason }; + } + if (adapters.length > 0) console.log(formatClaudeAdapterSummary(adapters)); + } else { + // Report-only: never writes settings.json or the ledger (`--claude` is the opt-in). + const drift = await planClaudeSettingsDrift(projectRoot); + if (drift) { + const protectedPath = isProtectedPath(CLAUDE_SETTINGS_REL, resolveProtectedGlobs(next)); + for (const line of formatClaudeSettingsDrift(drift, { protectedPath })) console.log(line); + } + } + await saveManifest(projectRoot, next); + for (const rewrite of packIds.rewrites) logger.info(formatPackIdRewrite(rewrite)); + for (const id of retiredSkills.dropped) logger.info(formatRetiredSkillDrop(id)); + logApplyStats(stats); + // State the version actually written: a run that changes no version is a + // legitimate outcome, but it must not read the same as one that bumps. + const transition = + next.version === existing.version + ? `unchanged at v${next.version}` + : `v${existing.version} → v${next.version}`; + logger.success(`Update complete: ${transition} (L3 protected paths left untouched).`); + await feedInstallsRegistry(projectRoot); + if (options.syncPathCli) { const sync = await syncPathCliToRuntime({ runtimeVersion: KIT_VERSION }); for (const line of sync.lines) console.log(line); - } finally { - await registry.unlock?.(); } - }, -}); + return { status: "applied", fromVersion: existing.version, toVersion: next.version, stats }; + } finally { + await registry.unlock?.(); + } +} function formatClaudeAdapterSummary(results: ClaudeCommandAdapterResult[]): string { const count = (status: ClaudeCommandAdapterResult["status"]) => diff --git a/packages/cli/src/dashboard/dashboard-data-snapshot.test.ts b/packages/cli/src/dashboard/dashboard-data-snapshot.test.ts index f89365f..eda3d5a 100644 --- a/packages/cli/src/dashboard/dashboard-data-snapshot.test.ts +++ b/packages/cli/src/dashboard/dashboard-data-snapshot.test.ts @@ -750,3 +750,235 @@ describe("dashboard-data.mjs: Health first run (Amend 2026-11-19)", SUBPROCESS_T expect(by.agents.detail).not.toContain("good.md"); }); }); + +// ── Install health (plan cli-install-update-overhaul c2): doctor writes, Health reads ── +type InstallSnapshot = { + health: { + status: string; + checks: HealthCheck[]; + install: null | { + generatedAt: string | null; + status: string; + checks: Array; + }; + }; +}; + +function seedInstallHealth(repo: string) { + mkdirSync(join(repo, ".cursor", "context"), { recursive: true }); + writeFileSync( + join(repo, ".cursor", "context", "install-health.json"), + JSON.stringify({ + version: 1, + generatedAt: "2026-11-26T10:00:00.000Z", + status: "warning", + checks: [ + { + id: "global-cli", + label: "Global CLI vs npm latest", + severity: "info", + detail: "v6.22.1 at /usr/local/bin/agent-kit; npm registry did not answer, not compared", + fix: null, + fixKind: null, + }, + { + id: "node-manager", + label: "Node version manager", + severity: "warning", + detail: + "~/.local/share/mise/installs/node/26.8.2/bin/agent-kit lives in mise node 26.8.2", + fix: '"npm:@dadado/agent-kit-cli" = { version = "latest", allow_low_downloads = true, minimum_release_age = "0s" }', + fixKind: "config-line", + }, + { + id: "registry-pin", + label: "Registry pin", + severity: "warning", + detail: "registry.ref v5.4.0 in .cursor/agent-kit.json is older than v5.9.0", + fix: "agent-kit update --ref v5.9.0", + fixKind: "command", + }, + { id: "unknown-id", label: "x", severity: "warning", detail: "dropped", fix: null }, + ], + }), + ); +} + +describe("dashboard-data.mjs: Health install group (c2)", SUBPROCESS_TIMEOUT, () => { + it("absent install-health.json: install is null and the seven checks are unchanged", () => { + const repo = mkdtempSync(join(tmpdir(), "ak-dashdata-install-absent-")); + initGitRepo(repo); + const snap = runDashboardData(repo, { HOME: scratchHome() }) as unknown as InstallSnapshot; + expect(snap.health.install).toBeNull(); + expect(snap.health.checks).toHaveLength(7); + }); + + it("loopback: reads doctor's file, keeps it outside checks[] and status, command fixes only", () => { + const repo = mkdtempSync(join(tmpdir(), "ak-dashdata-install-loop-")); + initGitRepo(repo); + seedInstallHealth(repo); + const snap = runDashboardData(repo, { HOME: scratchHome() }) as unknown as InstallSnapshot; + expect(snap.health.checks.map((c) => c.id)).not.toContain("node-manager"); + const install = snap.health.install; + expect(install?.status).toBe("warning"); + expect(install?.generatedAt).toBe("2026-11-26T10:00:00.000Z"); + expect(install?.checks.map((c) => c.id)).toEqual([ + "global-cli", + "node-manager", + "registry-pin", + ]); + const by = Object.fromEntries((install?.checks ?? []).map((c) => [c.id, c])); + expect(by["global-cli"]).toMatchObject({ ok: true, severity: "ok", fix: null }); + expect(by["node-manager"]).toMatchObject({ ok: false, severity: "warning", fix: null }); + expect(by["node-manager"].detail).toContain("~/.local/share/mise/installs/node/26.8.2"); + // The mise tool entry is a config line, not a terminal command: it rides in the detail. + expect(by["node-manager"].detail).toContain( + '(add: "npm:@dadado/agent-kit-cli" = { version = "latest", allow_low_downloads = true, minimum_release_age = "0s" })', + ); + expect(by["registry-pin"].fix).toBe("agent-kit update --ref v5.9.0"); + }); + + it("broadcast: no paths and no fix leave the machine", () => { + const repo = mkdtempSync(join(tmpdir(), "ak-dashdata-install-bcast-")); + initGitRepo(repo); + seedInstallHealth(repo); + const snap = runDashboardData(repo, { + HOME: scratchHome(), + HOST: "0.0.0.0", + MISSION_CONTROL_TOKEN: "h".repeat(32), + }) as unknown as InstallSnapshot; + const raw = JSON.stringify(snap.health.install); + expect(raw).not.toContain("~/"); + expect(raw).not.toContain("/usr/local/bin"); + expect(snap.health.install?.checks.every((c) => c.fix === null)).toBe(true); + }); +}); + +type UpdateNoticeSnapshot = { + health: { + checks: HealthCheck[]; + updateNotice: null | { + cliVersion: string | null; + npmLatest: string | null; + cliBehind: boolean; + installsBehind: number; + oldest: { kitVersion: string; path: string | null } | null; + label: string; + severity: string; + detail: string; + fix: string | null; + }; + }; +}; + +/** Seed the machine notice cache the sessionStart hook writes; returns the env that points at it. */ +function seedUpdateNotice(notice: Record | null): Record { + const dir = mkdtempSync(join(tmpdir(), "ak-dashdata-notice-")); + writeFileSync( + join(dir, "update-notice.json"), + JSON.stringify({ + schemaVersion: 1, + checkedAt: "2026-11-26T10:00:00.000Z", + npm: { packageName: "@dadado/agent-kit-cli", version: "6.22.0" }, + notice, + }), + ); + return { + AGENT_KIT_INSTALLS_FILE: join(dir, "installs.json"), + CI: "", + AGENT_KIT_NO_UPDATE_CHECK: "", + NO_UPDATE_NOTIFIER: "", + }; +} + +const BEHIND_NOTICE = { + generatedAt: "2026-11-26T10:00:00.000Z", + cliVersion: "6.19.1", + npmLatest: { packageName: "@dadado/agent-kit-cli", version: "6.22.0" }, + cliBehind: true, + installsBehind: 9, + oldest: { path: "~/x", kitVersion: "3.0.0" }, + cliCommand: "npm i -g @dadado/agent-kit-cli@latest", + line: "Agent Kit: CLI 6.19.1 < npm 6.22.0 (`npm i -g @dadado/agent-kit-cli@latest`); 9 installs behind, oldest v3.0.0 at ~/x (`agent-kit update --all`).", +}; + +describe("dashboard-data.mjs: update notice card (c4)", SUBPROCESS_TIMEOUT, () => { + it("loopback: one card with the count, the oldest install and the CLI command first", () => { + const repo = mkdtempSync(join(tmpdir(), "ak-dashdata-notice-loop-")); + initGitRepo(repo); + const snap = runDashboardData(repo, { + HOME: scratchHome(), + ...seedUpdateNotice(BEHIND_NOTICE), + }) as unknown as UpdateNoticeSnapshot; + expect(snap.health.checks).toHaveLength(7); + expect(snap.health.updateNotice).toMatchObject({ + cliVersion: "6.19.1", + npmLatest: "6.22.0", + cliBehind: true, + installsBehind: 9, + oldest: { kitVersion: "3.0.0", path: "~/x" }, + label: "9 installs behind", + severity: "warning", + fix: "npm i -g @dadado/agent-kit-cli@latest", + }); + expect(snap.health.updateNotice?.detail).toBe( + "CLI 6.19.1 is behind npm 6.22.0; 9 installs behind CLI 6.19.1, oldest v3.0.0 at ~/x. Check-only: nothing is applied.", + ); + }); + + it("installs only: the fix is update --all", () => { + const repo = mkdtempSync(join(tmpdir(), "ak-dashdata-notice-inst-")); + initGitRepo(repo); + const snap = runDashboardData(repo, { + HOME: scratchHome(), + ...seedUpdateNotice({ + ...BEHIND_NOTICE, + cliBehind: false, + cliCommand: null, + installsBehind: 1, + }), + }) as unknown as UpdateNoticeSnapshot; + expect(snap.health.updateNotice).toMatchObject({ + label: "1 install behind", + fix: "agent-kit update --all", + }); + }); + + it("broadcast: no path and no fix leave the machine", () => { + const repo = mkdtempSync(join(tmpdir(), "ak-dashdata-notice-bcast-")); + initGitRepo(repo); + const snap = runDashboardData(repo, { + HOME: scratchHome(), + HOST: "0.0.0.0", + MISSION_CONTROL_TOKEN: "h".repeat(32), + ...seedUpdateNotice(BEHIND_NOTICE), + }) as unknown as UpdateNoticeSnapshot; + const raw = JSON.stringify(snap.health.updateNotice); + expect(raw).not.toContain("~/"); + expect(snap.health.updateNotice?.oldest).toEqual({ kitVersion: "3.0.0", path: null }); + expect(snap.health.updateNotice?.fix).toBeNull(); + }); + + it("null when current, absent, under CI, with the env opt-out or updateCheck.enabled false", () => { + const repo = mkdtempSync(join(tmpdir(), "ak-dashdata-notice-off-")); + initGitRepo(repo); + const home = scratchHome(); + const run = (env: Record) => + (runDashboardData(repo, { HOME: home, ...env }) as unknown as UpdateNoticeSnapshot).health + .updateNotice; + expect(run(seedUpdateNotice(null))).toBeNull(); + const behind = seedUpdateNotice(BEHIND_NOTICE); + expect( + run({ ...behind, AGENT_KIT_INSTALLS_FILE: join(home, "nowhere", "installs.json") }), + ).toBeNull(); + expect(run({ ...behind, CI: "true" })).toBeNull(); + expect(run({ ...behind, AGENT_KIT_NO_UPDATE_CHECK: "1" })).toBeNull(); + expect(run({ ...behind, NO_UPDATE_NOTIFIER: "1" })).toBeNull(); + mkdirSync(join(repo, ".cursor", "context"), { recursive: true }); + writeFileSync( + join(repo, ".cursor", "context", "config.json"), + JSON.stringify({ updateCheck: { enabled: false } }), + ); + expect(run(behind)).toBeNull(); + }); +}); diff --git a/packages/cli/src/dashboard/plugin-ux-validation.test.ts b/packages/cli/src/dashboard/plugin-ux-validation.test.ts index 8dceb1b..de30429 100644 --- a/packages/cli/src/dashboard/plugin-ux-validation.test.ts +++ b/packages/cli/src/dashboard/plugin-ux-validation.test.ts @@ -4497,3 +4497,68 @@ describe("plugin-ux-validation: Git e CI/CD bento section (ship lane, ADR 2026-1 expect(gitCicdNavTone({})).toBe("gray"); }); }); + +describe("Health install group (plan cli-install-update-overhaul c2)", () => { + const fnSource = + dashboardHtml.match(/function renderInstallHealthGroup\([\s\S]*?\n\}\n/)?.[0] ?? ""; + const renderGroup = loadDashboardExtract< + (install: unknown, renderCard: (c: { id: string }) => string) => string + >(`const escapeHtml = (s) => String(s);\n${fnSource}\nreturn renderInstallHealthGroup;`); + + it("renders health.install as its own group outside the seven checks, empty when absent", () => { + expect(fnSource).not.toBe(""); + expect(renderGroup(null, () => "")).toBe(""); + expect(renderGroup({ checks: [] }, () => "")).toBe(""); + const html = renderGroup( + { generatedAt: "2026-11-26T10:00:00.000Z", checks: [{ id: "node-manager" }] }, + (c) => ``, + ); + expect(html).toContain('aria-label="Install"'); + expect(html).toContain("Install (agent-kit doctor, 2026-11-26)"); + expect(html).toContain(""); + expect(dashboardHtml).toContain("${renderInstallHealthGroup(health.install, renderCheckCard)}"); + }); + + it("a check's own fix line becomes a terminal copy before the static meta autofix", () => { + expect(dashboardHtml).toContain( + "? { text: c.fix, subject: c.fix, destination: 'terminal', label: 'Copy fix' }", + ); + expect(dashboardHtml).toContain( + ": ownFix || (meta.autofixBySeverity && meta.autofixBySeverity[sev]) || meta.autofix || null;", + ); + }); +}); + +describe("Health update notice card (plan cli-install-update-overhaul c4)", () => { + const fnSource = + dashboardHtml.match(/function renderUpdateNoticeGroup\([\s\S]*?\n\}\n/)?.[0] ?? ""; + const renderGroup = loadDashboardExtract< + ( + notice: unknown, + renderCard: (c: { + id: string; + label: string; + severity: string; + fix: string | null; + }) => string, + ) => string + >(`${fnSource}\nreturn renderUpdateNoticeGroup;`); + + it("renders one warning card from health.updateNotice, nothing when null", () => { + expect(fnSource).not.toBe(""); + expect(renderGroup(null, () => "x")).toBe(""); + const html = renderGroup( + { label: "9 installs behind", detail: "d", fix: "agent-kit update --all" }, + (c) => ``, + ); + expect(html).toContain('aria-label="Updates"'); + expect(html).toContain(""); + expect(dashboardHtml).toContain( + "${renderUpdateNoticeGroup(health.updateNotice, renderCheckCard)}", + ); + }); + + it("Config shows the update check on unless explicitly false", () => { + expect(dashboardHtml).toContain("const updateCheckEnabled = uc.enabled !== false;"); + }); +}); diff --git a/packages/cli/src/hooks/session-start.test.ts b/packages/cli/src/hooks/session-start.test.ts index cccc1e0..fc7570f 100644 --- a/packages/cli/src/hooks/session-start.test.ts +++ b/packages/cli/src/hooks/session-start.test.ts @@ -806,3 +806,51 @@ describe("sessionStart spawn sections: parallel + deadline", () => { expect(section).toContain("1.1.0"); }); }); + +describe("buildSessionStartAdditionalContext: machine update notice", () => { + it("adds the one notice line when an install is behind, and nothing when opted out", async () => { + const root = await mkdtemp(path.join(tmpdir(), "ak-session-notice-")); + await mkdir(path.join(root, ".cursor", "context"), { recursive: true }); + const home = path.join(root, "home"); + const installsFile = path.join(root, "cfg", "installs.json"); + await mkdir(path.dirname(installsFile), { recursive: true }); + await writeFile( + installsFile, + JSON.stringify({ + schemaVersion: 1, + installs: [ + { + path: path.join(home, "x"), + remote: null, + kitVersion: "3.0.0", + cliVersion: "6.0.0", + lastSeen: "2026-11-26T00:00:00.000Z", + kind: "repo", + }, + ], + }), + "utf8", + ); + const fetchImpl = vi.fn(async () => ({ ok: false, json: async () => ({}) })); + const notice = { + env: {}, + homeDir: home, + cliVersion: "6.22.0", + fetchImpl, + installsFile, + file: path.join(root, "cfg", "update-notice.json"), + cliPath: null, + }; + const line = + "Agent Kit: 1 install behind CLI 6.22.0, oldest v3.0.0 at ~/x (`agent-kit update --all`)."; + const on = await buildSessionStartAdditionalContext(root, {}, { updateNotice: notice }); + expect(on.additional_context).toContain(line); + expect(on.additional_context.split(line)).toHaveLength(2); + const off = await buildSessionStartAdditionalContext( + root, + {}, + { updateNotice: { ...notice, env: { AGENT_KIT_NO_UPDATE_CHECK: "1" } } }, + ); + expect(off.additional_context).not.toContain("Agent Kit: "); + }); +}); diff --git a/packages/cli/src/hooks/session-start.ts b/packages/cli/src/hooks/session-start.ts index 37c3f06..04effd2 100644 --- a/packages/cli/src/hooks/session-start.ts +++ b/packages/cli/src/hooks/session-start.ts @@ -13,6 +13,11 @@ import { shouldEmitPublicInboundNudge, stampPublicInboundCheck, } from "../lifecycle/public-inbound-radar.js"; +import { + computeUpdateNotice, + UPDATE_NOTICE_SESSION_FETCH_TIMEOUT_MS, + type UpdateNoticeOptions, +} from "../lifecycle/update-notice.js"; import { MANIFEST_RELATIVE_PATH } from "../manifest/types.js"; import { formatPlanIndexSection, writePlanIndex } from "../plan-index/plan-index.js"; import { @@ -227,6 +232,35 @@ export function colonyHostSection(env: NodeJS.ProcessEnv = process.env): string return env.COLONY_HOST_CLI?.trim() ? COLONY_HOST_HINT : null; } +/** Ceiling for the machine update notice (cache read + at most one bounded npm lookup a day). */ +export const UPDATE_NOTICE_SECTION_DEADLINE_MS = UPDATE_NOTICE_SESSION_FETCH_TIMEOUT_MS + 1_000; + +/** + * Machine update notice (ADR 2026-07-27 Amend 2026-11-26): one line when the CLI + * is behind npm or a registered install is behind the CLI; null when current, + * off (CI, env opt-out, `updateCheck.enabled: false`) or on any error. In-process + * and deadline-capped; never applies anything. + */ +export async function updateNoticeSection( + root: string, + options: UpdateNoticeOptions & { deadlineMs?: number } = {}, +): Promise { + const { deadlineMs, ...noticeOptions } = options; + const summary = await withDeadline( + computeUpdateNotice(root, { + timeoutMs: UPDATE_NOTICE_SESSION_FETCH_TIMEOUT_MS, + ...noticeOptions, + }), + deadlineMs ?? UPDATE_NOTICE_SECTION_DEADLINE_MS, + ); + return summary?.line ?? null; +} + +/** + * Legacy per-repo nudge (manifest vs public tags, a `git ls-remote` child): still + * only on an explicit `updateCheck.enabled: true`, although the check itself is + * on by default. The default path is {@link updateNoticeSection}, in-process. + */ async function loadUpdateCheckPrefs(root: string): Promise | null> { const data = await loadContextConfig(root); if (!data) return null; @@ -879,6 +913,8 @@ export async function buildSessionStartAdditionalContext( spawnFn?: CursorAwarenessSpawn; deadlineMs?: number; liveRoster?: (root: string) => Promise; + /** Seams for the machine update notice (tests: env, fetch, files, now). */ + updateNotice?: UpdateNoticeOptions; } = {}, ): Promise<{ additional_context: string }> { const root = path.resolve(rootDir); @@ -914,13 +950,17 @@ export async function buildSessionStartAdditionalContext( attempt: SectionAttempt, ): Promise => runSectionWithDeadline(section, root, deps.spawnFn, deadlineMs, attempt); - const [updateNudge, cursorNudge, inboundNudge] = await Promise.all([ + const [updateNotice, updateNudge, cursorNudge, inboundNudge] = await Promise.all([ + updateNoticeSection(root, deps.updateNotice).catch(() => null), runSection(updateCheckSection, updateAttempt), runSection(cursorAwarenessSection, cursorAttempt), runSection(publicInboundSection, inboundAttempt), ]); await stampSectionAttempts(root, updateAttempt, cursorAttempt, inboundAttempt); - if (updateNudge) parts.push(updateNudge); + // One update line: the machine notice wins over the legacy per-repo nudge + // (explicit `updateCheck.enabled: true` only) when both have something to say. + if (updateNotice) parts.push(updateNotice); + else if (updateNudge) parts.push(updateNudge); if (cursorNudge) parts.push(cursorNudge); if (inboundNudge) parts.push(inboundNudge); diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index f661b67..2288369 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -24,6 +24,7 @@ const main = defineCommand({ "setup-global": () => import("./commands/setup-global.js").then((m) => m.setupGlobalCommand), status: () => import("./commands/status.js").then((m) => m.statusCommand), update: () => import("./commands/update.js").then((m) => m.updateCommand), + installs: () => import("./commands/installs.js").then((m) => m.installsCommand), "cursor-awareness": () => import("./commands/cursor-awareness.js").then((m) => m.cursorAwarenessCommand), "public-inbound-radar": () => diff --git a/packages/cli/src/installs/index.ts b/packages/cli/src/installs/index.ts new file mode 100644 index 0000000..5d51e56 --- /dev/null +++ b/packages/cli/src/installs/index.ts @@ -0,0 +1,80 @@ +/** + * Machine install registry API (`~/.config/agent-kit/installs.json`). + * Consumers: `agent-kit installs`, the install/update/doctor feeds, and + * `update --all` (ADR 2026-11-26_update-all-operator-only-branch-mr-per-repo). + */ + +import { hasInstallManifest, type InspectOptions, inspectInstall } from "./inspect.js"; +import { + type InstallEntry, + type InstallsStoreOptions, + pruneInstalls, + upsertInstalls, +} from "./store.js"; + +export { + classifyInstall, + hasInstallManifest, + type InspectOptions, + type InstallFacts, + inspectInstall, + isFactoryInstall, + sanitizeRemote, +} from "./inspect.js"; +export { + DEFAULT_SCAN_DEPTH, + DEFAULT_SCAN_MAX_DIRS, + type ScanResult, + scanForInstalls, +} from "./scan.js"; +export { + INSTALL_KINDS, + INSTALLS_FILE_ENV, + type InstallEntry, + type InstallKind, + type InstallRecord, + type InstallsFile, + InstallsRegistryError, + type InstallsStoreOptions, + listInstalls, + readInstalls, + resolveInstallsFile, + upsertInstalls, +} from "./store.js"; + +export type RecordOptions = InstallsStoreOptions & InspectOptions; + +/** Inspect `dirs` and upsert the ones that hold a kit manifest. Returns the rows written. */ +export async function recordInstalls( + dirs: readonly string[], + options: RecordOptions = {}, +): Promise { + const records = []; + for (const dir of dirs) { + const record = await inspectInstall(dir, options); + if (record) records.push(record); + } + return upsertInstalls(records, { ...options, stillInstalled: hasInstallManifest }); +} + +/** Remove rows whose directory or manifest is gone. Returns the removed rows. */ +export function pruneMissingInstalls(options: InstallsStoreOptions = {}): Promise { + return pruneInstalls({ ...options, stillInstalled: hasInstallManifest }); +} + +/** Lock wait for the install/update/doctor feed: short, it must never stall them. */ +const FEED_LOCK_TIMEOUT_MS = 3_000; + +/** + * Fail-open feed from install, update, init and doctor: records `root` when it + * holds a kit manifest, silently. Any error (lock timeout, unreadable or newer + * registry file, read-only config dir) is swallowed; it never fails the command + * and never prints (doctor --json stdout stays deterministic). + */ +export async function feedInstallsRegistry(root: string): Promise { + try { + await recordInstalls([root], { lockTimeoutMs: FEED_LOCK_TIMEOUT_MS }); + } catch { + // Fail open: the registry is an index, rebuildable by `agent-kit installs scan`. + } +} diff --git a/packages/cli/src/installs/inspect.ts b/packages/cli/src/installs/inspect.ts new file mode 100644 index 0000000..dc866c4 --- /dev/null +++ b/packages/cli/src/installs/inspect.ts @@ -0,0 +1,243 @@ +/** + * Facts and classification for one install of the machine registry. + * Read-only: runs `git rev-parse` and `git remote get-url` only (never a + * command that may rewrite the index) and never writes inside the repo. + */ + +import { execFile } from "node:child_process"; +import { readFile, realpath } from "node:fs/promises"; +import { homedir, tmpdir } from "node:os"; +import path from "node:path"; +import { promisify } from "node:util"; +import { KIT_VERSION } from "../lifecycle/version.js"; +import { MANIFEST_RELATIVE_PATH } from "../manifest/types.js"; +import { fileExists } from "../utils/fs.js"; +import type { InstallKind, InstallRecord } from "./store.js"; + +const execFileAsync = promisify(execFile); + +/** Origin URL markers of the kit's own repository (factory, ADR 2026-07-31). */ +const FACTORY_REMOTE_MARKERS = ["agent-kit-dev"]; +/** CLI package names whose presence under `packages/cli` marks a kit checkout. */ +const FACTORY_CLI_PACKAGES = new Set(["@dadado/agent-kit-cli", "@missionkit/cli"]); +/** Path segments that mark a test fixture rather than a repository. */ +const FIXTURE_SEGMENTS = new Set([ + "fixtures", + "__fixtures__", + "test-fixtures", + "testdata", + "__tests__", +]); + +export interface GitFacts { + /** Absolute `--show-toplevel`. */ + toplevel: string; + /** Absolute `--git-dir`. */ + gitDir: string; + /** Absolute `--git-common-dir`. */ + commonDir: string; +} + +export interface InstallFacts { + /** Real absolute path of the install directory. */ + path: string; + /** Real home directory. */ + home: string; + /** Real temp roots: a manifest below one is a fixture. */ + tmpRoots: readonly string[]; + /** Null when the directory is not inside a git work tree. */ + git: GitFacts | null; + /** Raw origin URL (credentials still present), or null. */ + origin: string | null; + /** `name` of `packages/cli/package.json`, or null. */ + cliPackageName: string | null; +} + +/** Strip userinfo (`https://token@host/…`) so no credential lands in the registry. */ +export function sanitizeRemote(url: string | null): string | null { + if (!url) return null; + const trimmed = url.trim(); + if (!trimmed) return null; + try { + const parsed = new URL(trimmed); + if (parsed.username || parsed.password) { + parsed.username = ""; + parsed.password = ""; + return parsed.toString(); + } + return trimmed; + } catch { + // scp-style `git@host:group/repo.git` is not a URL and carries no secret. + return trimmed; + } +} + +function isUnder(child: string, parent: string): boolean { + const rel = path.relative(parent, child); + return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel)); +} + +export function isFactoryInstall(facts: Pick): boolean { + const origin = facts.origin?.toLowerCase() ?? ""; + if (FACTORY_REMOTE_MARKERS.some((m) => origin.includes(m))) return true; + return facts.cliPackageName !== null && FACTORY_CLI_PACKAGES.has(facts.cliPackageName); +} + +/** + * One kind per row, first match wins: + * home the install directory is the home directory (`~/.cursor`) + * fixture not its own repository: below a temp root, under a fixtures + * segment, or inside another repo's work tree (git toplevel differs) + * factory the kit's own repo by origin or CLI package, worktrees included + * (wins over worktree so `update --all --include-worktrees` never + * picks a factory worktree) + * worktree a linked worktree: git-dir differs from git-common-dir + * repo anything else, including a directory with no git at all + */ +export function classifyInstall(facts: InstallFacts): InstallKind { + if (facts.path === facts.home) return "home"; + if (facts.tmpRoots.some((root) => isUnder(facts.path, root))) return "fixture"; + const rel = path.relative(facts.home, facts.path); + const segments = (isUnder(facts.path, facts.home) ? rel : facts.path).split(path.sep); + if (segments.some((s) => FIXTURE_SEGMENTS.has(s))) return "fixture"; + if (facts.git && facts.git.toplevel !== facts.path) return "fixture"; + if (isFactoryInstall(facts)) return "factory"; + if (facts.git && facts.git.gitDir !== facts.git.commonDir) return "worktree"; + return "repo"; +} + +/** Child env for read-only git calls: never inherit a caller's repo override. */ +function gitEnv(): NodeJS.ProcessEnv { + const env = { ...process.env }; + for (const key of [ + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_COMMON_DIR", + "GIT_INDEX_FILE", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_CEILING_DIRECTORIES", + ]) { + delete env[key]; + } + return env; +} + +async function safeRealpath(p: string): Promise { + try { + return await realpath(p); + } catch { + return path.resolve(p); + } +} + +async function readGitFacts(dir: string): Promise { + try { + const { stdout } = await execFileAsync( + "git", + ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-dir", "--git-common-dir"], + { cwd: dir, env: gitEnv(), encoding: "utf8", timeout: 5_000 }, + ); + const [toplevel, gitDir, commonDir] = stdout.trim().split("\n"); + if (!toplevel || !gitDir || !commonDir) return null; + return { + toplevel: await safeRealpath(toplevel), + gitDir: await safeRealpath(gitDir), + commonDir: await safeRealpath(commonDir), + }; + } catch { + return null; + } +} + +async function readOrigin(dir: string): Promise { + try { + const { stdout } = await execFileAsync("git", ["remote", "get-url", "origin"], { + cwd: dir, + env: gitEnv(), + encoding: "utf8", + timeout: 5_000, + }); + return stdout.trim() || null; + } catch { + return null; + } +} + +async function readCliPackageName(dir: string): Promise { + try { + const raw = await readFile(path.join(dir, "packages", "cli", "package.json"), "utf8"); + const name = (JSON.parse(raw) as { name?: unknown }).name; + return typeof name === "string" ? name : null; + } catch { + return null; + } +} + +async function readManifestVersion(dir: string): Promise { + let raw: string; + try { + raw = await readFile(path.join(dir, MANIFEST_RELATIVE_PATH), "utf8"); + } catch { + return undefined; + } + try { + const version = (JSON.parse(raw) as { version?: unknown }).version; + return typeof version === "string" && version.trim() ? version.trim() : null; + } catch { + return null; + } +} + +/** True while `/.cursor/agent-kit.json` exists (the registry's liveness rule). */ +export function hasInstallManifest(dir: string): Promise { + return fileExists(path.join(dir, MANIFEST_RELATIVE_PATH)); +} + +export interface InspectOptions { + home?: string; + tmpRoots?: readonly string[]; + cliVersion?: string; +} + +async function defaultTmpRoots(): Promise { + const roots = new Set([await safeRealpath(tmpdir())]); + if (process.platform !== "win32") roots.add(await safeRealpath("/tmp")); + return [...roots]; +} + +/** + * Build the registry row for `dir`, or null when it holds no kit manifest. + * The kit version comes from the manifest on disk (the manifest wins). + */ +export async function inspectInstall( + dir: string, + options: InspectOptions = {}, +): Promise { + const installPath = await safeRealpath(dir); + const kitVersion = await readManifestVersion(installPath); + if (kitVersion === undefined) return null; + const home = await safeRealpath(options.home ?? homedir()); + const tmpRoots = options.tmpRoots + ? await Promise.all(options.tmpRoots.map(safeRealpath)) + : await defaultTmpRoots(); + const git = await readGitFacts(installPath); + // A fixture inside another repo would report that repo's origin: only a + // directory that is its own git toplevel has a remote of its own. + const origin = git && git.toplevel === installPath ? await readOrigin(installPath) : null; + const facts: InstallFacts = { + path: installPath, + home, + tmpRoots, + git, + origin, + cliPackageName: await readCliPackageName(installPath), + }; + return { + path: installPath, + remote: sanitizeRemote(origin), + kitVersion, + cliVersion: options.cliVersion ?? KIT_VERSION, + kind: classifyInstall(facts), + }; +} diff --git a/packages/cli/src/installs/installs.test.ts b/packages/cli/src/installs/installs.test.ts new file mode 100644 index 0000000..99a7b77 --- /dev/null +++ b/packages/cli/src/installs/installs.test.ts @@ -0,0 +1,422 @@ +import { execFile } from "node:child_process"; +import { existsSync } from "node:fs"; +import { + mkdir, + mkdtemp, + readdir, + readFile, + realpath, + rm, + symlink, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { runCommand } from "citty"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { collectRepeatedFlag, installsCommand } from "../commands/installs.js"; +import { + classifyInstall, + feedInstallsRegistry, + type InstallFacts, + InstallsRegistryError, + inspectInstall, + listInstalls, + pruneMissingInstalls, + readInstalls, + recordInstalls, + resolveInstallsFile, + sanitizeRemote, + scanForInstalls, + upsertInstalls, +} from "./index.js"; + +const execFileAsync = promisify(execFile); + +let scratch: string; +let file: string; + +async function git(cwd: string, ...args: string[]): Promise { + const { stdout } = await execFileAsync("git", args, { + cwd, + env: { + ...process.env, + GIT_AUTHOR_NAME: "t", + GIT_AUTHOR_EMAIL: "t@example.com", + GIT_COMMITTER_NAME: "t", + GIT_COMMITTER_EMAIL: "t@example.com", + }, + }); + return stdout.trim(); +} + +async function writeManifest(dir: string, version = "6.23.0"): Promise { + await mkdir(path.join(dir, ".cursor"), { recursive: true }); + await writeFile( + path.join(dir, ".cursor", "agent-kit.json"), + JSON.stringify({ schemaVersion: 1, version }), + ); +} + +async function initRepo(dir: string, origin?: string): Promise { + await mkdir(dir, { recursive: true }); + await git(dir, "init", "-q", "-b", "main"); + if (origin) await git(dir, "remote", "add", "origin", origin); + await writeManifest(dir); + await git(dir, "add", "."); + await git(dir, "commit", "-q", "-m", "init"); +} + +beforeEach(async () => { + scratch = await realpath(await mkdtemp(path.join(tmpdir(), "ak-installs-"))); + file = path.join(scratch, "config", "agent-kit", "installs.json"); +}); + +afterEach(async () => { + await rm(scratch, { recursive: true, force: true }); +}); + +describe("resolveInstallsFile", () => { + it("prefers the env override, then an absolute XDG_CONFIG_HOME, then ~/.config", () => { + expect(resolveInstallsFile({ AGENT_KIT_INSTALLS_FILE: "/x/i.json" }, "/home/u")).toBe( + "/x/i.json", + ); + expect(resolveInstallsFile({ XDG_CONFIG_HOME: "/xdg" }, "/home/u")).toBe( + "/xdg/agent-kit/installs.json", + ); + expect(resolveInstallsFile({ XDG_CONFIG_HOME: "relative" }, "/home/u")).toBe( + "/home/u/.config/agent-kit/installs.json", + ); + expect(resolveInstallsFile({}, "/home/u")).toBe("/home/u/.config/agent-kit/installs.json"); + }); + + it("is isolated by the vitest setup (never the operator's real file)", () => { + expect(process.env.AGENT_KIT_INSTALLS_FILE).toBeTruthy(); + expect(resolveInstallsFile()).toBe(process.env.AGENT_KIT_INSTALLS_FILE); + }); +}); + +describe("store", () => { + const row = (p: string) => ({ + path: p, + remote: null, + kitVersion: "6.23.0", + cliVersion: "6.23.0", + kind: "repo" as const, + }); + + it("reads a missing file as empty and creates nothing", async () => { + expect(await listInstalls({ file })).toEqual([]); + expect(existsSync(path.dirname(file))).toBe(false); + }); + + it("upserts by path, sorts, and leaves no temp or lock files", async () => { + await upsertInstalls([row("/b"), row("/a")], { file }); + await upsertInstalls([{ ...row("/a"), kitVersion: "6.24.0" }], { file }); + const body = JSON.parse(await readFile(file, "utf8")); + expect(body.schemaVersion).toBe(1); + expect(body.installs.map((e: { path: string }) => e.path)).toEqual(["/a", "/b"]); + expect(body.installs[0].kitVersion).toBe("6.24.0"); + expect(body.installs[0].lastSeen).toMatch(/^\d{4}-\d{2}-\d{2}T/); + expect(await readdir(path.dirname(file))).toEqual(["installs.json"]); + }); + + it("never loses a row under concurrent writers", async () => { + const paths = Array.from({ length: 12 }, (_, i) => `/repo-${String(i).padStart(2, "0")}`); + await Promise.all(paths.map((p) => upsertInstalls([row(p)], { file }))); + expect((await listInstalls({ file })).map((e) => e.path)).toEqual(paths); + }); + + it("never loses a row under concurrent writer processes", async () => { + const here = path.dirname(fileURLToPath(import.meta.url)); + const script = path.join(scratch, "writer.mts"); + await writeFile( + script, + `import { upsertInstalls } from ${JSON.stringify(path.join(here, "store.ts"))}; +const [file, p] = process.argv.slice(2); +await upsertInstalls([{ path: p, remote: null, kitVersion: "1.0.0", cliVersion: "1.0.0", kind: "repo" }], { file }); +`, + ); + const paths = ["/p1", "/p2", "/p3", "/p4"]; + await Promise.all( + paths.map((p) => + execFileAsync(process.execPath, ["--import", "tsx", script, file, p], { + cwd: path.join(here, "..", ".."), + }), + ), + ); + expect((await listInstalls({ file })).map((e) => e.path)).toEqual(paths); + }, 30_000); + + it("refuses to rewrite a corrupt or newer-schema file", async () => { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, "{not json"); + await expect(upsertInstalls([row("/a")], { file })).rejects.toBeInstanceOf( + InstallsRegistryError, + ); + expect(await readFile(file, "utf8")).toBe("{not json"); + + const newer = JSON.stringify({ schemaVersion: 2, installs: [] }); + await writeFile(file, newer); + await expect(readInstalls({ file })).rejects.toThrow(/schemaVersion 2/); + await expect(upsertInstalls([row("/a")], { file })).rejects.toThrow(/Left untouched/); + expect(await readFile(file, "utf8")).toBe(newer); + }); + + it("keeps rows it cannot read through a write", async () => { + await mkdir(path.dirname(file), { recursive: true }); + const future = { path: "/z", kind: "cloud", lastSeen: "x" }; + await writeFile(file, JSON.stringify({ schemaVersion: 1, installs: [future] })); + await upsertInstalls([row("/a")], { file }); + expect((await listInstalls({ file })).map((e) => e.path)).toEqual(["/a"]); + expect(JSON.parse(await readFile(file, "utf8")).installs).toContainEqual(future); + // A recognized row for the same path replaces it. + await upsertInstalls([row("/z")], { file }); + expect(JSON.parse(await readFile(file, "utf8")).installs).not.toContainEqual(future); + }); + + it("prunes rows whose install is gone and never resurrects them", async () => { + const live = path.join(scratch, "live"); + const gone = path.join(scratch, "gone"); + await writeManifest(live); + await writeManifest(gone); + await recordInstalls([live, gone], { file, tmpRoots: [] }); + await rm(gone, { recursive: true, force: true }); + + const removed = await pruneMissingInstalls({ file }); + expect(removed.map((e) => e.path)).toEqual([gone]); + expect((await listInstalls({ file })).map((e) => e.path)).toEqual([live]); + + // A writer holding a stale view of `gone` re-checks under the lock. + await upsertInstalls([row(gone)], { file, stillInstalled: async () => existsSync(gone) }); + expect((await listInstalls({ file })).map((e) => e.path)).toEqual([live]); + }); +}); + +describe("classifyInstall", () => { + const ownGit = { + toplevel: "/home/u/code/app", + gitDir: "/home/u/code/app/.git", + commonDir: "/home/u/code/app/.git", + }; + const base: InstallFacts = { + path: "/home/u/code/app", + home: "/home/u", + tmpRoots: ["/tmp"], + git: { + toplevel: "/home/u/code/app", + gitDir: "/home/u/code/app/.git", + commonDir: "/home/u/code/app/.git", + }, + origin: "git@github.com:acme/app.git", + cliPackageName: null, + }; + const wt = { + toplevel: base.path, + gitDir: "/home/u/code/main/.git/worktrees/app", + commonDir: "/home/u/code/main/.git", + }; + + it("classifies home, fixture, worktree and repo", () => { + expect(classifyInstall(base)).toBe("repo"); + expect(classifyInstall({ ...base, path: "/home/u" })).toBe("home"); + expect(classifyInstall({ ...base, path: "/tmp/x", git: null })).toBe("fixture"); + expect(classifyInstall({ ...base, path: "/home/u/code/kit/test/fixtures/consumer" })).toBe( + "fixture", + ); + expect(classifyInstall({ ...base, git: { ...ownGit, toplevel: "/home/u/code" } })).toBe( + "fixture", + ); + expect(classifyInstall({ ...base, git: wt })).toBe("worktree"); + expect(classifyInstall({ ...base, git: null, origin: null })).toBe("repo"); + }); + + it("treats a nested install as a fixture when $HOME itself is a git repo", () => { + const homeRepo = { toplevel: "/home/u", gitDir: "/home/u/.git", commonDir: "/home/u/.git" }; + expect(classifyInstall({ ...base, path: "/home/u", git: homeRepo })).toBe("home"); + expect(classifyInstall({ ...base, git: homeRepo })).toBe("fixture"); + }); + + it("marks the factory, and factory wins over worktree", () => { + const factory = { ...base, origin: "https://github.com/agent-kit-startup/agent-kit-dev.git" }; + expect(classifyInstall(factory)).toBe("factory"); + expect(classifyInstall({ ...factory, git: wt })).toBe("factory"); + expect( + classifyInstall({ ...base, origin: null, cliPackageName: "@dadado/agent-kit-cli", git: wt }), + ).toBe("factory"); + expect(classifyInstall({ ...base, cliPackageName: "@missionkit/cli" })).toBe("factory"); + }); +}); + +describe("sanitizeRemote", () => { + it("strips credentials and keeps scp-style remotes", () => { + expect(sanitizeRemote("https://oauth2:tok@gitlab.example.com/g/r.git")).toBe( + "https://gitlab.example.com/g/r.git", + ); + expect(sanitizeRemote("git@github.com:acme/app.git")).toBe("git@github.com:acme/app.git"); + expect(sanitizeRemote(null)).toBeNull(); + }); +}); + +describe("inspectInstall (real git)", () => { + it("reads the manifest version, origin and worktree from git", async () => { + const repo = path.join(scratch, "repo"); + await initRepo(repo, "https://user:secret@example.com/acme/app.git"); + const record = await inspectInstall(repo, { home: scratch, tmpRoots: [] }); + expect(record).toMatchObject({ + path: repo, + remote: "https://example.com/acme/app.git", + kitVersion: "6.23.0", + kind: "repo", + }); + + const linked = path.join(scratch, "linked"); + await git(repo, "worktree", "add", "-q", linked); + expect((await inspectInstall(linked, { home: scratch, tmpRoots: [] }))?.kind).toBe("worktree"); + + const nested = path.join(repo, "examples", "consumer"); + await writeManifest(nested); + expect(await inspectInstall(nested, { home: scratch, tmpRoots: [] })).toMatchObject({ + kind: "fixture", + remote: null, + }); + + expect(await inspectInstall(path.join(scratch, "nothing"), { tmpRoots: [] })).toBeNull(); + }); + + it("classifies a temp-dir install as a fixture by default", async () => { + const repo = path.join(scratch, "tmp-repo"); + await initRepo(repo); + expect((await inspectInstall(repo))?.kind).toBe("fixture"); + }); + + it("marks a kit checkout without the factory remote by its CLI package", async () => { + const repo = path.join(scratch, "kit"); + await initRepo(repo, "https://github.com/someone/fork.git"); + await mkdir(path.join(repo, "packages", "cli"), { recursive: true }); + await writeFile( + path.join(repo, "packages", "cli", "package.json"), + JSON.stringify({ name: "@dadado/agent-kit-cli" }), + ); + expect((await inspectInstall(repo, { home: scratch, tmpRoots: [] }))?.kind).toBe("factory"); + }); +}); + +describe("scanForInstalls", () => { + it("finds installs within bounds and skips node_modules, hidden dirs and symlinks", async () => { + const root = path.join(scratch, "home"); + await writeManifest(root); // home-level ~/.cursor install + await writeManifest(path.join(root, "code", "app")); + await writeManifest(path.join(root, "code", "app", "node_modules", "pkg")); + await writeManifest(path.join(root, ".cache", "thing")); + await writeManifest(path.join(root, "code", "app", ".worktrees", "feat")); + await writeManifest(path.join(root, "code", "app", ".claude", "worktrees", "agent-1")); + await writeManifest(path.join(root, "a", "b", "c", "d", "e", "f", "deep")); + await mkdir(path.join(root, "links"), { recursive: true }); + await symlink(path.join(root, "code"), path.join(root, "links", "code-link")); + + const result = await scanForInstalls([root]); + expect(result.found).toEqual( + [ + root, + path.join(root, "code", "app"), + path.join(root, "code", "app", ".claude", "worktrees", "agent-1"), + path.join(root, "code", "app", ".worktrees", "feat"), + ].sort(), + ); + expect(result.truncated).toBe(false); + + const deep = await scanForInstalls([root], { maxDepth: 7 }); + expect(deep.found).toContain(path.join(root, "a", "b", "c", "d", "e", "f", "deep")); + + const capped = await scanForInstalls([root], { maxDirs: 2 }); + expect(capped.truncated).toBe(true); + expect(capped.visited).toBe(2); + }); +}); + +describe("feedInstallsRegistry", () => { + it("records an install into the configured file and skips folders without a manifest", async () => { + const previous = process.env.AGENT_KIT_INSTALLS_FILE; + process.env.AGENT_KIT_INSTALLS_FILE = file; + try { + const repo = path.join(scratch, "repo"); + await writeManifest(repo, "6.20.0"); + await feedInstallsRegistry(repo); + await feedInstallsRegistry(path.join(scratch, "not-installed")); + const rows = await listInstalls({ file }); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ path: repo, kitVersion: "6.20.0" }); + } finally { + process.env.AGENT_KIT_INSTALLS_FILE = previous; + } + }); + + it("fails open on a corrupt registry file", async () => { + const previous = process.env.AGENT_KIT_INSTALLS_FILE; + process.env.AGENT_KIT_INSTALLS_FILE = file; + try { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, "garbage"); + const repo = path.join(scratch, "repo"); + await writeManifest(repo); + await expect(feedInstallsRegistry(repo)).resolves.toBeUndefined(); + expect(await readFile(file, "utf8")).toBe("garbage"); + } finally { + process.env.AGENT_KIT_INSTALLS_FILE = previous; + } + }); +}); + +describe("agent-kit installs", () => { + it("collects every repeated --root", () => { + expect(collectRepeatedFlag(["scan", "--root", "a", "--root=b", "--json"], "root")).toEqual([ + "a", + "b", + ]); + }); + + it("scans several roots, then lists and prunes", async () => { + const previous = process.env.AGENT_KIT_INSTALLS_FILE; + process.env.AGENT_KIT_INSTALLS_FILE = file; + const out: string[] = []; + const write = process.stdout.write.bind(process.stdout); + process.stdout.write = ((chunk: string) => { + out.push(String(chunk)); + return true; + }) as typeof process.stdout.write; + try { + const a = path.join(scratch, "r1", "app"); + const b = path.join(scratch, "r2", "svc"); + await writeManifest(a); + await writeManifest(b); + const scanArgs = [ + "scan", + "--root", + path.join(scratch, "r1"), + "--root", + path.join(scratch, "r2"), + "--json", + ]; + await runCommand(installsCommand, { rawArgs: scanArgs }); + const scanned = JSON.parse(out.join("")); + expect(scanned.recorded.map((e: { path: string }) => e.path)).toEqual([a, b]); + + out.length = 0; + await runCommand(installsCommand, { rawArgs: ["list", "--json"] }); + const listed = JSON.parse(out.join("")); + expect(listed.file).toBe(file); + expect(listed.installs.map((e: { kind: string }) => e.kind)).toEqual(["fixture", "fixture"]); + + await rm(b, { recursive: true, force: true }); + out.length = 0; + await runCommand(installsCommand, { rawArgs: ["prune", "--json"] }); + expect(JSON.parse(out.join("")).removed.map((e: { path: string }) => e.path)).toEqual([b]); + } finally { + process.stdout.write = write; + process.env.AGENT_KIT_INSTALLS_FILE = previous; + } + }); +}); diff --git a/packages/cli/src/installs/scan.ts b/packages/cli/src/installs/scan.ts new file mode 100644 index 0000000..592ec38 --- /dev/null +++ b/packages/cli/src/installs/scan.ts @@ -0,0 +1,112 @@ +/** + * Bounded discovery of kit installs (`.cursor/agent-kit.json`) under a few + * roots. Read-only; never follows symlinks. + * + * Bounds: a depth cap, a cap on directories visited, and a skip list. Hidden + * directories are skipped (caches, `.git` internals, `.local`, `.npm`, …) + * except the worktree homes `.worktrees/` and `.claude/worktrees/`. + */ + +import type { Dirent } from "node:fs"; +import { readdir, realpath } from "node:fs/promises"; +import path from "node:path"; +import { hasInstallManifest } from "./inspect.js"; + +export const DEFAULT_SCAN_DEPTH = 5; +export const DEFAULT_SCAN_MAX_DIRS = 20_000; + +/** Directory names never descended into (besides hidden ones). */ +const SKIP_DIRS = new Set([ + "node_modules", + "bower_components", + "vendor", + "dist", + "build", + "target", + "out", + "coverage", + "__pycache__", + "venv", + "Library", + "Applications", + "snap", + "AppData", +]); + +/** Hidden directories that may hold worktrees, with the subpath to descend into. */ +const HIDDEN_WORKTREE_HOMES: Record = { + ".worktrees": ".worktrees", + ".claude": path.join(".claude", "worktrees"), +}; + +export interface ScanOptions { + maxDepth?: number; + maxDirs?: number; +} + +export interface ScanResult { + /** Real paths of directories holding `.cursor/agent-kit.json`, sorted. */ + found: string[]; + visited: number; + /** True when the directory cap stopped the walk early. */ + truncated: boolean; +} + +export async function scanForInstalls( + roots: readonly string[], + options: ScanOptions = {}, +): Promise { + const maxDepth = options.maxDepth ?? DEFAULT_SCAN_DEPTH; + const maxDirs = options.maxDirs ?? DEFAULT_SCAN_MAX_DIRS; + const found = new Set(); + const seen = new Set(); + let visited = 0; + let truncated = false; + + // Breadth-first so a capped walk still covers the shallow levels. + const queue: Array<{ dir: string; depth: number }> = []; + for (const root of roots) { + try { + queue.push({ dir: await realpath(path.resolve(root)), depth: 0 }); + } catch { + // Missing root: nothing to scan there. + } + } + + while (queue.length > 0) { + const next = queue.shift(); + if (!next) break; + const { dir, depth } = next; + if (seen.has(dir)) continue; + if (visited >= maxDirs) { + truncated = true; + break; + } + seen.add(dir); + visited += 1; + + if (await hasInstallManifest(dir)) found.add(dir); + if (depth >= maxDepth) continue; + + let entries: Dirent[]; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch { + continue; + } + for (const entry of entries) { + // Dirent.isDirectory() is false for symlinks: links are never followed. + if (!entry.isDirectory()) continue; + const name = entry.name; + if (name.startsWith(".")) { + const sub = HIDDEN_WORKTREE_HOMES[name]; + if (sub) queue.push({ dir: path.join(dir, sub), depth: depth + 1 }); + continue; + } + if (SKIP_DIRS.has(name)) continue; + queue.push({ dir: path.join(dir, name), depth: depth + 1 }); + } + } + + return { found: [...found].sort(), visited, truncated }; +} diff --git a/packages/cli/src/installs/store.ts b/packages/cli/src/installs/store.ts new file mode 100644 index 0000000..bf86cfe --- /dev/null +++ b/packages/cli/src/installs/store.ts @@ -0,0 +1,275 @@ +/** + * Machine install registry: `~/.config/agent-kit/installs.json` + * (ADR 2026-08-02 amend 2026-11-26). + * + * - An index, never the source of truth: the repo manifest + * (`.cursor/agent-kit.json`) wins on conflict, so every write takes the kit + * version from the manifest on disk, never from a caller's memory. + * - Never written inside a repo: the file lives in the machine config dir only. + * - Writes go through the same owner-file + stale-reclaim lock as the registry + * cache (`utils/dir-lock.ts`), and publish by temp file + rename, so two + * concurrent writers never lose an entry. + * - A path that no longer exists is pruned and never resurrected: every write + * re-reads the file under the lock and only adds rows it just verified. + */ + +import { randomUUID } from "node:crypto"; +import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import path from "node:path"; +import { acquireDirLock } from "../utils/dir-lock.js"; + +export const INSTALLS_SCHEMA_VERSION = 1 as const; +export const INSTALLS_FILENAME = "installs.json"; +/** Env override for the registry file (tests and scratch runs). */ +export const INSTALLS_FILE_ENV = "AGENT_KIT_INSTALLS_FILE"; + +/** + * - `repo`: a regular consumer checkout. + * - `worktree`: a linked git worktree (its git-dir differs from git-common-dir). + * - `fixture`: a manifest that is not its own repository (test fixtures, temp dirs). + * - `factory`: the kit's own repository and its worktrees (pseudo-consumer, + * ADR 2026-07-31); wins over `worktree`. + * - `home`: the home-level install under `~/.cursor`. + */ +export type InstallKind = "repo" | "worktree" | "fixture" | "factory" | "home"; + +export const INSTALL_KINDS: readonly InstallKind[] = [ + "repo", + "worktree", + "fixture", + "factory", + "home", +]; + +export interface InstallEntry { + /** Absolute real path of the directory holding `.cursor/agent-kit.json`. */ + path: string; + /** `origin` URL without credentials, or null when the repo has none. */ + remote: string | null; + /** `version` of the repo manifest when last seen. */ + kitVersion: string | null; + /** Version of the CLI that last recorded this row. */ + cliVersion: string; + /** ISO timestamp of the last time a CLI saw this install. */ + lastSeen: string; + kind: InstallKind; +} + +export interface InstallsFile { + schemaVersion: typeof INSTALLS_SCHEMA_VERSION; + installs: InstallEntry[]; + /** + * Rows this CLI cannot read (for example a kind a newer CLI added). Hidden + * from listings, written back verbatim by every write unless a recognized + * row for the same path replaces them. + */ + unrecognized?: unknown[]; +} + +export interface InstallsStoreOptions { + /** Registry file path; defaults to {@link resolveInstallsFile}. */ + file?: string; + /** Lock wait for writes (default 60 s; feeds pass a short one). */ + lockTimeoutMs?: number; +} + +export class InstallsRegistryError extends Error { + constructor( + message: string, + readonly file: string, + ) { + super(message); + this.name = "InstallsRegistryError"; + } +} + +/** + * `$AGENT_KIT_INSTALLS_FILE`, else `$XDG_CONFIG_HOME/agent-kit/installs.json` + * (absolute values only, per the XDG spec), else `~/.config/agent-kit/installs.json`. + */ +export function resolveInstallsFile( + env: NodeJS.ProcessEnv = process.env, + home: string = homedir(), +): string { + const override = env[INSTALLS_FILE_ENV]?.trim(); + if (override) return path.resolve(override); + const xdg = env.XDG_CONFIG_HOME?.trim(); + const configDir = xdg && path.isAbsolute(xdg) ? xdg : path.join(home, ".config"); + return path.join(configDir, "agent-kit", INSTALLS_FILENAME); +} + +function isInstallEntry(value: unknown): value is InstallEntry { + if (!value || typeof value !== "object") return false; + const e = value as Record; + return ( + typeof e.path === "string" && + path.isAbsolute(e.path) && + (e.remote === null || typeof e.remote === "string") && + (e.kitVersion === null || typeof e.kitVersion === "string") && + typeof e.cliVersion === "string" && + typeof e.lastSeen === "string" && + INSTALL_KINDS.includes(e.kind as InstallKind) + ); +} + +/** Parse the file body. Throws {@link InstallsRegistryError} when it is not ours to rewrite. */ +export function parseInstallsFile(raw: string, file: string): InstallsFile { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + throw new InstallsRegistryError( + `${file} is not valid JSON; move it aside and run \`agent-kit installs scan\` to rebuild it.`, + file, + ); + } + const body = parsed as { schemaVersion?: unknown; installs?: unknown }; + if (!body || typeof body !== "object" || !Array.isArray(body.installs)) { + throw new InstallsRegistryError( + `${file} has no installs list; move it aside and run \`agent-kit installs scan\` to rebuild it.`, + file, + ); + } + if (body.schemaVersion !== INSTALLS_SCHEMA_VERSION) { + throw new InstallsRegistryError( + `${file} has schemaVersion ${String(body.schemaVersion)}; this CLI understands ${INSTALLS_SCHEMA_VERSION} (newer CLI?). Left untouched.`, + file, + ); + } + const installs = body.installs.filter(isInstallEntry); + const unrecognized = body.installs.filter((row) => !isInstallEntry(row)); + return { schemaVersion: INSTALLS_SCHEMA_VERSION, installs, unrecognized }; +} + +/** Read the registry. A missing file is an empty registry; nothing is created. */ +export async function readInstalls(options: InstallsStoreOptions = {}): Promise { + const file = options.file ?? resolveInstallsFile(); + let raw: string; + try { + raw = await readFile(file, "utf8"); + } catch (err) { + if ((err as NodeJS.ErrnoException).code === "ENOENT") { + return { schemaVersion: INSTALLS_SCHEMA_VERSION, installs: [] }; + } + throw err; + } + return parseInstallsFile(raw, file); +} + +/** Entries sorted by path. Read-only: takes no lock and writes nothing. */ +export async function listInstalls(options: InstallsStoreOptions = {}): Promise { + const { installs } = await readInstalls(options); + return [...installs].sort((a, b) => a.path.localeCompare(b.path)); +} + +async function writeInstallsFile(file: string, body: InstallsFile): Promise { + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.${randomUUID()}.tmp`; + const known = new Set(body.installs.map((e) => e.path)); + const kept = (body.unrecognized ?? []).filter((row) => { + const rowPath = (row as { path?: unknown } | null)?.path; + return !(typeof rowPath === "string" && known.has(rowPath)); + }); + const sorted = { + schemaVersion: INSTALLS_SCHEMA_VERSION, + installs: [...[...body.installs].sort((a, b) => a.path.localeCompare(b.path)), ...kept], + }; + try { + await writeFile(tmp, `${JSON.stringify(sorted, null, 2)}\n`, "utf8"); + await rename(tmp, file); + } catch (err) { + await rm(tmp, { force: true }).catch(() => undefined); + throw err; + } +} + +/** + * Read-modify-write under the lock. `mutate` sees the file as it is on disk + * now (never a snapshot taken before the lock) and returns the new list. + */ +async function mutateInstalls( + options: InstallsStoreOptions, + mutate: ( + current: InstallEntry[], + ) => Promise<{ installs: InstallEntry[]; result: T; changed: boolean }>, +): Promise { + const file = options.file ?? resolveInstallsFile(); + const unlock = await acquireDirLock(file, { + timeoutMs: options.lockTimeoutMs, + timeoutMessage: (target) => + `Timed out waiting for the install registry lock on ${target}. Another agent-kit process may be stuck.`, + }); + try { + const current = await readInstalls({ file }); + const { installs, result, changed } = await mutate(current.installs); + if (changed) { + await writeInstallsFile(file, { + schemaVersion: INSTALLS_SCHEMA_VERSION, + installs, + unrecognized: current.unrecognized, + }); + } + return result; + } finally { + await unlock(); + } +} + +/** A row to record; `lastSeen` defaults to now. */ +export type InstallRecord = Omit & { lastSeen?: string }; + +export interface UpsertOptions extends InstallsStoreOptions { + /** + * Re-checked under the lock for each record: a row whose install vanished + * since it was inspected is not written (prune never resurrects). + */ + stillInstalled?: (installPath: string) => Promise; + now?: () => Date; +} + +/** Insert or replace rows by path. Returns the rows written. */ +export async function upsertInstalls( + records: readonly InstallRecord[], + options: UpsertOptions = {}, +): Promise { + if (records.length === 0) return []; + const now = (options.now ?? (() => new Date()))().toISOString(); + return mutateInstalls(options, async (current) => { + const byPath = new Map(current.map((e) => [e.path, e])); + const written: InstallEntry[] = []; + for (const record of records) { + if (options.stillInstalled && !(await options.stillInstalled(record.path))) continue; + const entry: InstallEntry = { + path: record.path, + remote: record.remote, + kitVersion: record.kitVersion, + cliVersion: record.cliVersion, + lastSeen: record.lastSeen ?? now, + kind: record.kind, + }; + if (!isInstallEntry(entry)) continue; + byPath.set(entry.path, entry); + written.push(entry); + } + return { installs: [...byPath.values()], result: written, changed: written.length > 0 }; + }); +} + +export interface PruneOptions extends InstallsStoreOptions { + /** True when the row's install still exists (default: manifest present). */ + stillInstalled: (installPath: string) => Promise; +} + +/** Drop rows whose install is gone. Returns the removed rows. */ +export async function pruneInstalls(options: PruneOptions): Promise { + return mutateInstalls(options, async (current) => { + const kept: InstallEntry[] = []; + const removed: InstallEntry[] = []; + for (const entry of current) { + if (await options.stillInstalled(entry.path)) kept.push(entry); + else removed.push(entry); + } + return { installs: kept, result: removed, changed: removed.length > 0 }; + }); +} diff --git a/packages/cli/src/invariants/shell-guard.test.ts b/packages/cli/src/invariants/shell-guard.test.ts index eda0635..386a117 100644 --- a/packages/cli/src/invariants/shell-guard.test.ts +++ b/packages/cli/src/invariants/shell-guard.test.ts @@ -695,3 +695,106 @@ describe("pr-merge-protected-base (gh pr merge / glab mr merge)", () => { } }); }); + +describe("guard narrowing and allowed-form hints (ADR amend 2026-11-26)", () => { + const restore = ["git", "restore"].join(" "); + + it("allows the index-only restore and keeps the worktree forms denied", () => { + for (const cmd of [ + `${restore} --staged README.md`, + `${restore} -S src/a.ts src/b.ts`, + `${restore} --staged --source=HEAD~1 README.md`, + `git add -A && ${restore} --staged .env`, + ]) { + expect(evaluateShellCommand(cmd).permission, cmd).toBe("allow"); + } + for (const cmd of [ + `${restore} README.md`, + `${restore} .`, + `${restore} --staged --worktree README.md`, + `${restore} -SW README.md`, + `${restore} --worktree README.md`, + `${restore} --source=HEAD README.md`, + ]) { + expect(evaluateShellCommand(cmd).rule, cmd).toBe("git-restore"); + } + }); + + it("denies git checkout --theirs / --ours with or without --", () => { + for (const cmd of [ + "git checkout --theirs -- src/a.ts", + "git checkout --ours src/a.ts", + "git checkout --theirs .", + ]) { + expect(evaluateShellCommand(cmd).rule, cmd).toBe("git-checkout-path"); + } + expect(evaluateShellCommand("git checkout feat/x").permission).toBe("allow"); + }); + + const merge = (forge: "gh" | "glab", rest: string) => + forge === "gh" ? `gh pr ${"merge"} ${rest}` : `glab mr ${"merge"} ${rest}`; + + const cases: Array<{ + rule: string; + cmd: string; + opts?: Parameters[1]; + hint: string; + }> = [ + { rule: "git-checkout-path", cmd: "git checkout -- src/a.ts", hint: "`git stash`" }, + { rule: "git-restore", cmd: `${restore} src/a.ts`, hint: "`git restore --staged `" }, + { rule: "git-reset-hard", cmd: "git reset --hard HEAD", hint: "`git reset --keep `" }, + { rule: "git-clean-fd", cmd: "git clean -fd", hint: "`git clean -nd`" }, + { + rule: "public-repo-direct-write", + cmd: "git push https://github.com/agent-kit-startup/agent-kit.git staging", + hint: "`scripts/sync-public.mjs`", + }, + { rule: "git-push-main", cmd: "git push origin main", hint: "`git push -u origin `" }, + { + rule: "pr-merge-protected-base", + cmd: merge("gh", "12 --squash"), + opts: { prMergeBases: {} }, + hint: "-R owner/repo`", + }, + ]; + + it("covers every rule with a message test", () => { + expect(new Set(cases.map((c) => c.rule))).toEqual(new Set(SHELL_DENY_RULES.map((r) => r.id))); + }); + + for (const c of cases) { + it(`${c.rule}: the denial names the allowed form`, () => { + const r = evaluateShellCommand(c.cmd, c.opts); + expect(r.rule).toBe(c.rule); + expect(r.agent_message).toContain("Instead: "); + expect(r.agent_message).toContain(c.hint); + expect(r.agent_message).toContain("agent-kit guard shell"); + }); + } + + it("an unresolved glab merge names the glab -R host/group/repo form only", () => { + const cmd = merge("glab", "7"); + const r = evaluateShellCommand(cmd, { prMergeBases: {} }); + expect(r.rule).toBe("pr-merge-protected-base"); + expect(r.agent_message).toContain(`\`glab mr ${"merge"} -R host/group/repo\``); + expect(r.agent_message).not.toContain(`\`gh pr ${"merge"} -R owner/repo\``); + }); + + it("a merge looped over $n names the literal -R form", () => { + const cmd = `for n in 1 2; do ${merge("gh", "$n --squash")}; done`; + const r = evaluateShellCommand(cmd); + expect(r.rule).toBe("pr-merge-protected-base"); + expect(r.agent_message).toContain(`\`gh pr ${"merge"} -R owner/repo\``); + }); + + it("a resolved protected base names the staging route, not the -R form", () => { + const cmd = merge("gh", "12 --squash"); + const [target] = prMergeTargets(cmd); + const r = evaluateShellCommand(cmd, { + prMergeBases: { [prMergeKey(target as NonNullable)]: "main" }, + }); + expect(r.rule).toBe("pr-merge-protected-base"); + expect(r.agent_message).toContain("merge only into staging"); + expect(r.agent_message).not.toContain("-R owner/repo"); + }); +}); diff --git a/packages/cli/src/invariants/shell-guard.ts b/packages/cli/src/invariants/shell-guard.ts index f4e3902..1faf773 100644 --- a/packages/cli/src/invariants/shell-guard.ts +++ b/packages/cli/src/invariants/shell-guard.ts @@ -556,6 +556,8 @@ export const SHELL_DENY_RULES: Array<{ id: string; description: string; test: (command: string, opts?: ShellGuardOptions) => boolean; + /** What to run instead; named in every denial (ADR amend 2026-11-26). */ + allowed: (command: string, opts?: ShellGuardOptions) => string; }> = [ { id: "git-checkout-path", @@ -567,18 +569,29 @@ export const SHELL_DENY_RULES: Array<{ if (/\s--(?:\s|$)/.test(head)) return true; // git checkout . if (/\scheckout\s+\.(?:\s|$)/.test(head)) return true; + // git checkout --theirs|--ours overwrites the worktree copy + if (/\s--(?:theirs|ours)(?:\s|$)/.test(head)) return true; return false; }), + allowed: () => + "`git switch ` to change branches, `git stash` to set edits aside, `git restore --staged ` to unstage; resolve a conflict by editing the file", }, { id: "git-restore", - description: "git restore discards working-tree edits", - test: (cmd) => anyHeadMatches(cmd, /^(?:[\w./-]+\/)?git\s+restore\b/), + description: "git restore on the worktree discards working-tree edits", + test: (cmd) => + shellInvocationHeads(cmd).some( + (head) => /^(?:[\w./-]+\/)?git\s+restore\b/.test(head) && !restoreIsIndexOnly(head), + ), + allowed: () => + "`git restore --staged ` (index only, keeps the edit) or `git stash` to set edits aside", }, { id: "git-reset-hard", description: "git reset --hard destroys uncommitted work", test: (cmd) => anyHeadMatches(cmd, /^(?:[\w./-]+\/)?git\s+reset\b.*--hard\b/), + allowed: () => + "`git stash` to set edits aside, `git reset --keep ` (refuses to drop local edits) or `git reset --soft `", }, { id: "git-clean-fd", @@ -593,6 +606,8 @@ export const SHELL_DENY_RULES: Array<{ const hasD = tokens.some((t) => shortBundle(t) && t.includes("d")); return hasForce && hasD; }), + allowed: () => + "`git clean -nd` to list what would go, then ask the operator before deleting untracked files", }, { id: "public-repo-direct-write", @@ -604,6 +619,8 @@ export const SHELL_DENY_RULES: Array<{ const head = canonicalGitHead(segment); return pushTargetsPublicRepo(head, opts?.remotes) || ghTargetsPublicRepo(head); }), + allowed: () => + "ship through /git-staging and /git-prod; the public repo is written by `scripts/sync-public.mjs` in CI", }, { id: "git-push-main", @@ -623,6 +640,8 @@ export const SHELL_DENY_RULES: Array<{ } return false; }), + allowed: () => + "push a working branch (`git push -u origin `) and open a PR into staging (/git-staging); main moves only through /git-prod", }, { // Claude settings allow `gh pr merge` / `glab mr merge` so the /git-staging merge @@ -650,9 +669,49 @@ export const SHELL_DENY_RULES: Array<{ return typeof base !== "string" || isProtectedBranch(base); }); }, + allowed: prMergeAllowedHint, }, ]; +/** + * `git restore` that only resets the index: `--staged` / `-S` without + * `--worktree` / `-W` (short flags may be bundled, `-SW`). + */ +export function restoreIsIndexOnly(head: string): boolean { + const tokens = head.split(/\s+/); + const shortBundle = (t: string) => /^-[a-zA-Z]+$/.test(t); + const staged = tokens.some((t) => t === "--staged" || (shortBundle(t) && t.includes("S"))); + const worktree = tokens.some((t) => t === "--worktree" || (shortBundle(t) && t.includes("W"))); + return staged && !worktree; +} + +/** + * The merge hint: a merge the guard could not resolve (no literal target, or + * gh/glab could not read the PR/MR) names the `-R` form of its forge; a + * resolved protected base names the staging route. + */ +function prMergeAllowedHint(command: string, opts?: ShellGuardOptions): string { + const ghForm = "`gh pr merge -R owner/repo`"; + const glabForm = "`glab mr merge -R host/group/repo`"; + const staging = "merge only into staging (/git-staging); main moves through /git-prod"; + if (forgeApiMergeCall(command)) { + return `a literal ${ghForm} or ${glabForm} at the head of its own segment; ${staging}`; + } + const bases = opts?.prMergeBases ?? {}; + const unresolved = shellSegments(command).filter((segment) => { + if (!PR_MERGE_CALL_RE.test(segment)) return false; + const target = literalPrMergeTarget(segment); + return target === null || typeof bases[prMergeKey(target)] !== "string"; + }); + if (unresolved.length === 0) return staging; + const forms = [ + unresolved.some((seg) => /\bgh\s+pr\s+merge\b/.test(seg)) ? ghForm : null, + unresolved.some((seg) => /\bglab\s+mr\s+merge\b/.test(seg)) ? glabForm : null, + ].filter((f): f is string => f !== null); + const named = forms.length > 0 ? forms.join(" or ") : `${ghForm} or ${glabForm}`; + return `name the PR/MR and its repo literally, at the head of its own segment, so the base resolves: ${named} (check \`gh auth status\` / \`glab auth status\`); ${staging}`; +} + export function evaluateShellCommand( command: string, opts: ShellGuardOptions = {}, @@ -664,7 +723,7 @@ export function evaluateShellCommand( for (const rule of SHELL_DENY_RULES) { // Raw command: rules split on newlines before normalizing each segment. if (rule.test(command, opts)) { - const agent_message = `Denied by ${CITE}: ${rule.description} (rule \`${rule.id}\`). Use /git-staging; never discard human hunks or push protected branches from the agent.`; + const agent_message = `Denied by ${CITE}: ${rule.description} (rule \`${rule.id}\`). Instead: ${rule.allowed(command, opts)}. Never discard human hunks or push protected branches from the agent.`; return { permission: "deny", rule: rule.id, diff --git a/packages/cli/src/lifecycle/check-updates.test.ts b/packages/cli/src/lifecycle/check-updates.test.ts index 2bc4db9..526de39 100644 --- a/packages/cli/src/lifecycle/check-updates.test.ts +++ b/packages/cli/src/lifecycle/check-updates.test.ts @@ -1,17 +1,22 @@ -import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { + CLI_BIN_NAMES, checkForUpdates, checkRunningCliVsNpmLatest, compareSemver, + fetchLatestCliNpmVersion, fetchLatestNpmDistTag, isFactoryOrDevRegistry, + type NpmFetch, normalizeSemver, + npmLatestUrl, pickLatestSemverTag, readUpdateApplyPrefs, readUpdateCheckPrefs, + stampLastCheckedAt, warnIfRunningCliBehindNpm, } from "./check-updates.js"; import { KIT_VERSION } from "./version.js"; @@ -66,9 +71,9 @@ describe("pickLatestSemverTag", () => { }); describe("readUpdateCheckPrefs / readUpdateApplyPrefs", () => { - it("defaults updateCheck to opt-in false", () => { + it("defaults updateCheck to on (check-only); only an explicit false turns it off", () => { expect(readUpdateCheckPrefs(null)).toEqual({ - enabled: false, + enabled: true, intervalDays: 7, lastCheckedAt: null, }); @@ -77,6 +82,8 @@ describe("readUpdateCheckPrefs / readUpdateApplyPrefs", () => { intervalDays: 3, lastCheckedAt: null, }); + expect(readUpdateCheckPrefs({ updateCheck: {} }).enabled).toBe(true); + expect(readUpdateCheckPrefs({ updateCheck: { enabled: false } }).enabled).toBe(false); }); it("defaults updateApply.auto to false", () => { @@ -221,6 +228,7 @@ describe("checkForUpdates", () => { }); const result = await checkForUpdates(cwd, { respectPrefs: true, + env: {}, latestVersion: "9.0.0", }); expect(result.status).toBe("skipped-interval"); @@ -318,6 +326,30 @@ describe("checkRunningCliVsNpmLatest", () => { expect(fetchLatest).not.toHaveBeenCalled(); }); + it("is on by default with no config, and off under CI or the env opt-out (no fetch)", async () => { + const cwd = await mkdtemp(path.join(tmpdir(), "ak-cli-ver-")); + temps.push(cwd); + const fetchLatest = vi.fn(async () => "999.0.0"); + const on = await checkRunningCliVsNpmLatest(cwd, { respectPrefs: true, env: {}, fetchLatest }); + expect(on.status).toBe("behind"); + expect(fetchLatest).toHaveBeenCalledTimes(1); + for (const env of [ + { CI: "true" }, + { AGENT_KIT_NO_UPDATE_CHECK: "1" }, + { NO_UPDATE_NOTIFIER: "1" }, + ]) { + const off = await checkRunningCliVsNpmLatest(cwd, { respectPrefs: true, env, fetchLatest }); + expect(off.status).toBe("skipped-disabled"); + } + expect(fetchLatest).toHaveBeenCalledTimes(1); + const notOff = await checkRunningCliVsNpmLatest(cwd, { + respectPrefs: true, + env: { CI: "false", AGENT_KIT_NO_UPDATE_CHECK: "0" }, + fetchLatest, + }); + expect(notOff.status).toBe("behind"); + }); + it("skips within interval (no fetch)", async () => { const cwd = await mkdtemp(path.join(tmpdir(), "ak-cli-ver-")); temps.push(cwd); @@ -329,7 +361,11 @@ describe("checkRunningCliVsNpmLatest", () => { }, }); const fetchLatest = vi.fn(async () => "9.9.9"); - const result = await checkRunningCliVsNpmLatest(cwd, { respectPrefs: true, fetchLatest }); + const result = await checkRunningCliVsNpmLatest(cwd, { + respectPrefs: true, + env: {}, + fetchLatest, + }); expect(result.status).toBe("skipped-interval"); expect(fetchLatest).not.toHaveBeenCalled(); }); @@ -404,3 +440,60 @@ describe("checkRunningCliVsNpmLatest", () => { await expect(fetchLatestNpmDistTag()).resolves.toBeNull(); }); }); + +describe("dual-name npm latest (@dadado/agent-kit-cli + @missionkit/cli)", () => { + function stubRegistry(versions: Record): NpmFetch { + return async (url) => { + const hit = Object.entries(versions).find(([name]) => url === npmLatestUrl(name)); + const version = hit?.[1] ?? null; + return version + ? { ok: true, json: async () => ({ version }) } + : { ok: false, json: async () => ({}) }; + }; + } + + it("builds the scoped abbreviated URL", () => { + expect(npmLatestUrl("@missionkit/cli")).toBe( + "https://registry.npmjs.org/@missionkit%2Fcli/latest", + ); + expect(CLI_BIN_NAMES).toEqual(["agent-kit", "missionkit"]); + }); + + it("uses the only name that is published (the other 404s)", async () => { + await expect( + fetchLatestCliNpmVersion(stubRegistry({ "@dadado/agent-kit-cli": "6.22.1" })), + ).resolves.toEqual({ packageName: "@dadado/agent-kit-cli", version: "6.22.1" }); + }); + + it("picks the newer of both names", async () => { + await expect( + fetchLatestCliNpmVersion( + stubRegistry({ "@dadado/agent-kit-cli": "6.22.1", "@missionkit/cli": "7.0.0" }), + ), + ).resolves.toEqual({ packageName: "@missionkit/cli", version: "7.0.0" }); + }); + + it("fails open to null when npm is unreachable", async () => { + await expect( + fetchLatestCliNpmVersion(async () => { + throw new Error("ENOTFOUND"); + }), + ).resolves.toBeNull(); + }); +}); + +describe("stampLastCheckedAt", () => { + it("never writes an enabled default (an explicit true turns on the legacy nudge)", async () => { + const cwd = await mkdtemp(path.join(tmpdir(), "ak-stamp-")); + try { + await stampLastCheckedAt(cwd); + const written = JSON.parse( + await readFile(path.join(cwd, ".cursor", "context", "config.json"), "utf8"), + ) as { updateCheck: Record }; + expect(written.updateCheck).not.toHaveProperty("enabled"); + expect(typeof written.updateCheck.lastCheckedAt).toBe("string"); + } finally { + await rm(cwd, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/cli/src/lifecycle/check-updates.ts b/packages/cli/src/lifecycle/check-updates.ts index 24e5ae7..bbe94bb 100644 --- a/packages/cli/src/lifecycle/check-updates.ts +++ b/packages/cli/src/lifecycle/check-updates.ts @@ -51,12 +51,65 @@ export interface UpdateApplyPrefs { auto: boolean; } +/** + * The check is on by default and only ever notifies (ADR 2026-07-27 Amend + * 2026-11-26); `updateCheck.enabled: false`, `CI` or the env opt-out turn it off. + */ const DEFAULT_UPDATE_CHECK: UpdateCheckPrefs = { - enabled: false, + enabled: true, intervalDays: 7, lastCheckedAt: null, }; +/** Env opt-out for every update check (set to anything but `0`/`false`). */ +export const UPDATE_CHECK_OPT_OUT_ENV = "AGENT_KIT_NO_UPDATE_CHECK"; +/** The common update-notifier convention, honored too. */ +export const UPDATE_NOTIFIER_OPT_OUT_ENV = "NO_UPDATE_NOTIFIER"; + +function envFlagSet(value: string | undefined): boolean { + if (value === undefined) return false; + const v = value.trim().toLowerCase(); + return v !== "" && v !== "0" && v !== "false"; +} + +/** Why the update check is off for this env (and config), or null when it may run. */ +export function updateCheckOptOut( + env: NodeJS.ProcessEnv, + config: unknown, +): "ci" | "env" | "config" | null { + if (envFlagSet(env.CI)) return "ci"; + if (envFlagSet(env[UPDATE_CHECK_OPT_OUT_ENV]) || envFlagSet(env[UPDATE_NOTIFIER_OPT_OUT_ENV])) { + return "env"; + } + if (config && typeof config === "object" && !Array.isArray(config)) { + const uc = (config as Record).updateCheck; + if (uc && typeof uc === "object" && (uc as Record).enabled === false) { + return "config"; + } + } + return null; +} + +/** + * Whether an update check may reach the network: off under `CI`, with the env + * opt-out (`AGENT_KIT_NO_UPDATE_CHECK` or `NO_UPDATE_NOTIFIER`) and with an + * explicit `updateCheck.enabled: false`. An absent key does not opt out. + */ +export function updateCheckAllowed(env: NodeJS.ProcessEnv, config: unknown): boolean { + return updateCheckOptOut(env, config) === null; +} + +function updateCheckOptOutMessage(reason: "ci" | "env" | "config"): string { + switch (reason) { + case "ci": + return "Update check is off under CI."; + case "env": + return `Update check is off (${UPDATE_CHECK_OPT_OUT_ENV} or ${UPDATE_NOTIFIER_OPT_OUT_ENV} is set).`; + default: + return "updateCheck.enabled is false in .cursor/context/config.json (the check is on by default and only notifies)."; + } +} + const DEFAULT_UPDATE_APPLY: UpdateApplyPrefs = { auto: false, }; @@ -137,15 +190,47 @@ export async function fetchLatestPublicVersion( export const NPM_CLI_LATEST_URL = "https://registry.npmjs.org/@dadado%2Fagent-kit-cli/latest"; /** - * Resolve npm `dist-tags.latest` for this CLI package. Fail-open: returns null - * on network/parse errors. Tests inject `latestVersion` and never call this. + * Every npm name this CLI ships (or will ship) under, with its binary. The + * Mission Kit rename (plan `missionkit-rename-2026-11-22` r2) owns the package + * itself; checks accept both names until then. */ -export async function fetchLatestNpmDistTag(): Promise { +export const CLI_NPM_PACKAGES = [ + { name: "@dadado/agent-kit-cli", bin: "agent-kit" }, + { name: "@missionkit/cli", bin: "missionkit" }, +] as const; + +export type CliNpmPackageName = (typeof CLI_NPM_PACKAGES)[number]["name"]; + +/** Binary names a global CLI install can expose on PATH, in lookup order. */ +export const CLI_BIN_NAMES: readonly string[] = CLI_NPM_PACKAGES.map((pkg) => pkg.bin); + +/** npm abbreviated `latest` document URL for a (scoped) package name. */ +export function npmLatestUrl(packageName: string): string { + return `https://registry.npmjs.org/${packageName.replace("/", "%2F")}/latest`; +} + +/** Minimal fetch shape so tests can stub the npm registry without globals. */ +export type NpmFetch = ( + url: string, + init: { method: string; headers: Record; signal: AbortSignal }, +) => Promise<{ ok: boolean; json: () => Promise }>; + +const globalNpmFetch: NpmFetch = (url, init) => fetch(url, init); + +/** + * npm `dist-tags.latest` of one package. Fail-open: null on a 404 (the name is + * not published yet), network errors and unparsable bodies. + */ +export async function fetchLatestNpmVersion( + packageName: string, + fetchImpl: NpmFetch = globalNpmFetch, + timeoutMs = 8_000, +): Promise { try { - const res = await fetch(NPM_CLI_LATEST_URL, { + const res = await fetchImpl(npmLatestUrl(packageName), { method: "GET", headers: { accept: "application/json" }, - signal: AbortSignal.timeout(8_000), + signal: AbortSignal.timeout(timeoutMs), }); if (!res.ok) return null; const body: unknown = await res.json(); @@ -157,6 +242,47 @@ export async function fetchLatestNpmDistTag(): Promise { } } +export interface CliNpmLatest { + /** The package whose `latest` is highest. */ + packageName: CliNpmPackageName; + version: string; +} + +/** + * Highest npm `latest` across every CLI package name (queried in parallel; a + * name that is not published answers nothing). Null when neither answers. + * Fail-open, never throws. Reused by the doctor install check and the update + * notice. + */ +export async function fetchLatestCliNpmVersion( + fetchImpl: NpmFetch = globalNpmFetch, + timeoutMs = 8_000, +): Promise { + const results = await Promise.all( + CLI_NPM_PACKAGES.map(async (pkg) => ({ + packageName: pkg.name, + version: await fetchLatestNpmVersion(pkg.name, fetchImpl, timeoutMs), + })), + ); + let best: CliNpmLatest | null = null; + for (const result of results) { + if (!result.version) continue; + if (!best || compareSemver(result.version, best.version) > 0) { + best = { packageName: result.packageName, version: result.version }; + } + } + return best; +} + +/** + * Resolve npm `dist-tags.latest` for `@dadado/agent-kit-cli` only (release + * convergence polls this exact package). Fail-open: returns null on + * network/parse errors. Tests inject `latestVersion` and never call this. + */ +export async function fetchLatestNpmDistTag(): Promise { + return fetchLatestNpmVersion(CLI_NPM_PACKAGES[0].name); +} + export function readUpdateCheckPrefs(config: unknown): UpdateCheckPrefs { if (!config || typeof config !== "object" || Array.isArray(config)) { return { ...DEFAULT_UPDATE_CHECK }; @@ -171,7 +297,7 @@ export function readUpdateCheckPrefs(config: unknown): UpdateCheckPrefs { ? uc.intervalDays : DEFAULT_UPDATE_CHECK.intervalDays; return { - enabled: uc.enabled === true, + enabled: uc.enabled !== false, intervalDays, lastCheckedAt: typeof uc.lastCheckedAt === "string" ? uc.lastCheckedAt : null, }; @@ -198,8 +324,10 @@ export async function stampLastCheckedAt(cwd: string): Promise { existing.updateCheck && typeof existing.updateCheck === "object" ? { ...(existing.updateCheck as Record) } : {}; + // No `enabled` default is written: an explicit `true` is what turns on the + // legacy per-repo sessionStart nudge, and a stamp must not flip it. existing.updateCheck = { - ...DEFAULT_UPDATE_CHECK, + intervalDays: DEFAULT_UPDATE_CHECK.intervalDays, ...prev, lastCheckedAt: new Date().toISOString(), }; @@ -207,8 +335,10 @@ export async function stampLastCheckedAt(cwd: string): Promise { } export interface CheckForUpdatesOptions { - /** When true, honor updateCheck.enabled + intervalDays from config. */ + /** When true, honor updateCheck.enabled + intervalDays from config, CI and the env opt-out. */ respectPrefs?: boolean; + /** Env read for CI and the opt-out (default process.env). */ + env?: NodeJS.ProcessEnv; /** Persist updateCheck.lastCheckedAt after a network check. */ stamp?: boolean; /** Override public registry URL for tag lookup (HTTPS only). */ @@ -397,7 +527,8 @@ export async function checkForUpdates( if (options.respectPrefs) { const config = await loadContextConfig(cwd); const prefs = readUpdateCheckPrefs(config); - if (!prefs.enabled) { + const optOut = updateCheckOptOut(options.env ?? process.env, config); + if (optOut) { return { status: "skipped-disabled", installedVersion: manifest.version, @@ -405,8 +536,7 @@ export async function checkForUpdates( registryUrl, registryRef, applyRecommended: false, - message: - "updateCheck.enabled is false (opt-in). Set true in .cursor/context/config.json to nudge.", + message: updateCheckOptOutMessage(optOut), }; } if (!intervalElapsed(prefs.lastCheckedAt, prefs.intervalDays)) { @@ -532,8 +662,10 @@ export interface RunningCliCheckResult { } export interface CheckRunningCliOptions { - /** When true (default at install/doctor), honor updateCheck.enabled + intervalDays. */ + /** When true (default at install/doctor), honor updateCheck.enabled + intervalDays, CI and the env opt-out. */ respectPrefs?: boolean; + /** Env read for CI and the opt-out (default process.env). */ + env?: NodeJS.ProcessEnv; /** Persist updateCheck.lastCheckedAt after a network check. */ stamp?: boolean; /** Injected npm latest (tests). Skips fetch when set. */ @@ -549,7 +681,7 @@ function runningCliBehindMessage(running: string, latest: string): string { /** * Compare this process's KIT_VERSION to npm dist-tags.latest. * Independent of agent-kit.json (install may have no manifest yet). - * Never applies L0. Reuses updateCheck opt-in + interval so the default is no network. + * Never applies L0. Reuses the updateCheck gate (on by default, check-only) + interval. */ export async function checkRunningCliVsNpmLatest( cwd: string, @@ -560,13 +692,13 @@ export async function checkRunningCliVsNpmLatest( if (options.respectPrefs) { const config = await loadContextConfig(cwd); const prefs = readUpdateCheckPrefs(config); - if (!prefs.enabled) { + const optOut = updateCheckOptOut(options.env ?? process.env, config); + if (optOut) { return { status: "skipped-disabled", runningVersion: running, latestVersion: null, - message: - "updateCheck.enabled is false (opt-in). Set true in .cursor/context/config.json to nudge.", + message: updateCheckOptOutMessage(optOut), }; } if (!intervalElapsed(prefs.lastCheckedAt, prefs.intervalDays)) { @@ -586,7 +718,7 @@ export async function checkRunningCliVsNpmLatest( } else if (options.fetchLatest) { latest = await options.fetchLatest(); } else { - latest = await fetchLatestNpmDistTag(); + latest = (await fetchLatestCliNpmVersion())?.version ?? null; } } catch (err) { const msg = err instanceof Error ? err.message : String(err); @@ -611,7 +743,7 @@ export async function checkRunningCliVsNpmLatest( status: "error", runningVersion: running, latestVersion: null, - message: "No semver on npm dist-tags.latest for @dadado/agent-kit-cli.", + message: `No semver on npm dist-tags.latest for ${CLI_NPM_PACKAGES.map((pkg) => pkg.name).join(" or ")}.`, }; } @@ -662,6 +794,7 @@ export async function warnIfRunningCliBehindNpm( try { const result = await checkRunningCliVsNpmLatest(cwd, { respectPrefs: options.respectPrefs ?? true, + env: options.env, stamp: options.stamp ?? true, latestVersion: options.latestVersion, fetchLatest: options.fetchLatest, diff --git a/packages/cli/src/lifecycle/diff.ts b/packages/cli/src/lifecycle/diff.ts index 6c73643..834df39 100644 --- a/packages/cli/src/lifecycle/diff.ts +++ b/packages/cli/src/lifecycle/diff.ts @@ -76,10 +76,13 @@ export async function diffAgainstRegistry( ); }; - const { pairs, missingSkills } = await managedPairs(registryRoot, manifest); + const { pairs, missingSkills, missingPacks } = await managedPairs(registryRoot, manifest); for (const { sourceRel, targetRel } of pairs) { await pushUnique(sourceRel, targetRel); } + for (const id of missingPacks) { + entries.push({ path: `pack:${id}`, status: "missing-registry" }); + } for (const id of missingSkills) { entries.push({ path: `skill:${id}`, status: "missing-registry" }); } diff --git a/packages/cli/src/lifecycle/fixtures/agent-kit-manifest-v3.0.0.json b/packages/cli/src/lifecycle/fixtures/agent-kit-manifest-v3.0.0.json new file mode 100644 index 0000000..c909698 --- /dev/null +++ b/packages/cli/src/lifecycle/fixtures/agent-kit-manifest-v3.0.0.json @@ -0,0 +1,12 @@ +{ + "schemaVersion": 1, + "version": "3.0.0", + "profile": "default", + "packs": ["clean-code", "gestao-contexto", "gestao-projeto"], + "protected": [".cursor/HANDOFF.md", ".cursor/plans/**", ".cursor/memory/**"], + "registry": { + "url": "https://github.com/agent-kit-startup/agent-kit", + "ref": "main" + }, + "installedAt": "2026-04-05T17:08:29.000Z" +} diff --git a/packages/cli/src/lifecycle/legacy-pack-ids.test.ts b/packages/cli/src/lifecycle/legacy-pack-ids.test.ts new file mode 100644 index 0000000..6b8d47d --- /dev/null +++ b/packages/cli/src/lifecycle/legacy-pack-ids.test.ts @@ -0,0 +1,55 @@ +import { mkdtemp, readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { parseAgentKitManifest } from "../manifest/index.js"; +import type { AgentKitManifest } from "../manifest/types.js"; +import { diffAgainstRegistry } from "./diff.js"; +import { syncFromManifest } from "./sync.js"; +import { managedPairs } from "./targets.js"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const KIT_ROOT = path.resolve(here, "../../../.."); + +/** A manifest written by kit v3.0.0, before the L1 pack ids became English. */ +async function v3Manifest(extraPacks: string[] = []): Promise { + const raw = JSON.parse( + await readFile(path.join(here, "fixtures/agent-kit-manifest-v3.0.0.json"), "utf8"), + ); + raw.packs = [...raw.packs, ...extraPacks]; + return parseAgentKitManifest(raw); +} + +describe("legacy pack ids in a v3.0.0 manifest", () => { + it("managedPairs resolves legacy ids and lists an unknown id instead of throwing", async () => { + const manifest = await v3Manifest(["ghost-pack"]); + const { pairs, missingPacks } = await managedPairs(KIT_ROOT, manifest); + const canonical = await managedPairs(KIT_ROOT, { + ...manifest, + packs: ["clean-code", "context-management", "project-management"], + }); + expect(missingPacks).toEqual(["ghost-pack"]); + expect(pairs).toEqual(canonical.pairs); + }); + + it("diffAgainstRegistry reports an unknown pack as a missing-registry row", async () => { + const project = await mkdtemp(path.join(tmpdir(), "ak-legacy-pack-diff-")); + const entries = await diffAgainstRegistry(KIT_ROOT, project, await v3Manifest(["ghost-pack"])); + expect(entries).toContainEqual({ path: "pack:ghost-pack", status: "missing-registry" }); + expect(entries.some((e) => e.path.startsWith("pack:gestao"))).toBe(false); + }); + + it("syncFromManifest installs legacy packs and warns once for an unknown id", async () => { + const project = await mkdtemp(path.join(tmpdir(), "ak-legacy-pack-sync-")); + const warnings: string[] = []; + const stats = await syncFromManifest(KIT_ROOT, project, await v3Manifest(["ghost-pack"]), { + onWarning: (message) => warnings.push(message), + }); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain("Unknown pack 'ghost-pack'"); + expect(warnings[0]).toContain("Next:"); + expect(stats.missing).toContain("pack:ghost-pack"); + expect(stats.written.length).toBeGreaterThan(0); + }, 30_000); +}); diff --git a/packages/cli/src/lifecycle/overlay-known-hashes.ts b/packages/cli/src/lifecycle/overlay-known-hashes.ts index 38a4f97..03da130 100644 --- a/packages/cli/src/lifecycle/overlay-known-hashes.ts +++ b/packages/cli/src/lifecycle/overlay-known-hashes.ts @@ -476,4 +476,15 @@ export const KNOWN_SHIPPED_OVERLAY_HASHES: ReadonlySet = new Set([ "3d29d3d2ac1f38cd69ecf83e4c50de7419b07e853ae865318682a13480542ece", "6b48f8ada97dc27288723408d8a9f262ae0d22bba6c2fb08fbd12fa28b22f51a", "a137cebc4d7c6a14ed56029c3d11571e73e4eb870984a7f901c0880a0980e70f", + "e154da7c04f7e634898a49a1c3b573ad314293ee652a05de6c1d559b1fecde66", + "9241867256f047eceb37b6f86623feef80ddeba9bf492da4f81a06084bd5bb97", + "670c05a2d888c9702da525febea29b624af8e0d6f0b0bd0bd7ba947a5fac2c6f", + "6bbca9f7b50a7e904d523a7e1318ddcc54f02bf811928ecae4e82cb80956be1c", + "82916f566f132583c9a70f661b9675f6204e4fddd6f624add6e7075d19cbf071", + "9c5a10086431050bee393060acc94d6383a22af627dec13483abbbffa452736c", + "dc6156f15b94e0b7dbd6b59e4d16dee932763fbcb5169e3a1119fc1b63cecfbf", + "ec8b8f4b3a12813a6cba9c5a417f5f1ef8ed34e27ea0c1cdc7d2987ce32e0d00", + "f0555c4a43c3cfd5e6c9fdc9ce14922aaf927d1251d98465f8bc50e6a992d547", + "9d419d86204df507806fb96dc9e2ba14335b11a1d1a584fbefb1bd31799f1edb", + "cb7dc49acdf3d4bcce0fc6df938fe6f7867ee548147049cae840d92759a7e665", ]); diff --git a/packages/cli/src/lifecycle/retired.test.ts b/packages/cli/src/lifecycle/retired.test.ts new file mode 100644 index 0000000..964561b --- /dev/null +++ b/packages/cli/src/lifecycle/retired.test.ts @@ -0,0 +1,155 @@ +import { mkdir, mkdtemp, readdir, readFile, stat, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { contentHash } from "./overlay.js"; +import { KNOWN_SHIPPED_OVERLAY_HASHES } from "./overlay-known-hashes.js"; +import { + dropRetiredSkillIds, + RETIRED_MANAGED_FILES, + RETIRED_SKILL_IDS, + type RetiredManagedFile, + retireManagedFiles, +} from "./retired.js"; + +const BODY = "synthetic retired body\n"; +const FILE: RetiredManagedFile = { + path: ".cursor/skills/community/gone/SKILL.md", + hashes: new Set([contentHash(BODY)]), +}; + +async function project(body?: string): Promise { + const root = await mkdtemp(path.join(tmpdir(), "ak-retired-")); + if (body !== undefined) { + await mkdir(path.join(root, path.dirname(FILE.path)), { recursive: true }); + await writeFile(path.join(root, FILE.path), body, "utf8"); + } + return root; +} + +async function exists(p: string): Promise { + try { + await stat(p); + return true; + } catch { + return false; + } +} + +describe("retireManagedFiles", () => { + it("reports absent when nothing is installed", async () => { + const root = await project(); + expect(await retireManagedFiles(root, [], undefined, [FILE])).toEqual([ + { path: FILE.path, outcome: "absent" }, + ]); + }); + + it("removes a known shipped body and its now-empty directory", async () => { + const root = await project(BODY); + const res = await retireManagedFiles(root, [], undefined, [FILE]); + expect(res).toEqual([{ path: FILE.path, outcome: "removed" }]); + expect(await exists(path.join(root, path.dirname(FILE.path)))).toBe(false); + }); + + it("removes a body that matches the managed-hash ledger and clears the entry", async () => { + const edited = "text the ledger recorded\n"; + const root = await project(edited); + const ledger = { schemaVersion: 1, hashes: { [FILE.path]: contentHash(edited) } }; + const res = await retireManagedFiles(root, [], ledger as never, [FILE]); + expect(res[0]?.outcome).toBe("removed"); + expect(ledger.hashes[FILE.path]).toBeUndefined(); + }); + + it("keeps an edited body", async () => { + const root = await project("my own notes\n"); + const res = await retireManagedFiles(root, [], undefined, [FILE]); + expect(res[0]?.outcome).toBe("preserved-customized"); + expect(await readFile(path.join(root, FILE.path), "utf8")).toBe("my own notes\n"); + }); + + it("skips a protected path and a symlink", async () => { + const protectedRoot = await project(BODY); + const protectedRes = await retireManagedFiles(protectedRoot, [FILE.path], undefined, [FILE]); + expect(protectedRes[0]?.outcome).toBe("skipped-protected"); + expect(await exists(path.join(protectedRoot, FILE.path))).toBe(true); + + const linkRoot = await project(); + const outside = path.join(linkRoot, "outside.md"); + await writeFile(outside, BODY, "utf8"); + await mkdir(path.join(linkRoot, path.dirname(FILE.path)), { recursive: true }); + await symlink(outside, path.join(linkRoot, FILE.path)); + const linkRes = await retireManagedFiles(linkRoot, [], undefined, [FILE]); + expect(linkRes[0]?.outcome).toBe("skipped-symlink"); + expect(await exists(outside)).toBe(true); + }); +}); + +describe("retired registry content", () => { + it("drops retired skill ids and leaves the others in order", () => { + expect(RETIRED_SKILL_IDS).toEqual(["cursor-skills-groovy"]); + expect(dropRetiredSkillIds(["a", "cursor-skills-groovy", "b"])).toEqual({ + skills: ["a", "b"], + dropped: ["cursor-skills-groovy"], + }); + expect(dropRetiredSkillIds(undefined)).toEqual({ skills: undefined, dropped: [] }); + }); + + it("lists every file the kit ever installed for groovy, with hashes", () => { + expect(RETIRED_MANAGED_FILES.map((f) => f.path)).toEqual([ + ".cursor/rules/cursor-skills-groovy.mdc", + ".cursor/skills/community/cursor-skills-groovy/SKILL.md", + ]); + for (const file of RETIRED_MANAGED_FILES) expect(file.hashes.size).toBeGreaterThan(0); + }); +}); + +describe("overlay known hashes after the clean-room rewrite", () => { + // sha256 of the pre-rewrite community skill bodies (hashes only, no text): + // an unedited install without a ledger must keep refreshing to the new body. + const PRE_REWRITE: Record = { + api: "17818e47e06349ee35c1d8e1cc16e8bcbbbcc89c664014e9096e1f08c8567807", + integrations: "989e7e1bdfb29dedf850405f28648810d008885196efe7ae38c6e7554c7ce45d", + mobile: "bd9fd1efacbd132c5dafc12cd0cf2b651a2b1fab7b2d7a9ba4a3e44128097f48", + node: "8108b202c829627c3c2df33575016ebe942df42acf4f1cc393900be3b82b402c", + php: "54dda8addb74bc187ee23c31f8b7d17ad19e745a45169d29ffea094860eb18f2", + python: "f981764422d468567b5aff31148dc659aeee22cb13dc0ecd873d737deaf07372", + webdesign: "875b0a8805280b2a2df43f2c42f9063fe0623a34fa19c3aa5d2ec48211f3ebae", + }; + + for (const [id, hash] of Object.entries(PRE_REWRITE)) { + it(`still recognises the pre-rewrite cursor-skills-${id} body as unedited kit content`, () => { + expect(KNOWN_SHIPPED_OVERLAY_HASHES.has(hash)).toBe(true); + }); + } +}); + +describe("no third-party framing in the stack rules and community skills", () => { + const kitRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../.."); + const THIRD_PARTY = /CURSOR-SKILLS|araguaci|cursor-skills\.vercel/; + + it("keeps the cursor-skills rules and registry entries free of upstream titles and Source lines", async () => { + const files: string[] = []; + for (const name of await readdir(path.join(kitRoot, ".cursor/rules"))) { + if (name.startsWith("cursor-skills-")) files.push(`.cursor/rules/${name}`); + } + const community = "registry/skills/community"; + for (const name of await readdir(path.join(kitRoot, community))) { + if (name.startsWith("cursor-skills-")) files.push(`${community}/${name}/SKILL.md`); + } + files.push(".cursor/skills/community/cursor-skills-node/SKILL.md"); + expect(files.length).toBeGreaterThan(15); + const offenders: string[] = []; + for (const rel of files) { + if (THIRD_PARTY.test(await readFile(path.join(kitRoot, rel), "utf8"))) offenders.push(rel); + } + expect(offenders).toEqual([]); + }); + + it("no longer ships the groovy rule or registry entry", async () => { + expect(await exists(path.join(kitRoot, ".cursor/rules/cursor-skills-groovy.mdc"))).toBe(false); + expect(await exists(path.join(kitRoot, "registry/skills/community/cursor-skills-groovy"))).toBe( + false, + ); + }); +}); diff --git a/packages/cli/src/lifecycle/retired.ts b/packages/cli/src/lifecycle/retired.ts new file mode 100644 index 0000000..3c1f673 --- /dev/null +++ b/packages/cli/src/lifecycle/retired.ts @@ -0,0 +1,116 @@ +import { lstat, readFile, rmdir, unlink } from "node:fs/promises"; +import path from "node:path"; +import { MANIFEST_RELATIVE_PATH } from "../manifest/types.js"; +import { contentHash, type ManagedHashLedger } from "./overlay.js"; +import { resolveContained } from "./paths.js"; +import { isProtectedPath } from "./protected.js"; + +/** + * Kit content that was dropped from the registry (ADR + * `2026-11-26_third-party-skill-license-vendoring-policy`, point 8): the + * `cursor-skills-groovy` rule and registry entry had no provable origin. + * `update` removes an unedited installed copy, keeps and reports an edited one, + * and drops the skill id from the manifest. Same shape as the legacy + * `onboard.md` migration in `onboard-migration.ts`. + */ +export interface RetiredManagedFile { + /** Project-root-relative POSIX path of the file the kit used to install. */ + path: string; + /** sha256 (contentHash) of every body the kit ever shipped at this path. */ + hashes: ReadonlySet; +} + +export const RETIRED_SKILL_IDS: readonly string[] = ["cursor-skills-groovy"]; + +export const RETIRED_MANAGED_FILES: readonly RetiredManagedFile[] = [ + { + path: ".cursor/rules/cursor-skills-groovy.mdc", + hashes: new Set([ + "4bee84cedc08822a3c7ec61804574054031206ab0c66286b1adc81d2fd330f86", + "87eddaddb927069fd161845d514df56fdb395c3e8b893324c135020e2c0285a4", + ]), + }, + { + path: ".cursor/skills/community/cursor-skills-groovy/SKILL.md", + hashes: new Set(["ac2f1f7d9e68f9c98fc4fe5ca348b1a90cf484141bbd116db871d63bdcc3c7c3"]), + }, +]; + +export type RetiredOutcome = + | "absent" + | "removed" + | "preserved-customized" + | "skipped-protected" + | "skipped-symlink"; + +export interface RetiredResult { + path: string; + outcome: RetiredOutcome; +} + +export function isRetiredSkillId(id: string): boolean { + return RETIRED_SKILL_IDS.includes(id); +} + +/** Skill ids without the retired ones, plus the ones that were dropped. */ +export function dropRetiredSkillIds(skills: readonly string[] | undefined): { + skills: string[] | undefined; + dropped: string[]; +} { + if (!skills) return { skills: undefined, dropped: [] }; + const dropped = skills.filter(isRetiredSkillId); + return { skills: skills.filter((id) => !isRetiredSkillId(id)), dropped }; +} + +/** One line per dropped id, printed by `update`. */ +export function formatRetiredSkillDrop(id: string): string { + return `Skill '${id}' was retired from the registry and removed from "skills" in ${MANIFEST_RELATIVE_PATH} (ADR 2026-11-26 third-party skill license policy).`; +} + +/** + * Remove retired kit files that are still unedited. A file counts as unedited + * when its body is a known shipped body or matches the managed-hash ledger. + * Edited, protected and symlinked paths are left alone and reported. + */ +export async function retireManagedFiles( + projectRoot: string, + protectedGlobs: readonly string[], + ledger?: ManagedHashLedger, + files: readonly RetiredManagedFile[] = RETIRED_MANAGED_FILES, +): Promise { + const results: RetiredResult[] = []; + for (const file of files) { + const abs = resolveContained(projectRoot, file.path); + let info: Awaited>; + try { + info = await lstat(abs); + } catch { + results.push({ path: file.path, outcome: "absent" }); + continue; + } + if (isProtectedPath(file.path, protectedGlobs)) { + results.push({ path: file.path, outcome: "skipped-protected" }); + continue; + } + if (info.isSymbolicLink() || !info.isFile()) { + results.push({ path: file.path, outcome: "skipped-symlink" }); + continue; + } + const hash = contentHash(await readFile(abs, "utf8")); + const recorded = ledger?.hashes[file.path]; + if (!file.hashes.has(hash) && hash !== recorded) { + results.push({ path: file.path, outcome: "preserved-customized" }); + continue; + } + await unlink(abs); + if (ledger) delete ledger.hashes[file.path]; + // Drop the skill directory when the file was its last one. + try { + await rmdir(path.dirname(abs)); + } catch { + // not empty (or not a skill dir): leave it + } + results.push({ path: file.path, outcome: "removed" }); + } + return results; +} diff --git a/packages/cli/src/lifecycle/sync.ts b/packages/cli/src/lifecycle/sync.ts index 5aa5f71..678c653 100644 --- a/packages/cli/src/lifecycle/sync.ts +++ b/packages/cli/src/lifecycle/sync.ts @@ -1,6 +1,8 @@ import type { AgentKitManifest } from "../manifest/types.js"; import { allSkills, findSkill, loadRegistry } from "../registry/client.js"; import { installPack, installSkill, installSkillsByIds } from "../registry/install.js"; +import { UnknownPackError } from "../registry/pack-aliases.js"; +import { logger } from "../utils/logger.js"; import { type ApplyStats, copyRegistryFile, @@ -12,6 +14,7 @@ import { L0_ARTIFACTS } from "./l0.js"; import { migrateLegacyOnboardCommand } from "./onboard-migration.js"; import { loadManagedHashLedger, type ManagedHashLedger, saveManagedHashLedger } from "./overlay.js"; import { resolveProtectedGlobs } from "./protected.js"; +import { isRetiredSkillId, retireManagedFiles } from "./retired.js"; export async function installL0( registryRoot: string, @@ -33,6 +36,11 @@ export async function installL0( ); recordOutcome(stats, artifact.target, outcome); } + for (const retired of await retireManagedFiles(projectRoot, protectedGlobs, managedHashes)) { + if (retired.outcome === "removed") stats.removed.push(retired.path); + else if (retired.outcome === "preserved-customized") stats.collisions.push(retired.path); + } + // Save after the retirement so a removed file drops out of the ledger. if (!ledger) await saveManagedHashLedger(projectRoot, managedHashes); const migration = await migrateLegacyOnboardCommand(projectRoot); if (migration === "removed-managed") { @@ -43,15 +51,24 @@ export async function installL0( return stats; } +export interface SyncOptions { + /** Receives the named warning for a manifest pack id the registry does not ship. */ + onWarning?: (message: string) => void; +} + /** * Re-apply L0 + manifest packs + manifest skills (skips protected). The - * managed-hash ledger is read once up front and saved once at the end. + * managed-hash ledger is read once up front and saved once at the end. A pack + * id the registry does not ship (legacy aliases resolve) is skipped with a + * named warning and recorded as `pack:` in `missing`, like a missing skill. */ export async function syncFromManifest( registryRoot: string, projectRoot: string, manifest: AgentKitManifest, + options: SyncOptions = {}, ): Promise { + const onWarning = options.onWarning ?? ((message: string) => logger.warn(message)); const protectedGlobs = resolveProtectedGlobs(manifest); const stats = emptyStats(); const managedHashes = await loadManagedHashLedger(projectRoot); @@ -61,10 +78,16 @@ export async function syncFromManifest( mergeStats(stats, await installL0(registryRoot, projectRoot, protectedGlobs, managedHashes)); for (const packId of manifest.packs ?? []) { - mergeStats(stats, await installPack(registryRoot, projectRoot, packId, installOpts)); + try { + mergeStats(stats, await installPack(registryRoot, projectRoot, packId, installOpts)); + } catch (err) { + if (!(err instanceof UnknownPackError)) throw err; + onWarning(err.message); + stats.missing.push(`pack:${packId}`); + } } - const skillIds = manifest.skills ?? []; + const skillIds = (manifest.skills ?? []).filter((id) => !isRetiredSkillId(id)); if (skillIds.length > 0) { await loadRegistry(registryRoot); mergeStats(stats, await installSkillsByIds(registryRoot, projectRoot, skillIds, installOpts)); diff --git a/packages/cli/src/lifecycle/targets.test.ts b/packages/cli/src/lifecycle/targets.test.ts index eb46181..13b20e8 100644 --- a/packages/cli/src/lifecycle/targets.test.ts +++ b/packages/cli/src/lifecycle/targets.test.ts @@ -92,10 +92,11 @@ describe("managedPairs", () => { it("yields exactly the pairs diff and contribute enumerated before", async () => { const registryRoot = await fixtureRegistry(); const legacy = await legacyPairs(registryRoot); - const { pairs, missingSkills } = await managedPairs(registryRoot, manifest); + const { pairs, missingSkills, missingPacks } = await managedPairs(registryRoot, manifest); expect(pairs.map(({ sourceRel, targetRel }) => ({ sourceRel, targetRel }))).toEqual(legacy); expect(missingSkills).toEqual(["ghost"]); + expect(missingPacks).toEqual([]); expect(pairs.filter((p) => p.origin === "l0")).toHaveLength(L0_ARTIFACTS.length); expect(pairs.filter((p) => p.origin === "pack").map((p) => p.targetRel)).toEqual([ ".cursor/rules/demo-rule.mdc", @@ -108,7 +109,11 @@ describe("managedPairs", () => { ]); const index = await loadRegistry(registryRoot); - expect(await managedPairs(registryRoot, manifest, index)).toEqual({ pairs, missingSkills }); + expect(await managedPairs(registryRoot, manifest, index)).toEqual({ + pairs, + missingSkills, + missingPacks, + }); }); it("keeps diff and contribute on the same pairs", async () => { diff --git a/packages/cli/src/lifecycle/targets.ts b/packages/cli/src/lifecycle/targets.ts index 61d4e98..4462da9 100644 --- a/packages/cli/src/lifecycle/targets.ts +++ b/packages/cli/src/lifecycle/targets.ts @@ -1,9 +1,16 @@ import path from "node:path"; import type { AgentKitManifest } from "../manifest/types.js"; import { allSkills, loadRegistry } from "../registry/client.js"; -import { loadPackManifest, packMemberFileTargets, skillFileTargets } from "../registry/install.js"; +import { + loadPackManifest, + type PackManifest, + packMemberFileTargets, + skillFileTargets, +} from "../registry/install.js"; +import { UnknownPackError } from "../registry/pack-aliases.js"; import type { RegistryIndex } from "../registry/types.js"; import { L0_ARTIFACTS } from "./l0.js"; +import { isRetiredSkillId } from "./retired.js"; export type ManagedOrigin = "l0" | "pack" | "skill"; @@ -20,6 +27,8 @@ export interface ManagedPairs { pairs: ManagedPair[]; /** Manifest skill ids absent from the registry index. */ missingSkills: string[]; + /** Manifest pack ids absent from the registry index (legacy aliases resolve first). */ + missingPacks: string[]; } const toPosix = (rel: string) => rel.split(path.sep).join("/"); @@ -37,6 +46,7 @@ export async function managedPairs( ): Promise { const pairs: ManagedPair[] = []; const missingSkills: string[] = []; + const missingPacks: string[] = []; const push = (sourceRel: string, targetRel: string, origin: ManagedOrigin) => { pairs.push({ sourceRel: toPosix(sourceRel), targetRel: toPosix(targetRel), origin }); }; @@ -44,7 +54,14 @@ export async function managedPairs( for (const a of L0_ARTIFACTS) push(a.source, a.target, "l0"); for (const packId of manifest.packs ?? []) { - const pack = await loadPackManifest(registryRoot, packId); + let pack: PackManifest; + try { + pack = await loadPackManifest(registryRoot, packId); + } catch (err) { + if (!(err instanceof UnknownPackError)) throw err; + missingPacks.push(packId); + continue; + } for (const member of pack.members) { for (const { sourceRel, targetRel } of await packMemberFileTargets(registryRoot, member)) { push(sourceRel, targetRel, "pack"); @@ -55,6 +72,7 @@ export async function managedPairs( if ((manifest.skills ?? []).length > 0) { const pool = allSkills(index ?? (await loadRegistry(registryRoot))); for (const id of manifest.skills ?? []) { + if (isRetiredSkillId(id)) continue; const skill = pool.find((s) => s.id === id); if (!skill) { missingSkills.push(id); @@ -70,5 +88,5 @@ export async function managedPairs( } } - return { pairs, missingSkills }; + return { pairs, missingSkills, missingPacks }; } diff --git a/packages/cli/src/lifecycle/update-notice.test.ts b/packages/cli/src/lifecycle/update-notice.test.ts new file mode 100644 index 0000000..81d5d76 --- /dev/null +++ b/packages/cli/src/lifecycle/update-notice.test.ts @@ -0,0 +1,297 @@ +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { updateNoticeSection } from "../hooks/session-start.js"; +import type { InstallEntry, InstallKind } from "../installs/index.js"; +import type { NpmFetch } from "./check-updates.js"; +import { + cachedCliNpmLatest, + computeUpdateNotice, + readUpdateNoticeCache, + resolveUpdateNoticeFile, + summarizeUpdateNotice, + UPDATE_NOTICE_TTL_MS, +} from "./update-notice.js"; + +const NOW = new Date("2026-11-26T12:00:00.000Z"); + +/** Stub npm: `@dadado/agent-kit-cli` answers `version`, `@missionkit/cli` 404s. */ +function npmStub(version: string | null): NpmFetch & ReturnType { + return vi.fn(async (url: string) => { + if (version && url.includes("@dadado%2Fagent-kit-cli")) { + return { ok: true, json: async () => ({ version }) }; + } + return { ok: false, json: async () => ({}) }; + }) as unknown as NpmFetch & ReturnType; +} + +const offline = vi.fn(async () => { + throw new Error("getaddrinfo ENOTFOUND registry.npmjs.org"); +}) as unknown as NpmFetch; + +function entry(p: string, kitVersion: string | null, kind: InstallKind = "repo"): InstallEntry { + return { + path: p, + remote: null, + kitVersion, + cliVersion: "6.0.0", + lastSeen: NOW.toISOString(), + kind, + }; +} + +let scratch: string; +let home: string; +let cwd: string; +let installsFile: string; +let noticeFile: string; + +beforeEach(async () => { + scratch = await mkdtemp(path.join(tmpdir(), "ak-update-notice-")); + home = path.join(scratch, "home"); + cwd = path.join(scratch, "repo"); + await mkdir(path.join(cwd, ".cursor", "context"), { recursive: true }); + installsFile = path.join(scratch, "config", "agent-kit", "installs.json"); + noticeFile = path.join(scratch, "config", "agent-kit", "update-notice.json"); +}); + +afterEach(async () => { + await rm(scratch, { recursive: true, force: true }); +}); + +async function writeInstalls(installs: InstallEntry[]): Promise { + await mkdir(path.dirname(installsFile), { recursive: true }); + await writeFile(installsFile, JSON.stringify({ schemaVersion: 1, installs }), "utf8"); +} + +function opts(fetchImpl: NpmFetch, extra: Record = {}) { + return { + env: {}, + homeDir: home, + now: NOW, + cliVersion: "6.22.0", + fetchImpl, + file: noticeFile, + installsFile, + cliPath: null, + platform: "linux" as NodeJS.Platform, + ...extra, + }; +} + +describe("resolveUpdateNoticeFile", () => { + it("sits beside installs.json (env override, XDG, home)", () => { + expect(resolveUpdateNoticeFile({ AGENT_KIT_INSTALLS_FILE: "/s/x/installs.json" }, "/h")).toBe( + "/s/x/update-notice.json", + ); + expect(resolveUpdateNoticeFile({ XDG_CONFIG_HOME: "/xdg" }, "/h")).toBe( + "/xdg/agent-kit/update-notice.json", + ); + expect(resolveUpdateNoticeFile({}, "/h")).toBe("/h/.config/agent-kit/update-notice.json"); + }); +}); + +describe("cachedCliNpmLatest (daily cache)", () => { + it("fetches once, then serves the fresh cache without network", async () => { + const fetchImpl = npmStub("6.22.0"); + const first = await cachedCliNpmLatest({ file: noticeFile, now: NOW, fetchImpl }); + expect(first).toEqual({ packageName: "@dadado/agent-kit-cli", version: "6.22.0" }); + expect(fetchImpl).toHaveBeenCalledTimes(2); // both package names, in parallel + const later = new Date(NOW.getTime() + UPDATE_NOTICE_TTL_MS - 1000); + const second = await cachedCliNpmLatest({ file: noticeFile, now: later, fetchImpl }); + expect(second).toEqual(first); + expect(fetchImpl).toHaveBeenCalledTimes(2); + }); + + it("refreshes a stale cache (over a day old)", async () => { + await cachedCliNpmLatest({ file: noticeFile, now: NOW, fetchImpl: npmStub("6.21.0") }); + const fetchImpl = npmStub("6.22.0"); + const stale = new Date(NOW.getTime() + UPDATE_NOTICE_TTL_MS + 1000); + const result = await cachedCliNpmLatest({ file: noticeFile, now: stale, fetchImpl }); + expect(result?.version).toBe("6.22.0"); + expect(fetchImpl).toHaveBeenCalled(); + expect((await readUpdateNoticeCache(noticeFile))?.checkedAt).toBe(stale.toISOString()); + }); + + it("fails open offline and stamps the attempt so the next session does not retry", async () => { + const result = await cachedCliNpmLatest({ file: noticeFile, now: NOW, fetchImpl: offline }); + expect(result).toBeNull(); + const cache = await readUpdateNoticeCache(noticeFile); + expect(cache).toMatchObject({ checkedAt: NOW.toISOString(), npm: null }); + const fetchImpl = npmStub("6.22.0"); + await cachedCliNpmLatest({ file: noticeFile, now: NOW, fetchImpl }); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it("treats an unreadable cache as missing", async () => { + await mkdir(path.dirname(noticeFile), { recursive: true }); + await writeFile(noticeFile, "{not json", "utf8"); + const fetchImpl = npmStub("6.22.0"); + expect((await cachedCliNpmLatest({ file: noticeFile, now: NOW, fetchImpl }))?.version).toBe( + "6.22.0", + ); + }); +}); + +describe("summarizeUpdateNotice", () => { + const npm = { packageName: "@dadado/agent-kit-cli" as const, version: "6.22.0" }; + + it("names both commands when the CLI and installs are behind", () => { + const summary = summarizeUpdateNotice({ + cliVersion: "6.19.1", + npmLatest: npm, + installs: [ + entry("/h/a", "6.0.0"), + entry("/h/x", "3.0.0"), + entry("/h/home", "5.0.0", "home"), + entry("/h/wt", "1.0.0", "worktree"), + entry("/h/fx", "1.0.0", "fixture"), + entry("/h/kit", "1.0.0", "factory"), + entry("/h/cur", "6.19.1"), + entry("/h/none", null), + ], + homeDir: "/h", + now: NOW, + }); + expect(summary).toMatchObject({ + cliBehind: true, + installsBehind: 3, + oldest: { path: "~/x", kitVersion: "3.0.0" }, + cliCommand: "npm i -g @dadado/agent-kit-cli@latest", + }); + expect(summary.line).toBe( + "Agent Kit: CLI 6.19.1 < npm 6.22.0 (`npm i -g @dadado/agent-kit-cli@latest`); 3 installs behind, oldest v3.0.0 at ~/x (`agent-kit update --all`).", + ); + }); + + it("is silent when everything is current (and when the CLI is ahead of npm)", () => { + for (const cliVersion of ["6.22.0", "6.23.0"]) { + const summary = summarizeUpdateNotice({ + cliVersion, + npmLatest: npm, + installs: [entry("/h/a", cliVersion), entry("/h/wt", "3.0.0", "worktree")], + homeDir: "/h", + now: NOW, + }); + expect(summary.line).toBeNull(); + expect(summary.installsBehind).toBe(0); + } + }); + + it("names only update --all when the CLI is current", () => { + const summary = summarizeUpdateNotice({ + cliVersion: "6.22.0", + npmLatest: npm, + installs: [entry("/h/a", "6.21.0")], + homeDir: "/h", + now: NOW, + }); + expect(summary.line).toBe( + "Agent Kit: 1 install behind CLI 6.22.0, oldest v6.21.0 at ~/a (`agent-kit update --all`).", + ); + }); + + it("points a CLI in a per-version node dir at doctor (the mise-safe install)", () => { + const summary = summarizeUpdateNotice({ + cliVersion: "6.19.1", + npmLatest: npm, + installs: [], + homeDir: "/h", + now: NOW, + cliInNodeManager: true, + }); + expect(summary.cliCommand).toBe("agent-kit doctor"); + expect(summary.line).toContain("`agent-kit doctor`"); + expect(summary.line).not.toContain("npm i -g"); + }); + + it("ignores non-semver kit versions instead of throwing", () => { + const summary = summarizeUpdateNotice({ + cliVersion: "6.22.0", + npmLatest: null, + installs: [entry("/h/a", "weird")], + homeDir: "/h", + now: NOW, + }); + expect(summary.line).toBeNull(); + }); +}); + +describe("computeUpdateNotice", () => { + it("returns the line, persists it for Mission Control, and clears it when current", async () => { + await writeInstalls([entry(path.join(home, "x"), "3.0.0")]); + const summary = await computeUpdateNotice(cwd, opts(npmStub("6.22.0"))); + expect(summary?.line).toBe( + "Agent Kit: 1 install behind CLI 6.22.0, oldest v3.0.0 at ~/x (`agent-kit update --all`).", + ); + expect((await readUpdateNoticeCache(noticeFile))?.notice).toMatchObject({ + installsBehind: 1, + oldest: { path: "~/x", kitVersion: "3.0.0" }, + }); + + await writeInstalls([entry(path.join(home, "x"), "6.22.0")]); + const current = await computeUpdateNotice(cwd, opts(npmStub("6.22.0"))); + expect(current?.line).toBeNull(); + expect((await readUpdateNoticeCache(noticeFile))?.notice).toBeNull(); + }); + + it("is off under CI, the env opt-outs and updateCheck.enabled false (no fetch, no file)", async () => { + await writeInstalls([entry(path.join(home, "x"), "3.0.0")]); + for (const env of [ + { CI: "1" }, + { AGENT_KIT_NO_UPDATE_CHECK: "1" }, + { NO_UPDATE_NOTIFIER: "true" }, + ]) { + const fetchImpl = npmStub("9.0.0"); + expect(await computeUpdateNotice(cwd, opts(fetchImpl, { env }))).toBeNull(); + expect(fetchImpl).not.toHaveBeenCalled(); + } + await writeFile( + path.join(cwd, ".cursor", "context", "config.json"), + JSON.stringify({ updateCheck: { enabled: false } }), + "utf8", + ); + const fetchImpl = npmStub("9.0.0"); + expect(await computeUpdateNotice(cwd, opts(fetchImpl))).toBeNull(); + expect(fetchImpl).not.toHaveBeenCalled(); + await expect(readFile(noticeFile, "utf8")).rejects.toThrow(); + }); + + it("offline: still reports installs behind the CLI, never the npm half", async () => { + await writeInstalls([entry(path.join(home, "x"), "6.0.0")]); + const summary = await computeUpdateNotice(cwd, opts(offline, { cliVersion: "6.19.1" })); + expect(summary?.cliBehind).toBe(false); + expect(summary?.line).toBe( + "Agent Kit: 1 install behind CLI 6.19.1, oldest v6.0.0 at ~/x (`agent-kit update --all`).", + ); + }); + + it("offline with nothing behind is silent; a broken installs.json is silent too", async () => { + expect((await computeUpdateNotice(cwd, opts(offline)))?.line).toBeNull(); + await mkdir(path.dirname(installsFile), { recursive: true }); + await writeFile(installsFile, "{oops", "utf8"); + expect((await computeUpdateNotice(cwd, opts(offline)))?.line).toBeNull(); + }); +}); + +describe("updateNoticeSection (sessionStart)", () => { + it("prints the one line when something is behind", async () => { + await writeInstalls([entry(path.join(home, "x"), "3.0.0")]); + const line = await updateNoticeSection(cwd, opts(npmStub("6.22.0"), { cliVersion: "6.19.1" })); + expect(line).toBe( + "Agent Kit: CLI 6.19.1 < npm 6.22.0 (`npm i -g @dadado/agent-kit-cli@latest`); 1 install behind, oldest v3.0.0 at ~/x (`agent-kit update --all`).", + ); + }); + + it("is null when current, when opted out and when the lookup hangs past the deadline", async () => { + expect(await updateNoticeSection(cwd, opts(npmStub("6.22.0")))).toBeNull(); + expect( + await updateNoticeSection(cwd, opts(npmStub("9.0.0"), { env: { CI: "true" } })), + ).toBeNull(); + const hang = vi.fn(() => new Promise(() => {})) as unknown as NpmFetch; + const started = Date.now(); + expect(await updateNoticeSection(cwd, opts(hang, { deadlineMs: 50 }))).toBeNull(); + expect(Date.now() - started).toBeLessThan(2_000); + }); +}); diff --git a/packages/cli/src/lifecycle/update-notice.ts b/packages/cli/src/lifecycle/update-notice.ts new file mode 100644 index 0000000..18461b8 --- /dev/null +++ b/packages/cli/src/lifecycle/update-notice.ts @@ -0,0 +1,334 @@ +/** + * Machine update notice (ADR 2026-07-27 Amend 2026-11-26): check-only, on by + * default, at most one npm lookup a day. + * + * - Compares this CLI with npm `latest` (both package names, c2) and every + * registered install (c3 `installs.json`) with this CLI. + * - The npm answer is cached next to `installs.json` in the machine config dir + * (`update-notice.json`); the installs half is recomputed on every call, so + * the notice clears as soon as an update lands. + * - The computed summary is written into the same file for Mission Control, + * which only reads it (no semver or kind logic in the dashboard). + * - Off under `CI`, with `AGENT_KIT_NO_UPDATE_CHECK` / `NO_UPDATE_NOTIFIER`, and + * with `updateCheck.enabled: false`. Offline or any error is silent. + * - Never applies anything: it names the operator command and stops. + */ + +import { randomUUID } from "node:crypto"; +import { mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import path from "node:path"; +import { + type InstallEntry, + type InstallKind, + listInstalls, + resolveInstallsFile, +} from "../installs/index.js"; +import { classifyNodeManagerPath, PER_VERSION_MANAGERS } from "../readiness/install-health.js"; +import { + CLI_NPM_PACKAGES, + type CliNpmLatest, + compareSemver, + fetchLatestCliNpmVersion, + type NpmFetch, + normalizeSemver, + updateCheckAllowed, +} from "./check-updates.js"; +import { loadContextConfig } from "./context-config.js"; +import { KIT_VERSION } from "./version.js"; + +export const UPDATE_NOTICE_FILENAME = "update-notice.json"; +export const UPDATE_NOTICE_SCHEMA_VERSION = 1 as const; +/** One npm lookup a day at most. */ +export const UPDATE_NOTICE_TTL_MS = 24 * 60 * 60 * 1000; +/** sessionStart budget for the daily npm lookup; a miss is silent until tomorrow. */ +export const UPDATE_NOTICE_SESSION_FETCH_TIMEOUT_MS = 1_500; + +/** + * Kinds the notice counts. `worktree`, `fixture` and `factory` rows are left + * out: `agent-kit update --all` skips them too (a worktree follows its main + * checkout, a fixture is not a consumer, the factory is the kit itself). + */ +export const UPDATE_NOTICE_KINDS: ReadonlySet = new Set(["repo", "home"]); + +export interface UpdateNoticeSummary { + generatedAt: string; + cliVersion: string; + /** npm `latest` (highest across both names) or null when unknown. */ + npmLatest: CliNpmLatest | null; + cliBehind: boolean; + installsBehind: number; + /** Oldest install behind this CLI; `path` is home-relative (`~/…`). */ + oldest: { path: string; kitVersion: string } | null; + /** Operator command that upgrades the CLI, when `cliBehind`. */ + cliCommand: string | null; + /** The sessionStart line, or null when everything is current. */ + line: string | null; +} + +export interface UpdateNoticeCache { + schemaVersion: typeof UPDATE_NOTICE_SCHEMA_VERSION; + /** Last npm lookup attempt (success or not). */ + checkedAt: string; + npm: CliNpmLatest | null; + /** Last computed summary, for Mission Control; null when current. */ + notice?: UpdateNoticeSummary | null; +} + +/** `update-notice.json` beside `installs.json` (same env / XDG / home resolution). */ +export function resolveUpdateNoticeFile( + env: NodeJS.ProcessEnv = process.env, + home: string = homedir(), +): string { + return path.join(path.dirname(resolveInstallsFile(env, home)), UPDATE_NOTICE_FILENAME); +} + +function isCliNpmLatest(value: unknown): value is CliNpmLatest { + if (!value || typeof value !== "object") return false; + const v = value as Record; + return ( + typeof v.version === "string" && + normalizeSemver(v.version) !== null && + CLI_NPM_PACKAGES.some((pkg) => pkg.name === v.packageName) + ); +} + +/** Read the cache; null when missing, unreadable or not ours. Never throws. */ +export async function readUpdateNoticeCache(file: string): Promise { + try { + const raw = JSON.parse(await readFile(file, "utf8")) as Record; + if (!raw || raw.schemaVersion !== UPDATE_NOTICE_SCHEMA_VERSION) return null; + if (typeof raw.checkedAt !== "string" || Number.isNaN(Date.parse(raw.checkedAt))) return null; + return { + schemaVersion: UPDATE_NOTICE_SCHEMA_VERSION, + checkedAt: raw.checkedAt, + npm: isCliNpmLatest(raw.npm) + ? { packageName: raw.npm.packageName, version: raw.npm.version } + : null, + notice: (raw.notice as UpdateNoticeSummary | null | undefined) ?? null, + }; + } catch { + return null; + } +} + +/** Temp file + rename; best-effort (a read-only config dir just means no cache). */ +async function writeUpdateNoticeCache(file: string, cache: UpdateNoticeCache): Promise { + const tmp = `${file}.${process.pid}.${randomUUID()}.tmp`; + try { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(tmp, `${JSON.stringify(cache, null, 2)}\n`, "utf8"); + await rename(tmp, file); + } catch { + await rm(tmp, { force: true }).catch(() => {}); + } +} + +/** True when `checkedAt` is less than a day old (a future stamp counts as stale). */ +export function updateNoticeCacheFresh(checkedAt: string, now: Date): boolean { + const at = Date.parse(checkedAt); + if (Number.isNaN(at)) return false; + const age = now.getTime() - at; + return age >= 0 && age < UPDATE_NOTICE_TTL_MS; +} + +export interface CachedNpmLatestOptions { + file?: string; + now?: Date; + fetchImpl?: NpmFetch; + timeoutMs?: number; +} + +/** + * npm `latest` of the CLI from the daily cache; a stale or missing cache costs + * one lookup (bounded by `timeoutMs`), stamped even when it fails so an + * offline machine does not pay the timeout on every session. Never throws. + */ +export async function cachedCliNpmLatest( + options: CachedNpmLatestOptions = {}, +): Promise { + const file = options.file ?? resolveUpdateNoticeFile(); + const now = options.now ?? new Date(); + const cache = await readUpdateNoticeCache(file); + if (cache && updateNoticeCacheFresh(cache.checkedAt, now)) return cache.npm; + let npm: CliNpmLatest | null = null; + try { + npm = await fetchLatestCliNpmVersion(options.fetchImpl, options.timeoutMs); + } catch { + npm = null; + } + await writeUpdateNoticeCache(file, { + schemaVersion: UPDATE_NOTICE_SCHEMA_VERSION, + checkedAt: now.toISOString(), + npm, + notice: cache?.notice ?? null, + }); + return npm; +} + +function homeRelative(p: string, home: string): string { + const rel = path.relative(home, p); + if (rel === "") return "~"; + if (!rel.startsWith("..") && !path.isAbsolute(rel)) return `~/${rel.split(path.sep).join("/")}`; + return p; +} + +function semverLess(a: string, b: string): boolean { + try { + return compareSemver(a, b) < 0; + } catch { + return false; + } +} + +export interface SummarizeUpdateNoticeInput { + cliVersion: string; + npmLatest: CliNpmLatest | null; + installs: readonly InstallEntry[]; + homeDir: string; + now: Date; + /** When the running CLI sits in a per-version node dir (mise, nvm, fnm). */ + cliInNodeManager?: boolean; +} + +/** Pure: what is behind, and the one line to print (null when current). */ +export function summarizeUpdateNotice(input: SummarizeUpdateNoticeInput): UpdateNoticeSummary { + const cli = normalizeSemver(input.cliVersion) ?? input.cliVersion; + const npm = input.npmLatest; + const cliBehind = npm ? semverLess(cli, npm.version) : false; + + let installsBehind = 0; + let oldest: InstallEntry | null = null; + for (const entry of input.installs) { + if (!UPDATE_NOTICE_KINDS.has(entry.kind) || !entry.kitVersion) continue; + if (!semverLess(entry.kitVersion, cli)) continue; + installsBehind += 1; + if ( + !oldest || + semverLess(entry.kitVersion, oldest.kitVersion as string) || + (!semverLess(oldest.kitVersion as string, entry.kitVersion) && + entry.path.localeCompare(oldest.path) < 0) + ) { + oldest = entry; + } + } + + const cliCommand = + cliBehind && npm + ? input.cliInNodeManager + ? "agent-kit doctor" + : `npm i -g ${npm.packageName}@latest` + : null; + const oldestOut = oldest + ? { + path: homeRelative(oldest.path, input.homeDir), + kitVersion: normalizeSemver(oldest.kitVersion as string) ?? (oldest.kitVersion as string), + } + : null; + + const parts: string[] = []; + if (cliBehind && npm) { + const hint = input.cliInNodeManager + ? "`agent-kit doctor` shows the install that survives a node switch" + : `\`${cliCommand}\``; + parts.push(`CLI ${cli} < npm ${npm.version} (${hint})`); + } + if (installsBehind > 0 && oldestOut) { + const noun = installsBehind === 1 ? "install" : "installs"; + const behind = cliBehind ? "behind" : `behind CLI ${cli}`; + parts.push( + `${installsBehind} ${noun} ${behind}, oldest v${oldestOut.kitVersion} at ${oldestOut.path} (\`agent-kit update --all\`)`, + ); + } + + return { + generatedAt: input.now.toISOString(), + cliVersion: cli, + npmLatest: npm, + cliBehind, + installsBehind, + oldest: oldestOut, + cliCommand, + line: parts.length ? `Agent Kit: ${parts.join("; ")}.` : null, + }; +} + +/** Whether `cliPath` (realpath of the running CLI) sits in a per-version node dir. */ +export function cliPathInNodeManager(cliPath: string | null, platform: NodeJS.Platform): boolean { + if (!cliPath) return false; + return PER_VERSION_MANAGERS.has(classifyNodeManagerPath(cliPath, platform).manager); +} + +export interface UpdateNoticeOptions { + env?: NodeJS.ProcessEnv; + homeDir?: string; + now?: Date; + cliVersion?: string; + fetchImpl?: NpmFetch; + timeoutMs?: number; + /** Notice cache file (default beside installs.json). */ + file?: string; + /** installs.json path (default {@link resolveInstallsFile}). */ + installsFile?: string; + /** Path of the running CLI script (default realpath of argv[1]). */ + cliPath?: string | null; + platform?: NodeJS.Platform; +} + +/** + * Compute the notice for `cwd` (its config can opt out). Returns null when the + * check is off; otherwise the summary (its `line` is null when current). + * Persists the summary for Mission Control when it changed. Never throws. + */ +export async function computeUpdateNotice( + cwd: string, + options: UpdateNoticeOptions = {}, +): Promise { + try { + const env = options.env ?? process.env; + const config = await loadContextConfig(cwd).catch(() => null); + if (!updateCheckAllowed(env, config)) return null; + + const homeDir = options.homeDir ?? homedir(); + const now = options.now ?? new Date(); + const file = options.file ?? resolveUpdateNoticeFile(env, homeDir); + const npmLatest = await cachedCliNpmLatest({ + file, + now, + fetchImpl: options.fetchImpl, + timeoutMs: options.timeoutMs, + }); + const installs = await listInstalls({ + file: options.installsFile ?? resolveInstallsFile(env, homeDir), + }).catch(() => [] as InstallEntry[]); + + let cliPath = options.cliPath; + if (cliPath === undefined) { + cliPath = process.argv[1] ? await realpath(process.argv[1]).catch(() => null) : null; + } + const summary = summarizeUpdateNotice({ + cliVersion: options.cliVersion ?? KIT_VERSION, + npmLatest, + installs, + homeDir, + now, + cliInNodeManager: cliPathInNodeManager(cliPath, options.platform ?? process.platform), + }); + await persistNotice(file, summary.line ? summary : null); + return summary; + } catch { + return null; + } +} + +function sameNotice(a: UpdateNoticeSummary | null, b: UpdateNoticeSummary | null): boolean { + const strip = (n: UpdateNoticeSummary | null) => (n ? { ...n, generatedAt: "" } : null); + return JSON.stringify(strip(a)) === JSON.stringify(strip(b)); +} + +async function persistNotice(file: string, notice: UpdateNoticeSummary | null): Promise { + const cache = await readUpdateNoticeCache(file); + if (!cache) return; + if (sameNotice(cache.notice ?? null, notice)) return; + await writeUpdateNoticeCache(file, { ...cache, notice }); +} diff --git a/packages/cli/src/plan-loop/run-loop.ts b/packages/cli/src/plan-loop/run-loop.ts index a9e34a5..65524f7 100644 --- a/packages/cli/src/plan-loop/run-loop.ts +++ b/packages/cli/src/plan-loop/run-loop.ts @@ -67,6 +67,7 @@ import { runReviewJob, } from "./review-job.js"; import { + formatAgentStopLine, formatSentinelLine, resolveTickResultStatus, resolveTickSentinel, @@ -870,7 +871,7 @@ export async function runPlanLoop(opts: RunPlanLoopOptions): Promise { if (sentinel.kind === "continue") { // ok } else if (sentinel.kind === "stop") { - say(`Agent requested stop: ${formatSentinelLine(sentinel)}`); + say(formatAgentStopLine(sentinel)); stopReason = sentinel.reason; endReason = `agent requested stop: ${sentinel.reason}`; if (after === 0 || isPlanExhaustedReason(sentinel.reason)) { diff --git a/packages/cli/src/plan-loop/run-plan-all-orchestrator.test.ts b/packages/cli/src/plan-loop/run-plan-all-orchestrator.test.ts index b2f75bf..0c3d716 100644 --- a/packages/cli/src/plan-loop/run-plan-all-orchestrator.test.ts +++ b/packages/cli/src/plan-loop/run-plan-all-orchestrator.test.ts @@ -524,6 +524,20 @@ describe("readDeferredGatesFromHandoff (agent-kit queue gates)", () => { ), ).toEqual({ "a.plan.md": "merge #1 (truncated" }); }); + + // run-plan-all-consolidate.sh --rewrite-queue keeps displaced rows under this bullet. + it("ignores deferred rows kept under Queue outcomes anteriores", () => { + expect( + readDeferredGatesFromHandoff( + [ + "- **Queue outcomes:**", + " - a.plan.md: completed", + "- **Queue outcomes anteriores:**", + " old.plan.md: deferred-operator (gate: merge #1)", + ].join("\n"), + ), + ).toEqual({}); + }); }); describe("in-window implement guard (transcript 606a14a5)", () => { diff --git a/packages/cli/src/plan-loop/sentinel.test.ts b/packages/cli/src/plan-loop/sentinel.test.ts index 8538b82..3ad3346 100644 --- a/packages/cli/src/plan-loop/sentinel.test.ts +++ b/packages/cli/src/plan-loop/sentinel.test.ts @@ -5,6 +5,9 @@ import { describe, expect, it, vi } from "vitest"; import { type TurnResult, TurnWatcher } from "./hitl-relay.js"; import { TICK_PROMPT } from "./run-loop.js"; import { + AGENT_STOP_LINE_PREFIX, + formatAgentStopLine, + parseAgentStopLine, parseSentinelFromLog, parseTickResultStatus, resolveTickResultStatus, @@ -178,3 +181,24 @@ describe("tick outcome from the watched last result", () => { expect(statusFile).toHaveBeenCalledWith("tick.log"); }); }); + +describe("agent stop line (run-plan -> countdown)", () => { + it("round-trips the reason through the printed line", () => { + const line = formatAgentStopLine({ kind: "stop", reason: "which database? operator decides" }); + expect(line).toBe( + "Agent requested stop: LOOP_TICK_RESULT: stop - which database? operator decides", + ); + expect(line.startsWith(AGENT_STOP_LINE_PREFIX)).toBe(true); + expect(parseAgentStopLine(line)).toBe("which database? operator decides"); + expect(parseAgentStopLine(`${line}\r`)).toBe("which database? operator decides"); + }); + + it("ignores a quoted sentinel that is not the runner's own line", () => { + expect(parseAgentStopLine("LOOP_TICK_RESULT: stop - plan exhausted")).toBeNull(); + expect( + parseAgentStopLine(` ${formatAgentStopLine({ kind: "stop", reason: "x" })}`), + ).toBeNull(); + expect(parseAgentStopLine(TICK_PROMPT)).toBeNull(); + expect(parseAgentStopLine("Agent requested stop: LOOP_TICK_RESULT: continue")).toBeNull(); + }); +}); diff --git a/packages/cli/src/plan-loop/sentinel.ts b/packages/cli/src/plan-loop/sentinel.ts index d4cba49..9770de5 100644 --- a/packages/cli/src/plan-loop/sentinel.ts +++ b/packages/cli/src/plan-loop/sentinel.ts @@ -148,6 +148,31 @@ export function formatSentinelLine(sentinel: TickSentinel): string { return ""; } +/** + * The terminal line `run-plan` prints when a tick ends on an agent stop + * (non-driver mode). `agent-kit countdown` reads it back from the child's + * output to tell an agent stop apart from a completed run, so both sides + * share this one format. + */ +export const AGENT_STOP_LINE_PREFIX = "Agent requested stop: "; + +export function formatAgentStopLine(sentinel: Extract): string { + return `${AGENT_STOP_LINE_PREFIX}${formatSentinelLine(sentinel)}`; +} + +const AGENT_STOP_LINE_RE = /^Agent requested stop: LOOP_TICK_RESULT: stop - (.*)$/; + +/** + * The stop reason of a {@link formatAgentStopLine} line, or null. Anchored at + * the line start: a quoted sentinel (the tick prompt, agent text) never + * matches on its own. + */ +export function parseAgentStopLine(line: string): string | null { + const m = AGENT_STOP_LINE_RE.exec(line.replace(/\r$/, "")); + if (!m) return null; + return m[1]?.trim() || "requested by agent"; +} + /** * Sentinel of the last turn the relay watched (`BackendRunResult.lastResult`). * Same precedence as `parseSentinelFromLog` on that turn: the result line diff --git a/packages/cli/src/plan-loop/stream-render.test.ts b/packages/cli/src/plan-loop/stream-render.test.ts index bd7fee2..fa991ce 100644 --- a/packages/cli/src/plan-loop/stream-render.test.ts +++ b/packages/cli/src/plan-loop/stream-render.test.ts @@ -13,7 +13,12 @@ import { QUEUE_DRIFT_ASK_LABELS, } from "./run-plan-all-orchestrator.js"; import { firstLineOfContent, parseStreamLine, summarizeToolInput } from "./stream-events.js"; -import { renderStreamEvent, StreamRenderer } from "./stream-render.js"; +import { + formatResultLine, + parseResultLine, + renderStreamEvent, + StreamRenderer, +} from "./stream-render.js"; /** * Fixture provenance: `claude-stream-run-plan-all-queue-drift.log` is a @@ -553,3 +558,79 @@ describe("recorded claude run (queue-drift Ask fixture)", () => { expect(terminal.text()).not.toMatch(/\{"type":/); }); }); + +describe("result line format and parse (countdown reads the cost back)", () => { + const costed = { + kind: "result", + ok: true, + status: "success", + costUsd: 1.2345, + durationMs: 1500, + turns: 2, + } as const; + + it("round-trips the printed cost, the status and the session-total mark", () => { + expect(parseResultLine(formatResultLine(costed))).toEqual({ + status: "success", + costUsd: 1.23, + sessionTotal: false, + }); + expect(parseResultLine(formatResultLine(costed, { sessionTotal: true }))).toEqual({ + status: "success", + costUsd: 1.23, + sessionTotal: true, + }); + const small = { + kind: "result", + ok: false, + status: "error_max_budget_usd", + costUsd: 0.0123, + } as const; + expect(parseResultLine(formatResultLine(small))).toEqual({ + status: "error_max_budget_usd", + costUsd: 0.0123, + sessionTotal: false, + }); + }); + + it("a result line without a cost is a result with cost null; other lines are null", () => { + const bare = { kind: "result", ok: true, status: "success", durationMs: 900 } as const; + expect(parseResultLine(formatResultLine(bare))).toEqual({ + status: "success", + costUsd: null, + sessionTotal: false, + }); + expect(parseResultLine("✦ result success")).toEqual({ + status: "success", + costUsd: null, + sessionTotal: false, + }); + expect(parseResultLine(` ${formatResultLine(costed)}`)).toBeNull(); + expect(parseResultLine(`quoted: ${formatResultLine(costed)}`)).toBeNull(); + expect(parseResultLine("✦ result success · $-1.00")?.costUsd).toBeNull(); + expect(parseResultLine("tick done")).toBeNull(); + }); + + it("reads the renderer's own output, colored or plain, CRLF included", () => { + const colored = renderAll( + '{"type":"result","subtype":"success","total_cost_usd":0.5,"num_turns":2}\n', + { isTTY: true, env: {}, columns: 120 }, + ); + expect(colored).not.toBe("✦ result success · $0.50 · 2 turns\n"); + expect(parseResultLine(colored.replace(/\n$/, "\r"))?.costUsd).toBe(0.5); + }); + + it("marks every costed result after the first of one stream as the session total", () => { + const stream = [ + '{"type":"result","subtype":"success","total_cost_usd":0.8,"num_turns":10}', + '{"type":"result","subtype":"success","total_cost_usd":1.35,"num_turns":5}', + "", + ].join("\n"); + const lines = renderAll(stream, PLAIN).trimEnd().split("\n"); + expect(lines).toEqual([ + "✦ result success · $0.80 · 10 turns", + "✦ result success · $1.35 session total · 5 turns", + ]); + expect(lines.map((l) => parseResultLine(l)?.sessionTotal)).toEqual([false, true]); + }); +}); diff --git a/packages/cli/src/plan-loop/stream-render.ts b/packages/cli/src/plan-loop/stream-render.ts index 9918ca9..349bae6 100644 --- a/packages/cli/src/plan-loop/stream-render.ts +++ b/packages/cli/src/plan-loop/stream-render.ts @@ -73,13 +73,73 @@ function formatCost(usd: number): string { return `$${usd.toFixed(usd < 0.1 ? 4 : 2)}`; } +type ResultEvent = Extract; + +/** Start of a rendered result line. `agent-kit countdown` reads these lines back. */ +export const RESULT_LINE_HEAD = `${SPACE_MARKS.star} result `; +/** + * Marks the cost of a later result event in the same stream: claude's + * `total_cost_usd` is the session's running total, so it replaces the stream's + * earlier cost instead of adding to it. + */ +export const RESULT_COST_SESSION_TOTAL = "session total"; + +/** + * The uncolored text of a result line. `sessionTotal` is set by the renderer + * on every costed result after the first one of its stream. Countdown parses + * this text with {@link parseResultLine}, so both sides share this format. + */ +export function formatResultLine( + event: ResultEvent, + opts: { sessionTotal?: boolean } = {}, +): string { + const parts = [`${RESULT_LINE_HEAD}${event.status}`]; + if (event.costUsd !== undefined) { + const cost = formatCost(event.costUsd); + parts.push(opts.sessionTotal ? `${cost} ${RESULT_COST_SESSION_TOTAL}` : cost); + } + if (event.durationMs !== undefined) parts.push(formatDuration(event.durationMs)); + else if (event.apiMs !== undefined) parts.push(`${formatDuration(event.apiMs)} api`); + if (event.turns !== undefined) { + parts.push(`${event.turns} turn${event.turns === 1 ? "" : "s"}`); + } + return parts.join(` ${SPACE_MARKS.tick} `); +} + +/** A result line read back: the printed cost (rounded as printed), or null when it had none. */ +export interface RenderedResult { + status: string; + costUsd: number | null; + /** The cost is the session's running total (replaces the stream's previous cost). */ + sessionTotal: boolean; +} + +const ESC = String.fromCharCode(27); +const ANSI_RE = new RegExp(`${ESC}\\[[0-9;]*m`, "g"); +const RESULT_LINE_RE = new RegExp( + `^${RESULT_LINE_HEAD}(\\S+)(?: ${SPACE_MARKS.tick} \\$(\\d+(?:\\.\\d+)?)( ${RESULT_COST_SESSION_TOTAL})?)?(?: ${SPACE_MARKS.tick} .*)?$`, +); + +/** + * Parse a {@link formatResultLine} line (color codes and a trailing CR are + * ignored), or null when the line is not one. Anchored on the whole line: a + * result line quoted inside other text never matches. + */ +export function parseResultLine(line: string): RenderedResult | null { + const m = RESULT_LINE_RE.exec(line.replace(ANSI_RE, "").replace(/\r$/, "")); + if (!m) return null; + const cost = m[2] === undefined ? null : Number(m[2]); + const costUsd = cost !== null && Number.isFinite(cost) ? cost : null; + return { status: m[1] ?? "", costUsd, sessionTotal: costUsd !== null && m[3] !== undefined }; +} + /** * Render one parsed event as a terminal line (without trailing newline), or * null when the event prints nothing. Assistant text is returned verbatim. */ export function renderStreamEvent( event: StreamEvent, - opts: { color: boolean; columns: number }, + opts: { color: boolean; columns: number; sessionTotal?: boolean }, ): string | null { const width = Math.max(MIN_COLUMNS, opts.columns); const color = opts.color; @@ -98,16 +158,12 @@ export function renderStreamEvent( const text = line ? `${head} ${SPACE_MARKS.tick} ${line}` : head; return paint(event.ok ? LABEL_MUTED : STATUS_ERR, text, color); } - case "result": { - const parts = [`${SPACE_MARKS.star} result ${event.status}`]; - if (event.costUsd !== undefined) parts.push(formatCost(event.costUsd)); - if (event.durationMs !== undefined) parts.push(formatDuration(event.durationMs)); - else if (event.apiMs !== undefined) parts.push(`${formatDuration(event.apiMs)} api`); - if (event.turns !== undefined) { - parts.push(`${event.turns} turn${event.turns === 1 ? "" : "s"}`); - } - return paint(event.ok ? STATUS_OK : STATUS_ERR, parts.join(` ${SPACE_MARKS.tick} `), color); - } + case "result": + return paint( + event.ok ? STATUS_OK : STATUS_ERR, + formatResultLine(event, { sessionTotal: opts.sessionTotal === true }), + color, + ); case "hook": { const detail = event.detail ? ` (${event.detail})` : ""; return paint( @@ -145,6 +201,8 @@ export class StreamRenderer implements StreamSink { private pending = ""; private dropped = false; private textOpen = false; + /** A costed result was already rendered: later costs are the session's running total. */ + private costSeen = false; private readonly decoder = new StringDecoder("utf8"); private readonly write: (text: string) => void; private readonly color: boolean; @@ -196,7 +254,13 @@ export class StreamRenderer implements StreamSink { private renderLine(line: string): void { for (const event of parseStreamLine(line)) { - const rendered = renderStreamEvent(event, { color: this.color, columns: this.columns }); + const costed = event.kind === "result" && event.costUsd !== undefined; + const rendered = renderStreamEvent(event, { + color: this.color, + columns: this.columns, + sessionTotal: costed && this.costSeen, + }); + if (costed) this.costSeen = true; if (rendered === null) continue; if (event.kind === "text") { this.write(rendered); diff --git a/packages/cli/src/readiness/env-checks.ts b/packages/cli/src/readiness/env-checks.ts index 8ed9e56..3378400 100644 --- a/packages/cli/src/readiness/env-checks.ts +++ b/packages/cli/src/readiness/env-checks.ts @@ -78,13 +78,11 @@ export interface AssessEnvironmentOptions { readFileImpl?: (filePath: string) => Promise; } -const CLI_PACKAGE_JSON_REL = path.join( - "lib", - "node_modules", - "@dadado", - "agent-kit-cli", - "package.json", -); +/** Scoped npm names of this CLI (current and post-rename), as path segments. */ +const CLI_PACKAGE_SEGMENTS = [ + ["@dadado", "agent-kit-cli"], + ["@missionkit", "cli"], +] as const; /** Shim targets: quotes/spaces stay outside the match so `@scope` paths still hit. */ const DIST_INDEX_RE = /(?:\$\{basedir\}|\$basedir)?[^'"\s;]*dist\/index\.js/g; @@ -143,10 +141,12 @@ export async function readBinVersion( if (path.basename(realBin) === "index.js" && path.basename(path.dirname(realBin)) === "dist") { candidates.push(packageJsonFromDistIndex(realBin)); } - candidates.push( - path.join(binDir, "..", CLI_PACKAGE_JSON_REL), - path.join(binDir, "..", "node_modules", "@dadado", "agent-kit-cli", "package.json"), - ); + for (const [scope, name] of CLI_PACKAGE_SEGMENTS) { + candidates.push( + path.join(binDir, "..", "lib", "node_modules", scope, name, "package.json"), + path.join(binDir, "..", "node_modules", scope, name, "package.json"), + ); + } try { // Only a small shim is worth scanning; never pull in the whole CLI bundle. if ((await stat(realBin)).size < SHIM_MAX_BYTES) { diff --git a/packages/cli/src/readiness/install-health.test.ts b/packages/cli/src/readiness/install-health.test.ts new file mode 100644 index 0000000..5eec0d0 --- /dev/null +++ b/packages/cli/src/readiness/install-health.test.ts @@ -0,0 +1,419 @@ +import { describe, expect, it, vi } from "vitest"; +import { + assessGlobalCli, + assessHomeInstall, + assessInstallHealth, + assessNodeManager, + assessRegistryPin, + classifyNodeManagerPath, + homeRelative, + miseToolEntry, + npmLatestCheckAllowed, + packageForBin, +} from "./install-health.js"; + +const HOME = "/home/op"; + +describe("classifyNodeManagerPath", () => { + it.each([ + // mise (POSIX) and its realpath into the package + ["/home/op/.local/share/mise/installs/node/26.8.2/bin/agent-kit", "linux", "mise", "26.8.2"], + [ + "/home/op/.local/share/mise/installs/node/26.8.2/lib/node_modules/@dadado/agent-kit-cli/dist/index.js", + "linux", + "mise", + "26.8.2", + ], + // mise (Windows: no bin/ segment) + [ + "C:\\Users\\op\\AppData\\Local\\mise\\installs\\node\\22.12.0\\agent-kit.cmd", + "win32", + "mise", + "22.12.0", + ], + // nvm + ["/home/op/.nvm/versions/node/v22.12.0/bin/agent-kit", "linux", "nvm", "v22.12.0"], + ["/Users/op/.nvm/versions/node/v24.1.0/bin/missionkit", "darwin", "nvm", "v24.1.0"], + // fnm (realpath of the fnm_multishells PATH entry) + [ + "/home/op/.local/share/fnm/node-versions/v22.12.0/installation/bin/agent-kit", + "linux", + "fnm", + "v22.12.0", + ], + [ + "/Users/op/Library/Application Support/fnm/node-versions/v24.0.0/installation/bin/agent-kit", + "darwin", + "fnm", + "v24.0.0", + ], + [ + "C:\\Users\\op\\AppData\\Roaming\\fnm\\node-versions\\v22.12.0\\installation\\agent-kit.cmd", + "win32", + "fnm", + "v22.12.0", + ], + // nvm-windows (realpath of the NVM_SYMLINK junction) + [ + "C:\\Users\\op\\AppData\\Roaming\\nvm\\v22.12.0\\agent-kit.cmd", + "win32", + "nvm-windows", + "v22.12.0", + ], + ] as const)("%s (%s) -> %s %s", (p, platform, manager, version) => { + expect(classifyNodeManagerPath(p, platform)).toEqual({ manager, nodeVersion: version }); + }); + + it.each([ + // A CLI installed by the recommended mise tool entry is clean. + [ + "/home/op/.local/share/mise/installs/npm-dadado-agent-kit-cli/6.22.1/bin/agent-kit", + "linux", + "other", + ], + ["/home/op/.local/share/mise/shims/agent-kit", "linux", "mise-shim"], + ["/home/op/.volta/bin/agent-kit", "linux", "volta"], + ["C:\\Users\\op\\AppData\\Local\\Volta\\bin\\agent-kit.cmd", "win32", "volta"], + ["/opt/homebrew/bin/agent-kit", "darwin", "homebrew"], + ["/usr/local/Cellar/node/24.0.0/bin/agent-kit", "darwin", "homebrew"], + ["/home/linuxbrew/.linuxbrew/bin/agent-kit", "linux", "homebrew"], + ["/usr/bin/agent-kit", "linux", "other"], + ["/usr/local/bin/agent-kit", "linux", "other"], + // A POSIX path with an `nvm/vX` segment is not nvm-windows. + ["/srv/nvm/v22.12.0/bin/agent-kit", "linux", "other"], + ] as const)("%s (%s) -> %s, not flagged", (p, platform, manager) => { + expect(classifyNodeManagerPath(p, platform).manager).toBe(manager); + }); +}); + +describe("assessNodeManager", () => { + it("mise: warns and prints the exact mise tool entry; names the orphaned version", () => { + const result = assessNodeManager({ + binPath: `${HOME}/.local/share/mise/installs/node/26.8.2/bin/agent-kit`, + binRealPath: `${HOME}/.local/share/mise/installs/node/26.8.2/lib/node_modules/@dadado/agent-kit-cli/dist/index.js`, + nodeExecPath: `${HOME}/.local/share/mise/installs/node/26.13.1/bin/node`, + platform: "linux", + homeDir: HOME, + }); + expect(result.severity).toBe("warning"); + expect(result.fixKind).toBe("config-line"); + expect(result.fix).toBe( + '"npm:@dadado/agent-kit-cli" = { version = "latest", allow_low_downloads = true, minimum_release_age = "0s" }', + ); + expect(result.detail).toContain("~/.local/share/mise/installs/node/26.8.2/bin/agent-kit"); + expect(result.detail).toContain("node now resolves to 26.13.1"); + expect(result.detail).toContain("~/.config/mise/config.toml"); + expect(result.detail).not.toContain(HOME); + }); + + it("mise: missionkit binary gets the @missionkit/cli entry", () => { + const result = assessNodeManager({ + binPath: `${HOME}/.local/share/mise/installs/node/26.8.2/bin/missionkit`, + binRealPath: null, + nodeExecPath: null, + platform: "linux", + homeDir: HOME, + }); + expect(result.fix).toBe(miseToolEntry("@missionkit/cli")); + }); + + it("nvm: reinstall-packages-from the old version, plus the fixed-prefix alternative", () => { + const result = assessNodeManager({ + binPath: `${HOME}/.nvm/versions/node/v22.12.0/bin/agent-kit`, + binRealPath: `${HOME}/.nvm/versions/node/v22.12.0/lib/node_modules/@dadado/agent-kit-cli/dist/index.js`, + nodeExecPath: `${HOME}/.nvm/versions/node/v24.1.0/bin/node`, + platform: "linux", + homeDir: HOME, + }); + expect(result.severity).toBe("warning"); + expect(result.fix).toBe("nvm install v24.1.0 --reinstall-packages-from=v22.12.0"); + expect(result.fixKind).toBe("command"); + expect(result.detail).toContain("npm i -g --prefix ~/.local @dadado/agent-kit-cli"); + }); + + it("nvm: same version as the running node -> placeholder", () => { + const result = assessNodeManager({ + binPath: `${HOME}/.nvm/versions/node/v22.12.0/bin/agent-kit`, + binRealPath: null, + nodeExecPath: `${HOME}/.nvm/versions/node/v22.12.0/bin/node`, + platform: "linux", + homeDir: HOME, + }); + expect(result.fix).toBe("nvm install --reinstall-packages-from=v22.12.0"); + // A placeholder is not a runnable command: never offered as a terminal copy. + expect(result.fixKind).toBe("template"); + expect(result.detail).not.toContain("orphaned"); + }); + + it("fnm: the PATH entry is a multishell symlink; the realpath shows the version", () => { + const result = assessNodeManager({ + binPath: `${HOME}/.local/state/fnm_multishells/1234_1700000000000/bin/agent-kit`, + binRealPath: `${HOME}/.local/share/fnm/node-versions/v22.12.0/installation/lib/node_modules/@dadado/agent-kit-cli/dist/index.js`, + nodeExecPath: null, + platform: "linux", + homeDir: HOME, + }); + expect(result.severity).toBe("warning"); + expect(result.fix).toBe("fnm use && npm i -g @dadado/agent-kit-cli"); + expect(result.fixKind).toBe("template"); + }); + + it("nvm-windows: the NVM_SYMLINK junction resolves into %NVM_HOME%", () => { + const result = assessNodeManager({ + binPath: "C:\\Program Files\\nodejs\\agent-kit.cmd", + binRealPath: "C:\\Users\\op\\AppData\\Roaming\\nvm\\v22.12.0\\agent-kit.cmd", + nodeExecPath: "C:\\Users\\op\\AppData\\Roaming\\nvm\\v24.1.0\\node.exe", + platform: "win32", + homeDir: "C:\\Users\\op", + }); + expect(result.severity).toBe("warning"); + expect(result.fix).toBe("nvm use v24.1.0 && npm i -g @dadado/agent-kit-cli"); + }); + + it.each([ + [`${HOME}/.volta/bin/agent-kit`, "Volta"], + ["/opt/homebrew/bin/agent-kit", "Homebrew node"], + ["/usr/bin/agent-kit", "a node install that keeps globals"], + [`${HOME}/.local/share/mise/shims/agent-kit`, "a mise shim"], + ])("%s is not flagged", (binPath, kind) => { + const result = assessNodeManager({ + binPath, + binRealPath: null, + nodeExecPath: null, + platform: binPath.startsWith("/opt") ? "darwin" : "linux", + homeDir: HOME, + }); + expect(result.severity).toBe("ok"); + expect(result.fix).toBeNull(); + expect(result.detail).toContain(kind); + }); + + it("no CLI on PATH is ok", () => { + expect( + assessNodeManager({ + binPath: null, + binRealPath: null, + nodeExecPath: null, + platform: "linux", + homeDir: HOME, + }).severity, + ).toBe("ok"); + }); +}); + +describe("assessGlobalCli", () => { + const base = { + binPath: `${HOME}/.npm-global/bin/agent-kit`, + binVersion: "6.19.1", + latestChecked: true, + homeDir: HOME, + }; + + it("behind npm latest: warning with the package that answered", () => { + const result = assessGlobalCli({ + ...base, + latest: { packageName: "@dadado/agent-kit-cli", version: "6.22.0" }, + }); + expect(result.severity).toBe("warning"); + expect(result.detail).toContain("v6.19.1 at ~/.npm-global/bin/agent-kit"); + expect(result.fix).toBe("npm i -g @dadado/agent-kit-cli@6.22.0"); + }); + + it("the renamed package can be the newest", () => { + const result = assessGlobalCli({ + ...base, + latest: { packageName: "@missionkit/cli", version: "7.0.0" }, + }); + expect(result.fix).toBe("npm i -g @missionkit/cli@7.0.0"); + }); + + it("current or ahead is ok", () => { + expect( + assessGlobalCli({ + ...base, + latest: { packageName: "@dadado/agent-kit-cli", version: "6.19.1" }, + }).severity, + ).toBe("ok"); + expect( + assessGlobalCli({ + ...base, + latest: { packageName: "@dadado/agent-kit-cli", version: "6.0.0" }, + }).detail, + ).toContain("ahead"); + }); + + it("npm unreachable or not checked fails open as info", () => { + const offline = assessGlobalCli({ ...base, latest: null }); + expect(offline.severity).toBe("info"); + expect(offline.detail).toContain("did not answer"); + const skipped = assessGlobalCli({ ...base, latestChecked: false, latest: null }); + expect(skipped.severity).toBe("info"); + expect(skipped.detail).toContain("not checked"); + }); + + it("no binary on PATH is info, naming both binaries", () => { + const result = assessGlobalCli({ ...base, binPath: null, binVersion: null, latest: null }); + expect(result.severity).toBe("info"); + expect(result.detail).toContain("agent-kit or missionkit"); + expect(result.fix).toBeNull(); + }); +}); + +describe("assessHomeInstall", () => { + const base = { + homeDir: HOME, + cwd: `${HOME}/code/app`, + presentRels: [".cursor/agent-kit.json", ".cursor/rules", ".cursor/hooks.json"], + repoVersion: "6.22.0", + cliVersion: "6.22.0", + }; + + it("older home install: warning naming the paths, nothing moved", () => { + const result = assessHomeInstall({ ...base, homeManifestVersion: "3.0.0" }); + expect(result.severity).toBe("warning"); + expect(result.detail).toContain("v3.0.0 is older than this repo's kit v6.22.0"); + expect(result.detail).toContain( + "~/.cursor/agent-kit.json, ~/.cursor/rules/, ~/.cursor/hooks.json", + ); + expect(result.detail).toContain("Nothing was moved"); + // Naming the paths is the whole remedy: no one-click rewrite of ~/.cursor. + expect(result.fix).toBeNull(); + }); + + it("no home manifest, current home install, or cwd is home: ok", () => { + expect(assessHomeInstall({ ...base, homeManifestVersion: null }).severity).toBe("ok"); + expect(assessHomeInstall({ ...base, homeManifestVersion: "6.22.0" }).severity).toBe("ok"); + expect(assessHomeInstall({ ...base, cwd: HOME, homeManifestVersion: "3.0.0" }).severity).toBe( + "ok", + ); + }); + + it("repo without a kit compares against the running CLI", () => { + const result = assessHomeInstall({ ...base, repoVersion: null, homeManifestVersion: "6.0.0" }); + expect(result.detail).toContain("the running CLI v6.22.0"); + }); +}); + +describe("assessRegistryPin", () => { + const base = { + hasManifest: true, + installedVersion: "5.9.0", + registryUrl: "https://github.com/agent-kit-startup/agent-kit.git", + cliVersion: "5.9.0", + }; + + it("semver pin older than the CLI: warning with update --ref", () => { + const result = assessRegistryPin({ ...base, registryRef: "v5.4.0" }); + expect(result.severity).toBe("warning"); + expect(result.fix).toBe("agent-kit update --ref v5.9.0"); + }); + + it.each([ + ["v5.9.0", "current"], + ["main", "branch"], + [null, "No registry.ref"], + ])("%s is ok", (ref, word) => { + const result = assessRegistryPin({ ...base, registryRef: ref }); + expect(result.severity).toBe("ok"); + expect(result.detail).toContain(word); + }); + + it("factory registry and missing manifest are ok", () => { + expect( + assessRegistryPin({ + ...base, + registryUrl: "https://github.com/agent-kit-startup/agent-kit-dev.git", + registryRef: "v1.0.0", + }).severity, + ).toBe("ok"); + expect( + assessRegistryPin({ ...base, hasManifest: false, installedVersion: null, registryRef: null }) + .severity, + ).toBe("ok"); + }); +}); + +describe("assessInstallHealth (gatherer with injected fs)", () => { + it("home install fixture + mise path fixture -> warning report, no real fs", async () => { + const files: Record = { + [`${HOME}/.cursor/agent-kit.json`]: JSON.stringify({ version: "3.0.0" }), + }; + const existing = new Set([`${HOME}/.cursor/agent-kit.json`, `${HOME}/.cursor/hooks.json`]); + const readFileImpl = vi.fn(async (p: string) => { + const body = files[p]; + if (body === undefined) throw new Error(`ENOENT ${p}`); + return body; + }); + const report = await assessInstallHealth({ + cwd: `${HOME}/code/app`, + cliVersion: "6.22.1", + npm: { checked: true, latest: { packageName: "@dadado/agent-kit-cli", version: "6.22.1" } }, + binPath: `${HOME}/.local/share/mise/installs/node/26.8.2/bin/agent-kit`, + binVersion: "6.16.1", + manifest: { version: "6.22.0", registryUrl: null, registryRef: "v6.20.0" }, + platform: "linux", + homeDir: HOME, + nodeExecPath: `${HOME}/.local/share/mise/installs/node/26.13.1/bin/node`, + realpathImpl: async (p) => p, + readFileImpl, + existsImpl: async (p) => existing.has(p), + }); + const by = Object.fromEntries(report.checks.map((c) => [c.id, c])); + expect(report.status).toBe("warning"); + expect(report.checks.map((c) => c.id)).toEqual([ + "global-cli", + "node-manager", + "home-install", + "registry-pin", + ]); + expect(by["global-cli"]?.severity).toBe("warning"); + // Reinstalling into the same node dir would vanish again: defer to node-manager. + expect(by["global-cli"]?.fix).toBeNull(); + expect(by["global-cli"]?.detail).toContain("use the Node version manager fix"); + expect(by["node-manager"]?.fix).toBe(miseToolEntry("@dadado/agent-kit-cli")); + expect(by["home-install"]?.detail).toContain("~/.cursor/agent-kit.json, ~/.cursor/hooks.json"); + expect(by["registry-pin"]?.fix).toBe("agent-kit update --ref v6.22.1"); + expect(JSON.stringify(report)).not.toContain(`${HOME}/`); + }); + + it("clean machine -> ok", async () => { + const report = await assessInstallHealth({ + cwd: `${HOME}/code/app`, + cliVersion: "6.22.1", + npm: { checked: false, latest: null }, + binPath: "/usr/local/bin/agent-kit", + binVersion: "6.22.1", + manifest: { version: "6.22.1", registryUrl: null, registryRef: "main" }, + platform: "linux", + homeDir: HOME, + nodeExecPath: "/usr/bin/node", + realpathImpl: async (p) => p, + readFileImpl: async () => { + throw new Error("ENOENT"); + }, + existsImpl: async () => false, + }); + expect(report.status).toBe("ok"); + }); +}); + +describe("helpers", () => { + it("npmLatestCheckAllowed: off under CI and with explicit updateCheck.enabled false only", () => { + expect(npmLatestCheckAllowed({}, null)).toBe(true); + expect(npmLatestCheckAllowed({}, { updateCheck: {} })).toBe(true); + expect(npmLatestCheckAllowed({ CI: "true" }, null)).toBe(false); + expect(npmLatestCheckAllowed({ CI: "false" }, null)).toBe(true); + expect(npmLatestCheckAllowed({}, { updateCheck: { enabled: false } })).toBe(false); + }); + + it("packageForBin maps both binaries", () => { + expect(packageForBin("agent-kit")).toBe("@dadado/agent-kit-cli"); + expect(packageForBin("missionkit.cmd")).toBe("@missionkit/cli"); + }); + + it("homeRelative handles both separators", () => { + expect(homeRelative("/home/op/x", "/home/op")).toBe("~/x"); + expect(homeRelative("C:\\Users\\op\\x", "C:\\Users\\op")).toBe("~/x"); + expect(homeRelative("/usr/bin/x", "/home/op")).toBe("/usr/bin/x"); + }); +}); diff --git a/packages/cli/src/readiness/install-health.ts b/packages/cli/src/readiness/install-health.ts new file mode 100644 index 0000000..4d9fc7e --- /dev/null +++ b/packages/cli/src/readiness/install-health.ts @@ -0,0 +1,552 @@ +/** + * Install health for `agent-kit doctor` and Mission Control Health. + * + * Four read-only checks about how the kit is installed on this machine, + * not about the repository: + * (a) global-cli the CLI on PATH vs npm `latest` (both package names); + * (b) node-manager the CLI lives inside a per-version node dir (mise, nvm, + * nvm-windows, fnm), so its globals vanish on the next node + * switch or patch; + * (c) home-install a home-level kit install under `~/.cursor` older than + * this repo's kit (its rules/hooks apply in every workspace); + * (d) registry-pin a semver `registry.ref` pin older than the CLI, so + * `update` would re-apply an old tree. + * + * Every check is a pure function over injected inputs (paths, env, versions, + * fetched latest). The gatherer reads the filesystem through injectable + * helpers and never moves, installs or writes anything except the snapshot + * that Mission Control reads (`.cursor/context/install-health.json`). + */ + +import { access, readFile, realpath } from "node:fs/promises"; +import { homedir } from "node:os"; +import path from "node:path"; +import { + CLI_NPM_PACKAGES, + type CliNpmLatest, + compareSemver, + isFactoryOrDevRegistry, + normalizeSemver, + updateCheckAllowed, +} from "../lifecycle/check-updates.js"; +import { writeJson } from "../utils/fs.js"; + +export const INSTALL_HEALTH_SNAPSHOT_RELATIVE_PATH = ".cursor/context/install-health.json"; + +/** + * The working mise tool entry (checked 2026-11-24, mise 2026.11.10, Linux). + * A bare `mise use -g npm:` fails: the npm backend refuses packages under + * 1000 weekly downloads, and the default minimum release age resolves `latest` + * to an older release. + */ +export function miseToolEntry(packageName: string): string { + return `"npm:${packageName}" = { version = "latest", allow_low_downloads = true, minimum_release_age = "0s" }`; +} + +export type InstallHealthCheckId = "global-cli" | "node-manager" | "home-install" | "registry-pin"; + +/** `info` = nothing to fix, but the check could not fully run (offline, no binary, …). */ +export type InstallHealthSeverity = "ok" | "warning" | "info"; + +export interface InstallHealthCheck { + id: InstallHealthCheckId; + label: string; + severity: InstallHealthSeverity; + /** One line: what was found and where (paths home-relative). */ + detail: string; + /** Copy-paste remedy, or null when nothing needs fixing. */ + fix: string | null; + /** + * `command` runs as is in a terminal; `config-line` goes into the file named + * in `detail`; `template` is a command with a placeholder (``) the + * operator fills in first, so Mission Control never offers it as a terminal copy. + */ + fixKind: "command" | "config-line" | "template" | null; +} + +export interface InstallHealthReport { + status: "ok" | "warning"; + checks: InstallHealthCheck[]; +} + +const LABELS: Record = { + "global-cli": "Global CLI vs npm latest", + "node-manager": "Node version manager", + "home-install": "Home-level install", + "registry-pin": "Registry pin", +}; + +function check( + id: InstallHealthCheckId, + severity: InstallHealthSeverity, + detail: string, + fix: string | null = null, + fixKind: InstallHealthCheck["fixKind"] = null, +): InstallHealthCheck { + return { id, label: LABELS[id], severity, detail, fix, fixKind: fix ? fixKind : null }; +} + +/** `~/...` for paths under `homeDir` (either separator style). */ +export function homeRelative(p: string, homeDir: string): string { + if (!homeDir) return p; + const norm = (s: string) => s.replace(/\\/g, "/").replace(/\/+$/, ""); + const home = norm(homeDir); + const target = norm(p); + if (target === home) return "~"; + if (target.startsWith(`${home}/`)) return `~${target.slice(home.length)}`; + return p; +} + +/** npm package that owns a CLI binary name (`agent-kit` → `@dadado/agent-kit-cli`). */ +export function packageForBin(binName: string | null): string { + const base = (binName ?? "").replace(/\.(cmd|exe|bat|ps1)$/i, ""); + return CLI_NPM_PACKAGES.find((pkg) => pkg.bin === base)?.name ?? CLI_NPM_PACKAGES[0].name; +} + +// ── (a) global CLI vs npm latest ──────────────────────────────────────────── + +export interface GlobalCliInput { + /** First PATH hit for `agent-kit` / `missionkit`, or null. */ + binPath: string | null; + /** Version read from that binary's package.json, or null. */ + binVersion: string | null; + /** Whether doctor asked npm at all (false: CI, opt-out or a test without a fetcher). */ + latestChecked: boolean; + /** Highest npm `latest` across both package names; null when npm did not answer. */ + latest: CliNpmLatest | null; + homeDir: string; +} + +export function assessGlobalCli(input: GlobalCliInput): InstallHealthCheck { + if (!input.binPath) { + const names = CLI_NPM_PACKAGES.map((pkg) => pkg.bin).join(" or "); + return check("global-cli", "info", `No ${names} binary on PATH (npx-only use is fine)`); + } + const where = homeRelative(input.binPath, input.homeDir); + const installed = input.binVersion ? normalizeSemver(input.binVersion) : null; + if (!installed) { + return check("global-cli", "info", `Could not read the version of ${where}`); + } + if (!input.latestChecked) { + return check( + "global-cli", + "info", + `v${installed} at ${where}; npm latest not checked (CI or updateCheck.enabled: false)`, + ); + } + if (!input.latest) { + return check( + "global-cli", + "info", + `v${installed} at ${where}; npm registry did not answer, not compared`, + ); + } + const { version: latest, packageName } = input.latest; + if (compareSemver(installed, latest) < 0) { + return check( + "global-cli", + "warning", + `v${installed} at ${where} is behind npm latest v${latest} (${packageName})`, + `npm i -g ${packageName}@${latest}`, + "command", + ); + } + return check( + "global-cli", + "ok", + compareSemver(installed, latest) === 0 + ? `v${installed} at ${where} matches npm latest` + : `v${installed} at ${where} is ahead of npm latest v${latest} (dev build)`, + ); +} + +// ── (b) per-version node managers ─────────────────────────────────────────── + +export type NodeManager = + | "mise" + | "nvm" + | "nvm-windows" + | "fnm" + | "volta" + | "homebrew" + | "mise-shim" + | "other"; + +export interface NodeManagerMatch { + manager: NodeManager; + /** Node version dir the path lives in (per-version managers only). */ + nodeVersion: string | null; +} + +/** Per-version managers drop npm globals when node changes; the rest keep them. */ +export const PER_VERSION_MANAGERS: ReadonlySet = new Set([ + "mise", + "nvm", + "nvm-windows", + "fnm", +]); + +/** + * Which node manager owns `p` (a PATH hit or its realpath), from the string + * alone. Windows paths are matched case-insensitively with either separator. + * mise shims cannot be classified from a path (their realpath is mise itself), + * so they are reported as `mise-shim` and never flagged. + */ +export function classifyNodeManagerPath(p: string, platform: NodeJS.Platform): NodeManagerMatch { + const win = platform === "win32"; + const norm = p.replace(/\\/g, "/"); + const s = win ? norm.toLowerCase() : norm; + const version = (re: RegExp): string | null => { + const m = re.exec(s); + return m?.[1] ?? null; + }; + + // mise: …/mise/installs/node//bin (POSIX) or …\mise\installs\node\\ (Windows). + // Anchored to installs/node/ so a CLI installed as a mise npm: tool + // (…/mise/installs/npm-…) is clean. + const mise = version(/\/mise\/installs\/node\/([^/]+)\//); + if (mise) return { manager: "mise", nodeVersion: mise }; + if (/\/mise\/shims\//.test(s)) return { manager: "mise-shim", nodeVersion: null }; + + // nvm (POSIX): $NVM_DIR/versions/node/v/bin, NVM_DIR usually ~/.nvm. + const nvm = version(/\/\.?nvm\/versions\/node\/(v?\d[^/]*)\//); + if (nvm) return { manager: "nvm", nodeVersion: nvm }; + + // fnm: …/fnm/node-versions//installation/bin (POSIX, macOS) or + // …\fnm\node-versions\\installation\ (Windows). The PATH entry is a + // fnm_multishells symlink; its realpath lands here. + const fnm = version(/\/\.?fnm\/node-versions\/([^/]+)\/installation\//); + if (fnm) return { manager: "fnm", nodeVersion: fnm }; + + // nvm-windows: %NVM_HOME%\v\ (default %APPDATA%\nvm). The PATH entry is + // the NVM_SYMLINK junction (C:\Program Files\nodejs); its realpath lands here. + if (win) { + const nvmWin = version(/\/nvm\/(v\d+\.\d+\.\d+[^/]*)\//); + if (nvmWin) return { manager: "nvm-windows", nodeVersion: nvmWin }; + } + + if (/\/\.?volta\//.test(s)) return { manager: "volta", nodeVersion: null }; + if (/^\/opt\/homebrew\/|^\/usr\/local\/cellar\/|\/\.linuxbrew\//i.test(norm)) { + return { manager: "homebrew", nodeVersion: null }; + } + return { manager: "other", nodeVersion: null }; +} + +export interface NodeManagerInput { + /** PATH hit of the CLI binary, or null when none. */ + binPath: string | null; + /** Realpath of that hit (symlinks followed), or null when unreadable. */ + binRealPath: string | null; + /** The running node (process.execPath), to name the version node resolves to now. */ + nodeExecPath: string | null; + platform: NodeJS.Platform; + homeDir: string; +} + +function nodeManagerFix( + manager: NodeManager, + packageName: string, + oldVersion: string, + newVersion: string | null, +): { fix: string; fixKind: "command" | "config-line" | "template"; also?: string } { + const known = Boolean(newVersion && newVersion !== oldVersion); + const target = known ? (newVersion as string) : ""; + const kind = known ? "command" : "template"; + switch (manager) { + case "mise": + return { fix: miseToolEntry(packageName), fixKind: "config-line" }; + case "nvm": + return { + fix: `nvm install ${target} --reinstall-packages-from=${oldVersion}`, + fixKind: kind, + also: `or install under a fixed prefix outside nvm: npm i -g --prefix ~/.local ${packageName} (with ~/.local/bin on PATH)`, + }; + case "nvm-windows": + return { fix: `nvm use ${target} && npm i -g ${packageName}`, fixKind: kind }; + default: + return { fix: `fnm use ${target} && npm i -g ${packageName}`, fixKind: kind }; + } +} + +export function assessNodeManager(input: NodeManagerInput): InstallHealthCheck { + if (!input.binPath) { + return check("node-manager", "ok", "No global CLI on PATH; nothing tied to a node version"); + } + const candidates = [input.binRealPath, input.binPath].filter((p): p is string => Boolean(p)); + let match: NodeManagerMatch = { manager: "other", nodeVersion: null }; + for (const candidate of candidates) { + const found = classifyNodeManagerPath(candidate, input.platform); + if (PER_VERSION_MANAGERS.has(found.manager)) { + match = found; + break; + } + if (match.manager === "other") match = found; + } + const where = homeRelative(input.binPath, input.homeDir); + if (!PER_VERSION_MANAGERS.has(match.manager) || !match.nodeVersion) { + const kind = + match.manager === "volta" + ? "Volta" + : match.manager === "homebrew" + ? "Homebrew node" + : match.manager === "mise-shim" + ? "a mise shim (not classified)" + : "a node install that keeps globals"; + return check("node-manager", "ok", `${where} comes from ${kind}`); + } + + const running = input.nodeExecPath + ? classifyNodeManagerPath(input.nodeExecPath, input.platform) + : null; + const runningVersion = running && running.manager === match.manager ? running.nodeVersion : null; + const packageName = packageForBin(path.basename(input.binPath)); + const remedy = nodeManagerFix(match.manager, packageName, match.nodeVersion, runningVersion); + const drift = + runningVersion && runningVersion !== match.nodeVersion + ? `; node now resolves to ${runningVersion}, so this copy is already orphaned` + : ""; + const where2 = + match.manager === "mise" + ? "; add the fix line under [tools] in ~/.config/mise/config.toml" + : remedy.also + ? `; ${remedy.also}` + : ""; + return check( + "node-manager", + "warning", + `${where} lives in ${match.manager} node ${match.nodeVersion}: npm globals vanish on the next node switch or patch${drift}${where2}`, + remedy.fix, + remedy.fixKind, + ); +} + +// ── (c) home-level install under ~/.cursor ────────────────────────────────── + +/** Paths a home-level install leaves under `~/.cursor` that apply in every workspace. */ +export const HOME_INSTALL_RELS = [ + ".cursor/agent-kit.json", + ".cursor/rules", + ".cursor/hooks.json", + ".cursor/commands", +] as const; + +export interface HomeInstallInput { + homeDir: string; + cwd: string; + /** `version` of `~/.cursor/agent-kit.json`, or null when there is no such manifest. */ + homeManifestVersion: string | null; + /** Which of HOME_INSTALL_RELS exist under home. */ + presentRels: string[]; + /** This repo's manifest version, or null when the repo has no kit. */ + repoVersion: string | null; + /** The running CLI version, used when the repo has no kit. */ + cliVersion: string; +} + +export function assessHomeInstall(input: HomeInstallInput): InstallHealthCheck { + if (path.resolve(input.cwd) === path.resolve(input.homeDir)) { + return check("home-install", "ok", "Running in the home directory: this is the home install"); + } + if (!input.homeManifestVersion) { + return check("home-install", "ok", "No home-level install (~/.cursor/agent-kit.json absent)"); + } + const home = normalizeSemver(input.homeManifestVersion); + const reference = normalizeSemver(input.repoVersion ?? input.cliVersion); + const against = input.repoVersion ? "this repo's kit" : "the running CLI"; + if (!home || !reference) { + return check( + "home-install", + "info", + `Home-level install v${input.homeManifestVersion} under ~/.cursor; version not comparable`, + ); + } + if (compareSemver(home, reference) >= 0) { + return check("home-install", "ok", `Home-level install v${home} is current with ${against}`); + } + const paths = input.presentRels + .map((rel) => `~/${rel}${rel.endsWith(".json") ? "" : "/"}`) + .join(", "); + // No fix line on purpose: update or remove the home install is the + // operator's call; doctor only names the paths and never moves them. + return check( + "home-install", + "warning", + `Home-level install v${home} is older than ${against} v${reference}; its rules and hooks still apply in every workspace: ${paths}. Nothing was moved`, + ); +} + +// ── (d) stale registry.ref pin ────────────────────────────────────────────── + +export interface RegistryPinInput { + /** Manifest present at all. */ + hasManifest: boolean; + installedVersion: string | null; + registryUrl: string | null; + registryRef: string | null; + cliVersion: string; +} + +export function assessRegistryPin(input: RegistryPinInput): InstallHealthCheck { + if (!input.hasManifest) { + return check("registry-pin", "ok", "No .cursor/agent-kit.json in this repo"); + } + if (!input.registryRef) { + return check("registry-pin", "ok", "No registry.ref pin"); + } + if (isFactoryOrDevRegistry(input.registryUrl, input.registryRef)) { + return check("registry-pin", "ok", `Factory/dev registry (${input.registryRef}); not checked`); + } + const pin = normalizeSemver(input.registryRef); + if (!pin) { + return check("registry-pin", "ok", `registry.ref ${input.registryRef} is a branch, not a pin`); + } + const versions = [input.installedVersion, input.cliVersion] + .map((v) => (v ? normalizeSemver(v) : null)) + .filter((v): v is string => Boolean(v)); + const newest = versions.reduce( + (best, v) => (!best || compareSemver(v, best) > 0 ? v : best), + null, + ); + if (!newest || compareSemver(pin, newest) >= 0) { + return check("registry-pin", "ok", `registry.ref ${input.registryRef} is current`); + } + return check( + "registry-pin", + "warning", + `registry.ref ${input.registryRef} in .cursor/agent-kit.json is older than v${newest}; update would re-apply the v${pin} tree`, + `agent-kit update --ref v${newest}`, + "command", + ); +} + +// ── report + gatherer ─────────────────────────────────────────────────────── + +export function summarizeInstallHealth(checks: InstallHealthCheck[]): InstallHealthReport { + return { + status: checks.some((c) => c.severity === "warning") ? "warning" : "ok", + checks, + }; +} + +export interface InstallHealthGatherOptions { + cwd: string; + cliVersion: string; + /** null = not checked; otherwise the fetch outcome (latest may be null). */ + npm: { checked: boolean; latest: CliNpmLatest | null }; + /** PATH hit + its version (from assessEnvironment's bin resolution). */ + binPath: string | null; + binVersion: string | null; + manifest: { version: string; registryUrl: string | null; registryRef: string | null } | null; + env?: NodeJS.ProcessEnv; + platform?: NodeJS.Platform; + homeDir?: string; + nodeExecPath?: string; + realpathImpl?: (p: string) => Promise; + readFileImpl?: (p: string) => Promise; + existsImpl?: (p: string) => Promise; +} + +async function defaultExists(p: string): Promise { + try { + await access(p); + return true; + } catch { + return false; + } +} + +/** Run the four checks. Read-only, never throws. */ +export async function assessInstallHealth( + options: InstallHealthGatherOptions, +): Promise { + const platform = options.platform ?? process.platform; + const homeDir = options.homeDir ?? homedir(); + const realpathImpl = options.realpathImpl ?? realpath; + const readFileImpl = options.readFileImpl ?? ((p: string) => readFile(p, "utf8")); + const existsImpl = options.existsImpl ?? defaultExists; + + let binRealPath: string | null = null; + if (options.binPath) { + binRealPath = await realpathImpl(options.binPath).catch(() => null); + } + + let homeManifestVersion: string | null = null; + try { + const raw = JSON.parse(await readFileImpl(path.join(homeDir, ".cursor", "agent-kit.json"))) as { + version?: unknown; + }; + if (typeof raw.version === "string" && raw.version) homeManifestVersion = raw.version; + } catch { + // No home manifest, or unreadable: no home-level install to report. + } + const presentRels: string[] = []; + if (homeManifestVersion) { + for (const rel of HOME_INSTALL_RELS) { + if (await existsImpl(path.join(homeDir, rel)).catch(() => false)) presentRels.push(rel); + } + } + + const checks: InstallHealthCheck[] = [ + assessGlobalCli({ + binPath: options.binPath, + binVersion: options.binVersion, + latestChecked: options.npm.checked, + latest: options.npm.latest, + homeDir, + }), + assessNodeManager({ + binPath: options.binPath, + binRealPath, + nodeExecPath: options.nodeExecPath ?? process.execPath, + platform, + homeDir, + }), + assessHomeInstall({ + homeDir, + cwd: options.cwd, + homeManifestVersion, + presentRels, + repoVersion: options.manifest?.version ?? null, + cliVersion: options.cliVersion, + }), + assessRegistryPin({ + hasManifest: options.manifest != null, + installedVersion: options.manifest?.version ?? null, + registryUrl: options.manifest?.registryUrl ?? null, + registryRef: options.manifest?.registryRef ?? null, + cliVersion: options.cliVersion, + }), + ]; + // A reinstall into the same per-version node dir vanishes again on the next + // node switch: point the global-CLI fix at the node-manager line instead. + const [globalCli, nodeManager] = checks; + if (globalCli?.severity === "warning" && nodeManager?.severity === "warning" && nodeManager.fix) { + checks[0] = { + ...globalCli, + detail: `${globalCli.detail}; use the ${nodeManager.label} fix so the upgrade survives the next node switch`, + fix: null, + fixKind: null, + }; + } + return summarizeInstallHealth(checks); +} + +/** + * Whether doctor may ask npm for `latest`: off under CI, with the env opt-out + * and when the config says `updateCheck.enabled: false` explicitly (an absent + * key does not opt out; ADR 2026-07-27 Amend 2026-11-26). + */ +export function npmLatestCheckAllowed(env: NodeJS.ProcessEnv, config: unknown): boolean { + return updateCheckAllowed(env, config); +} + +/** Persist the report for Mission Control Health (gitignored, home-relative paths only). */ +export async function writeInstallHealthSnapshot( + rootDir: string, + report: InstallHealthReport, + generatedAt: string = new Date().toISOString(), +): Promise { + const snapshotPath = path.join(rootDir, INSTALL_HEALTH_SNAPSHOT_RELATIVE_PATH); + await writeJson(snapshotPath, { version: 1, generatedAt, ...report }); + return snapshotPath; +} diff --git a/packages/cli/src/registry/client.ts b/packages/cli/src/registry/client.ts index 28e6a91..5a9ad80 100644 --- a/packages/cli/src/registry/client.ts +++ b/packages/cli/src/registry/client.ts @@ -1,5 +1,6 @@ import path from "node:path"; import { readJson } from "../utils/fs.js"; +import { legacyPackIdTarget, type PackIdRewrite, UnknownPackError } from "./pack-aliases.js"; import { REGISTRY_INDEX_REL } from "./paths.js"; import type { RegistryArtifact, @@ -34,13 +35,65 @@ export async function findSkill(rootDir: string, skillId: string): Promise item.id === packId); + if (exact) return exact; + const alias = legacyPackIdTarget(packId); + return alias ? packs.find((item) => item.id === alias) : undefined; +} + +/** Resolve a pack id (legacy aliases included); throws `UnknownPackError` when absent. */ export async function findPack(rootDir: string, packId: string): Promise { const index = await loadRegistry(rootDir); - const pack = allPacks(index).find((item) => item.id === packId); - if (!pack) throw new Error(`Pack '${packId}' not found in registry.`); + const pack = resolvePackSummary(index, packId); + if (!pack) + throw new UnknownPackError( + packId, + allPacks(index).map((item) => item.id), + ); return pack; } +export interface CanonicalPackIds { + /** Pack ids with legacy aliases replaced by the id the registry ships; order kept, deduplicated. */ + packs: string[] | undefined; + /** One entry per legacy id that resolved to a different registry id. */ + rewrites: PackIdRewrite[]; + /** Ids the registry does not ship under any alias (kept in `packs`). */ + unknown: string[]; + /** Every pack id in the registry index. */ + knownIds: string[]; +} + +/** Map manifest pack ids to the ids the registry resolves them to. */ +export async function canonicalizePackIds( + rootDir: string, + packIds: readonly string[] | undefined, +): Promise { + const index = await loadRegistry(rootDir); + const knownIds = allPacks(index).map((item) => item.id); + if (!packIds) return { packs: undefined, rewrites: [], unknown: [], knownIds }; + const packs: string[] = []; + const rewrites: PackIdRewrite[] = []; + const unknown: string[] = []; + for (const id of packIds) { + const summary = resolvePackSummary(index, id); + if (!summary) unknown.push(id); + else if (summary.id !== id) rewrites.push({ from: id, to: summary.id }); + const resolved = summary?.id ?? id; + if (!packs.includes(resolved)) packs.push(resolved); + } + return { packs, rewrites, unknown, knownIds }; +} + export async function findArtifact( rootDir: string, kind: RegistryArtifact["kind"], @@ -59,7 +112,7 @@ export async function resolveAddTarget( ): Promise<{ type: "skill"; skill: RegistrySkill } | { type: "pack"; pack: RegistryPackSummary }> { const index = await loadRegistry(rootDir); const skill = allSkills(index).find((item) => item.id === id); - const pack = allPacks(index).find((item) => item.id === id); + const pack = resolvePackSummary(index, id); if (skill && pack) { throw new Error( `'${id}' is both a skill and a pack. Disambiguate: agent-kit add --skill ${id} | agent-kit add --pack ${id}`, diff --git a/packages/cli/src/registry/pack-aliases.test.ts b/packages/cli/src/registry/pack-aliases.test.ts new file mode 100644 index 0000000..cd47890 --- /dev/null +++ b/packages/cli/src/registry/pack-aliases.test.ts @@ -0,0 +1,95 @@ +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { DOMAIN_PACK_IDS } from "../manifest/index.js"; +import { canonicalizePackIds, findPack, loadRegistry, resolvePackSummary } from "./client.js"; +import { + formatPackIdRewrite, + LEGACY_PACK_ID_ALIASES, + legacyPackIdTarget, + UnknownPackError, +} from "./pack-aliases.js"; + +const KIT_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../.."); + +/** Registry pinned to a ref that still ships the pre-rename id. */ +async function legacyRegistry(): Promise { + const root = await mkdtemp(path.join(tmpdir(), "ak-pack-alias-legacy-")); + await mkdir(path.join(root, "registry"), { recursive: true }); + await writeFile( + path.join(root, "registry/registry.json"), + JSON.stringify({ + skills: { core: [], community: [] }, + packs: [ + { + id: "gestao-contexto", + title: "Context", + description: "Old id.", + version: "0.1.0", + path: "registry/packs/gestao-contexto", + }, + ], + }), + ); + return root; +} + +describe("LEGACY_PACK_ID_ALIASES", () => { + it("maps the three ADR 2026-07-19 renames onto current L1 pack ids", () => { + expect(LEGACY_PACK_ID_ALIASES).toEqual({ + "gestao-projeto": "project-management", + "gestao-contexto": "context-management", + "engenharia-arquitetura": "engineering-architecture", + }); + for (const target of Object.values(LEGACY_PACK_ID_ALIASES)) { + expect(DOMAIN_PACK_IDS).toContain(target); + } + expect(legacyPackIdTarget("gestao-contexto")).toBe("context-management"); + expect(legacyPackIdTarget("toString")).toBeUndefined(); + expect(legacyPackIdTarget("clean-code")).toBeUndefined(); + }); + + it("formats one rewrite line naming both ids and the manifest", () => { + expect(formatPackIdRewrite({ from: "gestao-contexto", to: "context-management" })).toBe( + "Pack id 'gestao-contexto' renamed to 'context-management' in .cursor/agent-kit.json (legacy L1 pack id).", + ); + }); +}); + +describe("pack lookup with legacy aliases", () => { + it("findPack resolves every legacy id against the real registry", async () => { + for (const [legacy, current] of Object.entries(LEGACY_PACK_ID_ALIASES)) { + expect((await findPack(KIT_ROOT, legacy)).id).toBe(current); + } + }); + + it("findPack throws a named UnknownPackError with the next step for an unknown id", async () => { + const err = await findPack(KIT_ROOT, "ghost-pack").catch((e: unknown) => e); + expect(err).toBeInstanceOf(UnknownPackError); + const message = (err as Error).message; + expect(message).toContain("Unknown pack 'ghost-pack'"); + expect(message).toContain("context-management"); + expect(message).toContain("Next: replace or remove 'ghost-pack'"); + }); + + it("an exact registry id wins over the alias", async () => { + const index = await loadRegistry(await legacyRegistry()); + expect(resolvePackSummary(index, "gestao-contexto")?.id).toBe("gestao-contexto"); + }); + + it("canonicalizePackIds rewrites legacy ids, dedupes, and keeps unknown ids", async () => { + const result = await canonicalizePackIds(KIT_ROOT, [ + "clean-code", + "gestao-contexto", + "context-management", + "ghost-pack", + ]); + expect(result.packs).toEqual(["clean-code", "context-management", "ghost-pack"]); + expect(result.rewrites).toEqual([{ from: "gestao-contexto", to: "context-management" }]); + expect(result.unknown).toEqual(["ghost-pack"]); + expect(result.knownIds).toContain("project-management"); + expect((await canonicalizePackIds(KIT_ROOT, undefined)).packs).toBeUndefined(); + }); +}); diff --git a/packages/cli/src/registry/pack-aliases.ts b/packages/cli/src/registry/pack-aliases.ts new file mode 100644 index 0000000..44632ad --- /dev/null +++ b/packages/cli/src/registry/pack-aliases.ts @@ -0,0 +1,46 @@ +import { MANIFEST_RELATIVE_PATH } from "../manifest/types.js"; + +/** + * Pre-rename L1 pack ids and the English id each became (ADR + * `2026-07-19_l1-pack-ids-english`). The single source for every pack lookup + * and for the `update` manifest rewrite. An exact registry match always wins, + * so a registry pinned to a ref that still ships the old id keeps working. + */ +export const LEGACY_PACK_ID_ALIASES: Readonly> = Object.freeze({ + "gestao-projeto": "project-management", + "gestao-contexto": "context-management", + "engenharia-arquitetura": "engineering-architecture", +}); + +/** The current id a legacy pack id was renamed to, or undefined. */ +export function legacyPackIdTarget(id: string): string | undefined { + return Object.hasOwn(LEGACY_PACK_ID_ALIASES, id) ? LEGACY_PACK_ID_ALIASES[id] : undefined; +} + +export interface PackIdRewrite { + from: string; + to: string; +} + +/** One line per manifest rewrite, printed by `update` and `install`. */ +export function formatPackIdRewrite(rewrite: PackIdRewrite): string { + return `Pack id '${rewrite.from}' renamed to '${rewrite.to}' in ${MANIFEST_RELATIVE_PATH} (legacy L1 pack id).`; +} + +/** Named warning for a pack id the registry does not ship, with the next step. */ +export function formatUnknownPack(packId: string, knownIds: readonly string[]): string { + const known = knownIds.length > 0 ? knownIds.join(", ") : "none"; + return `Unknown pack '${packId}': not found in registry (known packs: ${known}). Next: replace or remove '${packId}' in "packs" of ${MANIFEST_RELATIVE_PATH} (or in --pack), then re-run.`; +} + +export class UnknownPackError extends Error { + readonly packId: string; + readonly knownIds: readonly string[]; + + constructor(packId: string, knownIds: readonly string[]) { + super(formatUnknownPack(packId, knownIds)); + this.name = "UnknownPackError"; + this.packId = packId; + this.knownIds = knownIds; + } +} diff --git a/packages/cli/src/registry/resolve.ts b/packages/cli/src/registry/resolve.ts index ed53746..bac94f8 100644 --- a/packages/cli/src/registry/resolve.ts +++ b/packages/cli/src/registry/resolve.ts @@ -1,197 +1,25 @@ import { execFile } from "node:child_process"; -import { createHash, randomUUID } from "node:crypto"; -import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import { createHash } from "node:crypto"; import { homedir } from "node:os"; import path from "node:path"; import { promisify } from "node:util"; +import { acquireDirLock, refreshLockOwner, releaseDirLock } from "../utils/dir-lock.js"; import { fileExists } from "../utils/fs.js"; import { REGISTRY_INDEX_REL } from "./paths.js"; const execFileAsync = promisify(execFile); -const LOCK_TIMEOUT_MS = 60_000; -const LOCK_RETRY_MS = 200; -const LOCK_STALE_MS = 5 * 60_000; -const LOCK_REFRESH_MS = 10_000; - -interface LockOwner { - pid: number; - uuid: string; - updatedAt: number; -} - -function lockOwnerPath(lockDir: string): string { - return path.join(lockDir, "owner.json"); -} - -function isProcessAlive(pid: number): boolean { - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -} - -async function readLockOwner(lockDir: string): Promise { - try { - const raw = await readFile(lockOwnerPath(lockDir), "utf8"); - const parsed = JSON.parse(raw) as LockOwner; - if (typeof parsed.pid === "number" && typeof parsed.uuid === "string") { - return parsed; - } - } catch {} - return null; +/** Registry cache lock (`${cacheDir}.lock`); the pattern lives in utils/dir-lock.ts. */ +function acquireCacheLock(cacheDir: string): Promise<() => Promise> { + return acquireDirLock(cacheDir, { + vanishedMessage: (target) => + `Timed out acquiring cache lock on ${target}: the lock parent directory kept vanishing (concurrent cache clear?).`, + timeoutMessage: (target) => + `Timed out waiting for cache lock on ${target}. Another install may be stuck.`, + }); } -async function writeLockOwner(lockDir: string, owner: LockOwner): Promise { - // Atomic publish: never leave an observable lock dir without a complete owner file. - // Per-write nonce: the uuid alone is constant for the holder's lifetime, so an - // overlapping refresh write to the same tmp path could interleave and publish - // corrupt bytes. Stray tmp files are swept by the recursive rm on release. - const finalPath = lockOwnerPath(lockDir); - const tmpPath = path.join(lockDir, `owner.${owner.uuid}.${randomUUID()}.tmp`); - await writeFile(tmpPath, JSON.stringify(owner), "utf8"); - await rename(tmpPath, finalPath); -} - -async function refreshLockOwner(lockDir: string, uuid: string): Promise { - const owner = await readLockOwner(lockDir); - // Another holder's lock: never touch it. - if (owner && owner.uuid !== uuid) return; - // owner === null while we hold the lock means our owner.json is missing or - // corrupt. Without healing, the fail-closed release could never remove the - // lock and peers would stall until stale reclaim (up to LOCK_STALE_MS). - await writeLockOwner(lockDir, { pid: process.pid, uuid, updatedAt: Date.now() }); -} - -async function releaseCacheLock(lockDir: string, uuid: string): Promise { - const claimPath = path.join(lockDir, `releasing.${uuid}`); - try { - // Atomically claim the owner file (rename) instead of check-then-`rm -rf`: - // a bare read → rm window let a stale-reclaim + successor republish land in - // between, deleting the successor's fresh lock. The rename also bumps the - // lock dir mtime, which keeps tryReclaimStaleLock away for LOCK_STALE_MS - // while we verify and remove. - await rename(lockOwnerPath(lockDir), claimPath); - } catch { - // No owner file (or dir gone): fail closed, nothing of ours to release. - return; - } - let claimed: LockOwner | null = null; - try { - const raw = await readFile(claimPath, "utf8"); - const parsed = JSON.parse(raw) as LockOwner; - if (typeof parsed.pid === "number" && typeof parsed.uuid === "string") { - claimed = parsed; - } - } catch {} - if (!claimed || claimed.uuid !== uuid) { - // We grabbed a successor's (or corrupt) owner file — put it back and abort. - try { - await rename(claimPath, lockOwnerPath(lockDir)); - } catch {} - return; - } - try { - await rm(lockDir, { recursive: true, force: true }); - } catch {} -} - -/** - * Stale-reclaim mtime semantics (intentional, pinned by test): every owner - * refresh publishes via tmp + rename inside the lock dir, which bumps the lock - * dir's mtime. The `mtimeMs > LOCK_STALE_MS` gate below therefore measures - * time since the last heartbeat (liveness), not time since acquisition — a - * dead owner becomes reclaimable LOCK_STALE_MS after its last refresh, while a - * long-running live install stays protected by refreshes (and by the - * isProcessAlive + ownerFresh short-circuit). - */ -async function tryReclaimStaleLock(lockDir: string): Promise { - let owner: LockOwner | null; - let lockStat: Awaited>; - try { - lockStat = await stat(lockDir); - owner = await readLockOwner(lockDir); - } catch { - return false; - } - - const now = Date.now(); - if (owner) { - const ownerFresh = now - owner.updatedAt < LOCK_STALE_MS; - if (isProcessAlive(owner.pid) && ownerFresh) { - // Owner is still alive and refreshing; do not reclaim. - return false; - } - } - - if (now - lockStat.mtimeMs > LOCK_STALE_MS) { - try { - await rm(lockDir, { recursive: true, force: true }); - return true; - } catch {} - } - return false; -} - -async function acquireCacheLock(cacheDir: string): Promise<() => Promise> { - const lockDir = `${cacheDir}.lock`; - const deadline = Date.now() + LOCK_TIMEOUT_MS; - const uuid = randomUUID(); - const owner: LockOwner = { pid: process.pid, uuid, updatedAt: Date.now() }; - - await mkdir(path.dirname(lockDir), { recursive: true }); - - let lastErrorCode: string | undefined; - while (Date.now() < deadline) { - try { - await mkdir(lockDir, { recursive: false }); - await writeLockOwner(lockDir, owner); - // Serialize refreshes: a slow write outliving the interval must not - // overlap the next one (paired with the per-write tmp nonce). - let refreshing = false; - const refreshInterval = setInterval(() => { - if (refreshing) return; - refreshing = true; - refreshLockOwner(lockDir, uuid) - .catch(() => {}) - .finally(() => { - refreshing = false; - }); - }, LOCK_REFRESH_MS); - return async () => { - clearInterval(refreshInterval); - await releaseCacheLock(lockDir, uuid); - }; - } catch (err) { - const code = (err as NodeJS.ErrnoException).code; - lastErrorCode = code; - if (code === "EEXIST") { - if (await tryReclaimStaleLock(lockDir)) { - continue; - } - await new Promise((r) => setTimeout(r, LOCK_RETRY_MS + Math.random() * 100)); - continue; - } - // Lock dir (or its parent) vanished between mkdir and owner publish — - // peer fail-closed race or concurrent cache clear. Self-heal the parent - // and back off like EEXIST: a persistent ENOENT must not hot-loop - // (~3.4k syscalls/sec measured without the delay). - if (code === "ENOENT") { - await mkdir(path.dirname(lockDir), { recursive: true }); - await new Promise((r) => setTimeout(r, LOCK_RETRY_MS + Math.random() * 100)); - continue; - } - throw err; - } - } - throw new Error( - lastErrorCode === "ENOENT" - ? `Timed out acquiring cache lock on ${cacheDir}: the lock parent directory kept vanishing (concurrent cache clear?).` - : `Timed out waiting for cache lock on ${cacheDir}. Another install may be stuck.`, - ); -} +const releaseCacheLock = releaseDirLock; // refreshLockOwner is exported for tests only (like releaseCacheLock); none of // these are re-exported from a package entry point. diff --git a/packages/cli/src/scanner/detect-repository.ts b/packages/cli/src/scanner/detect-repository.ts index 518c444..0141076 100644 --- a/packages/cli/src/scanner/detect-repository.ts +++ b/packages/cli/src/scanner/detect-repository.ts @@ -230,12 +230,14 @@ export const KIT_OWNED_IGNORE_PATTERNS = [ ".cursor/HANDOFF.md", ".cursor/dogfood/", ".cursor/context/readiness.json", + ".cursor/context/install-health.json", ".cursor/context/flight-log.json", ".cursor/context/mission-timing.json", ".cursor/context/outcome-ledger.json", ".cursor/context/test-results.json", ".cursor/context/gate-exit.json", ".cursor/context/review-ledger.json", + ".cursor/context/cost-ledger.ndjson", ".cursor/context/plan-index.json", ".cursor/context/run-plan-all.lock", ".cursor/loop-logs/", diff --git a/packages/cli/src/scanner/safe-fixes.test.ts b/packages/cli/src/scanner/safe-fixes.test.ts index 6752db0..0bc0e13 100644 --- a/packages/cli/src/scanner/safe-fixes.test.ts +++ b/packages/cli/src/scanner/safe-fixes.test.ts @@ -169,6 +169,7 @@ describe("executeSafeReadinessFixes", () => { ".cursor/context/mission-timing.json", ".cursor/context/gate-exit.json", ".cursor/context/review-ledger.json", + ".cursor/context/cost-ledger.ndjson", ".cursor/context/plan-index.json", ".cursor/context/run-plan-all.lock", ".cursor/loop-logs/", diff --git a/packages/cli/src/test-support/vitest-setup.ts b/packages/cli/src/test-support/vitest-setup.ts new file mode 100644 index 0000000..6f1d768 --- /dev/null +++ b/packages/cli/src/test-support/vitest-setup.ts @@ -0,0 +1,30 @@ +/** + * Global vitest setup (packages/cli/vitest.config.ts `setupFiles`). + * + * install, update, init and doctor feed the machine install registry + * (`~/.config/agent-kit/installs.json`). Point it at a scratch file for every + * test file so no test, and no CLI child that inherits this env, can write the + * operator's real registry. A test that needs another path sets it itself. + * The update check is opted out by env for the same reason. + */ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterAll } from "vitest"; + +// Literal on purpose: importing installs/store.ts here would load +// node:fs/promises into the module graph before a test file's vi.mock of it. +const INSTALLS_FILE_ENV = "AGENT_KIT_INSTALLS_FILE"; + +const scratch = mkdtempSync(path.join(tmpdir(), "ak-installs-test-")); +process.env[INSTALLS_FILE_ENV] = path.join(scratch, "installs.json"); + +// The update check is on by default (ADR 2026-07-27 Amend 2026-11-26): keep +// every suite, and every CLI child it spawns, off the npm registry. The notice +// cache (`update-notice.json`) lands beside the scratch installs.json. Tests +// of the check itself pass their own env. +process.env.AGENT_KIT_NO_UPDATE_CHECK = "1"; + +afterAll(() => { + rmSync(scratch, { recursive: true, force: true }); +}); diff --git a/packages/cli/src/utils/agent-session.ts b/packages/cli/src/utils/agent-session.ts new file mode 100644 index 0000000..9b43d29 --- /dev/null +++ b/packages/cli/src/utils/agent-session.ts @@ -0,0 +1,69 @@ +/** + * Agent-session detection for operator-only commands (`update --all`, + * ADR 2026-11-26_update-all-operator-only-branch-mr-per-repo point 1). + * + * A marker here means the process runs under an agent or a headless kit run, + * not under an operator's own keystrokes. `COLONY_HOST_CLI` is deliberately + * absent: Colony also exports it into the operator's own terminal tabs. + */ + +import { CLAUDE_NESTED_SESSION_KEYS } from "../plan-loop/backends.js"; +import { QUEUE_LEASE_SESSION_ENV } from "../plan-loop/queue-lease.js"; + +/** Set by the kit on headless children (external review, plan-loop spawns). */ +export const AGENT_KIT_HEADLESS_ENV = "AGENT_KIT_HEADLESS"; + +/** + * Env markers of an agent session, each with the label printed in a refusal. + * Claude Code exports the nested-session keys into every shell it runs; + * Cursor exports `CURSOR_AGENT` into agent-run terminals; the kit exports + * the queue-lease session to the agent child of `run-plan-all`. + */ +export const AGENT_SESSION_MARKERS: readonly { key: string; label: string }[] = [ + ...CLAUDE_NESTED_SESSION_KEYS.map((key) => ({ key, label: "Claude Code agent session" })), + { key: "CURSOR_AGENT", label: "Cursor agent session" }, + { key: AGENT_KIT_HEADLESS_ENV, label: "headless Agent Kit run" }, + { key: QUEUE_LEASE_SESSION_ENV, label: "Agent Kit plan loop" }, +]; + +function markerSet(value: string | undefined): boolean { + if (value === undefined) return false; + const v = value.trim().toLowerCase(); + return v !== "" && v !== "0" && v !== "false"; +} + +/** The first agent-session marker set in `env`, or null when none is. */ +export function detectAgentSession( + env: NodeJS.ProcessEnv = process.env, +): { key: string; label: string } | null { + for (const marker of AGENT_SESSION_MARKERS) { + if (markerSet(env[marker.key])) return marker; + } + return null; +} + +export interface OperatorTerminalProbe { + env?: NodeJS.ProcessEnv; + stdinIsTTY?: boolean; + stdoutIsTTY?: boolean; +} + +/** + * One-line reason `command` refuses to run here, or null when an operator is + * typing it in a terminal. `--yes`, `AGENT_KIT_YES` and `CI` never lift it. + */ +export function operatorOnlyRefusal( + command: string, + probe: OperatorTerminalProbe = {}, +): string | null { + const agent = detectAgentSession(probe.env ?? process.env); + if (agent) { + return `${command} is operator-only and refuses inside an agent session (${agent.label}: ${agent.key} is set); type it in your own terminal.`; + } + const stdinTTY = probe.stdinIsTTY ?? Boolean(process.stdin.isTTY); + const stdoutTTY = probe.stdoutIsTTY ?? Boolean(process.stdout.isTTY); + if (!stdinTTY || !stdoutTTY) { + return `${command} is operator-only and needs an interactive terminal (stdin and stdout must be a TTY); type it in your own terminal.`; + } + return null; +} diff --git a/packages/cli/src/utils/dir-lock.ts b/packages/cli/src/utils/dir-lock.ts new file mode 100644 index 0000000..b11a108 --- /dev/null +++ b/packages/cli/src/utils/dir-lock.ts @@ -0,0 +1,214 @@ +import { randomUUID } from "node:crypto"; +import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; + +/** + * Cross-process directory lock: `${target}.lock/` holds an `owner.json` + * ({pid, uuid, updatedAt}) published by temp-file + rename and refreshed while + * held. A dead or silent owner is reclaimed after {@link LOCK_STALE_MS}. + * + * Extracted from `registry/resolve.ts` (registry cache lock) so the machine + * install registry (`installs/store.ts`) uses the exact same pattern + * (ADR 2026-08-02 amend 2026-11-26). + */ + +const DEFAULT_LOCK_TIMEOUT_MS = 60_000; +const LOCK_RETRY_MS = 200; +export const LOCK_STALE_MS = 5 * 60_000; +const LOCK_REFRESH_MS = 10_000; + +interface LockOwner { + pid: number; + uuid: string; + updatedAt: number; +} + +export interface DirLockOptions { + /** Give up after this many ms (default 60 s). */ + timeoutMs?: number; + /** Error text when the lock parent kept vanishing (ENOENT loop). */ + vanishedMessage?: (target: string) => string; + /** Error text when another holder kept the lock past the timeout. */ + timeoutMessage?: (target: string) => string; +} + +function lockOwnerPath(lockDir: string): string { + return path.join(lockDir, "owner.json"); +} + +function isProcessAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function readLockOwner(lockDir: string): Promise { + try { + const raw = await readFile(lockOwnerPath(lockDir), "utf8"); + const parsed = JSON.parse(raw) as LockOwner; + if (typeof parsed.pid === "number" && typeof parsed.uuid === "string") { + return parsed; + } + } catch {} + return null; +} + +async function writeLockOwner(lockDir: string, owner: LockOwner): Promise { + // Atomic publish: never leave an observable lock dir without a complete owner file. + // Per-write nonce: the uuid alone is constant for the holder's lifetime, so an + // overlapping refresh write to the same tmp path could interleave and publish + // corrupt bytes. Stray tmp files are swept by the recursive rm on release. + const finalPath = lockOwnerPath(lockDir); + const tmpPath = path.join(lockDir, `owner.${owner.uuid}.${randomUUID()}.tmp`); + await writeFile(tmpPath, JSON.stringify(owner), "utf8"); + await rename(tmpPath, finalPath); +} + +export async function refreshLockOwner(lockDir: string, uuid: string): Promise { + const owner = await readLockOwner(lockDir); + // Another holder's lock: never touch it. + if (owner && owner.uuid !== uuid) return; + // owner === null while we hold the lock means our owner.json is missing or + // corrupt. Without healing, the fail-closed release could never remove the + // lock and peers would stall until stale reclaim (up to LOCK_STALE_MS). + await writeLockOwner(lockDir, { pid: process.pid, uuid, updatedAt: Date.now() }); +} + +export async function releaseDirLock(lockDir: string, uuid: string): Promise { + const claimPath = path.join(lockDir, `releasing.${uuid}`); + try { + // Atomically claim the owner file (rename) instead of check-then-`rm -rf`: + // a bare read → rm window let a stale-reclaim + successor republish land in + // between, deleting the successor's fresh lock. The rename also bumps the + // lock dir mtime, which keeps tryReclaimStaleLock away for LOCK_STALE_MS + // while we verify and remove. + await rename(lockOwnerPath(lockDir), claimPath); + } catch { + // No owner file (or dir gone): fail closed, nothing of ours to release. + return; + } + let claimed: LockOwner | null = null; + try { + const raw = await readFile(claimPath, "utf8"); + const parsed = JSON.parse(raw) as LockOwner; + if (typeof parsed.pid === "number" && typeof parsed.uuid === "string") { + claimed = parsed; + } + } catch {} + if (!claimed || claimed.uuid !== uuid) { + // We grabbed a successor's (or corrupt) owner file — put it back and abort. + try { + await rename(claimPath, lockOwnerPath(lockDir)); + } catch {} + return; + } + try { + await rm(lockDir, { recursive: true, force: true }); + } catch {} +} + +/** + * Stale-reclaim mtime semantics (intentional, pinned by test): every owner + * refresh publishes via tmp + rename inside the lock dir, which bumps the lock + * dir's mtime. The `mtimeMs > LOCK_STALE_MS` gate below therefore measures + * time since the last heartbeat (liveness), not time since acquisition — a + * dead owner becomes reclaimable LOCK_STALE_MS after its last refresh, while a + * long-running live holder stays protected by refreshes (and by the + * isProcessAlive + ownerFresh short-circuit). + */ +async function tryReclaimStaleLock(lockDir: string): Promise { + let owner: LockOwner | null; + let lockStat: Awaited>; + try { + lockStat = await stat(lockDir); + owner = await readLockOwner(lockDir); + } catch { + return false; + } + + const now = Date.now(); + if (owner) { + const ownerFresh = now - owner.updatedAt < LOCK_STALE_MS; + if (isProcessAlive(owner.pid) && ownerFresh) { + // Owner is still alive and refreshing; do not reclaim. + return false; + } + } + + if (now - lockStat.mtimeMs > LOCK_STALE_MS) { + try { + await rm(lockDir, { recursive: true, force: true }); + return true; + } catch {} + } + return false; +} + +/** + * Acquire `${target}.lock`. Resolves to the release function; call it in a + * `finally` (the refresh interval keeps the process alive until released). + */ +export async function acquireDirLock( + target: string, + options: DirLockOptions = {}, +): Promise<() => Promise> { + const lockDir = `${target}.lock`; + const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS); + const uuid = randomUUID(); + const owner: LockOwner = { pid: process.pid, uuid, updatedAt: Date.now() }; + + await mkdir(path.dirname(lockDir), { recursive: true }); + + let lastErrorCode: string | undefined; + while (Date.now() < deadline) { + try { + await mkdir(lockDir, { recursive: false }); + await writeLockOwner(lockDir, owner); + // Serialize refreshes: a slow write outliving the interval must not + // overlap the next one (paired with the per-write tmp nonce). + let refreshing = false; + const refreshInterval = setInterval(() => { + if (refreshing) return; + refreshing = true; + refreshLockOwner(lockDir, uuid) + .catch(() => {}) + .finally(() => { + refreshing = false; + }); + }, LOCK_REFRESH_MS); + return async () => { + clearInterval(refreshInterval); + await releaseDirLock(lockDir, uuid); + }; + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + lastErrorCode = code; + if (code === "EEXIST") { + if (await tryReclaimStaleLock(lockDir)) { + continue; + } + await new Promise((r) => setTimeout(r, LOCK_RETRY_MS + Math.random() * 100)); + continue; + } + // Lock dir (or its parent) vanished between mkdir and owner publish — + // peer fail-closed race or concurrent cache clear. Self-heal the parent + // and back off like EEXIST: a persistent ENOENT must not hot-loop + // (~3.4k syscalls/sec measured without the delay). + if (code === "ENOENT") { + await mkdir(path.dirname(lockDir), { recursive: true }); + await new Promise((r) => setTimeout(r, LOCK_RETRY_MS + Math.random() * 100)); + continue; + } + throw err; + } + } + throw new Error( + lastErrorCode === "ENOENT" + ? (options.vanishedMessage?.(target) ?? + `Timed out acquiring lock on ${target}: the lock parent directory kept vanishing.`) + : (options.timeoutMessage?.(target) ?? `Timed out waiting for lock on ${target}.`), + ); +} diff --git a/packages/cli/src/welcome/help-groups.ts b/packages/cli/src/welcome/help-groups.ts index 814542b..ed14c2c 100644 --- a/packages/cli/src/welcome/help-groups.ts +++ b/packages/cli/src/welcome/help-groups.ts @@ -21,7 +21,7 @@ export const CLI_HELP_GROUPS: HelpGroup[] = [ { id: "setup", title: "SETUP", - commands: ["init", "install", "doctor", "status", "update", "add", "scan"], + commands: ["init", "install", "doctor", "status", "update", "installs", "add", "scan"], }, { id: "mission", diff --git a/packages/cli/vitest.config.ts b/packages/cli/vitest.config.ts index c1433e6..c20ce71 100644 --- a/packages/cli/vitest.config.ts +++ b/packages/cli/vitest.config.ts @@ -4,5 +4,7 @@ export default defineConfig({ test: { environment: "node", include: ["src/**/*.test.ts"], + // Scratch machine install registry for every test file (never the real one). + setupFiles: ["./src/test-support/vitest-setup.ts"], }, }); diff --git a/plugin.json b/plugin.json index 3615105..86e5823 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "agent-kit", - "version": "6.23.0", + "version": "6.25.0", "description": "Mission Kit core skills: HITL gates, plan backlog and onboarding, QA, external plan review. The full kit (slash commands, plans, HANDOFF, staging-then-prod git flow) installs with npx @dadado/agent-kit-cli@latest install.", "author": { "name": "agent-kit-startup" diff --git a/skills/hitl-gates/run-plan-all-queue.md b/skills/hitl-gates/run-plan-all-queue.md index 9af7b83..6014a86 100644 --- a/skills/hitl-gates/run-plan-all-queue.md +++ b/skills/hitl-gates/run-plan-all-queue.md @@ -169,7 +169,7 @@ Use the safe helper after the confirm Ask grants consolidations. Canonical launc | Drop / archive | `.cursor/scripts/run-plan-all-consolidate.sh --drop PLAN.plan.md --apply --approved` (refuse overwrite unless `--force-overwrite`) | | HANDOFF queue rewrite | `.cursor/scripts/run-plan-all-consolidate.sh --rewrite-queue --queue "a.plan.md,b.plan.md" --cursor 0 --status running --activate a.plan.md --apply --approved` | -`--rewrite-queue` validates and normalizes `--outcomes` (including multiline) **before** any HANDOFF mutation, then applies Plan/Mode/queue/cursor/status/outcomes as one atomic rewrite. Invalid outcomes (for example a line that looks like a HANDOFF machine field) refuse with the file untouched. Backlog CRUD callers still cannot rewrite the queue. +`--rewrite-queue` validates and normalizes `--outcomes` (including multiline) **before** any HANDOFF mutation, then applies Plan/Mode/queue/cursor/status/outcomes as one atomic rewrite. Invalid outcomes (for example a line that looks like a HANDOFF machine field) refuse with the file untouched. Backlog CRUD callers still cannot rewrite the queue. The rewrite keeps history by default (no flag). Plan, Mode, Last updated, Queue cursor and Queue status become ` · antes: ` when the value changes (an unchanged value leaves the line as it was; Run queue is replaced bare). Old Queue outcomes rows that `--outcomes` does not carry forward move to `- **Queue outcomes anteriores:**` right after the live block, newest first: history, not live outcomes (the orchestrator and `agent-kit queue` read only `- **Queue outcomes:**`; `agent-kit handoff` keeps both). Dry-run prints the same HANDOFF line diff as the apply (`-` removed, `+` added): read it before `--apply --approved`. Queue field shape aligns with `serializeRunPlanAllQueueFields` in `packages/cli/src/plan-loop/run-plan-all-orchestrator.ts` (machine-field bullets only). This path does not promote.