From e74206763e8613d936d01d6f66d922b4fefe8a23 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Fri, 22 May 2026 23:27:38 +0000 Subject: [PATCH 1/3] chore: sync public mirror from internal --- CHANGELOG.md | 8 +- docs/protocols/a2a-fleet-delegation.md | 12 - docs/protocols/codex-operating-layer.json | 2 +- package.json | 567 ++++++------ .../slack-agent/test/tools-status.test.ts | 48 +- scripts/ci-nx-tests.sh | 29 + scripts/plan-ci-checks.mjs | 30 + scripts/plan-nx-test-command.mjs | 294 ++++++- scripts/smoke-maestro-a2a-local-swarm.ts | 815 ------------------ scripts/verify-platform-a2a-live-evidence.ts | 25 +- src/agent/transport.ts | 5 + src/telemetry/cli-command-aggregator.ts | 32 + .../provider-transport-provider-tools.test.ts | 44 +- ...rovider-transport-tool-concurrency.test.ts | 250 ++++++ .../a2a-platform-live-evidence-verify.test.ts | 61 ++ test/scripts/ci-guardrails.test.ts | 150 +++- test/telemetry/cli-command-aggregator.test.ts | 2 + 17 files changed, 1224 insertions(+), 1150 deletions(-) delete mode 100644 scripts/smoke-maestro-a2a-local-swarm.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 17e892f19..2efa8f6a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,11 +19,17 @@ versioning when releases are cut. ## [0.10.21] - 2026-05-22 +### Changed + +- Add Platform-owned A2A delegation (#2080). +- Reduce avoidable tool serialization (#2079). + ### Fixed - Vendor runtime workspaces under `dist/node_modules` so Bun and npm installs of `@evalops/maestro` do not resolve unpublished `@evalops/contracts` or - `@evalops/tui` packages from the registry. + `@evalops/tui` packages from the registry. +- Allow public mirror ci guardrail shape (#2092). ## [0.10.20] - 2026-05-22 diff --git a/docs/protocols/a2a-fleet-delegation.md b/docs/protocols/a2a-fleet-delegation.md index cf9b1d333..4b0a06c81 100644 --- a/docs/protocols/a2a-fleet-delegation.md +++ b/docs/protocols/a2a-fleet-delegation.md @@ -121,18 +121,6 @@ MAESTRO_SWARM_A2A_PREFER_INTERNAL=1 \ maestro swarm run plan.md ``` -For a host-local proof of the full Maestro loop, run: - -```sh -npm run smoke:a2a-local-swarm -``` - -The smoke starts a mock Agent Registry plus two real Rust control-plane -instances, waits for both peers to auto-register and heartbeat, runs the swarm -executor through Platform-style discovery, verifies both peers complete remote -A2A tasks, resumes one task by `message.taskId`, and checks that a denied task -class returns zero eligible candidates before dispatch. - Platform-discovered peers are ranked by the A2A capability market (`evalops.maestro.a2a-capability-market.v1`) before selection. The ranking prefers exact skill matches, idle/online and freshly heartbeated agents, diff --git a/docs/protocols/codex-operating-layer.json b/docs/protocols/codex-operating-layer.json index ada282990..774944874 100644 --- a/docs/protocols/codex-operating-layer.json +++ b/docs/protocols/codex-operating-layer.json @@ -155,7 +155,7 @@ "records Platform observations for cached dynamic read callbacks", "lets Codex dynamic tool callbacks wait for user approval instead of auto-denying", "preserves Platform joins for denied Codex dynamic callbacks", - "returns workflow-state errors from cached dynamic callbacks", + "returns workflow-state errors from repeated dynamic callbacks", "withTimeout", "action_approval_required", "ActionApprovalService(\"prompt\")", diff --git a/package.json b/package.json index 1886e5fd6..3552e8366 100644 --- a/package.json +++ b/package.json @@ -1,286 +1,285 @@ { - "name": "@evalops/maestro", - "description": "Maestro by EvalOps - Deterministic coding agent with TUI/CLI and Web UI for AI-assisted development", - "version": "0.10.21", - "private": false, - "type": "module", - "workspaces": [ - "packages/*" - ], - "bin": { - "maestro": "dist/cli.js" - }, - "main": "./dist/index.js", - "types": "./dist/index.d.ts", - "files": [ - "dist", - "skills" - ], - "maestroRuntimeWorkspaces": [ - "@evalops/contracts", - "@evalops/tui" - ], - "scripts": { - "clean": "node ./scripts/clean-paths.js dist ./tmp/tsbuildinfo/composer.tsbuildinfo", - "prepare": "husky", - "postinstall": "node -e \"const fs=require('node:fs');const cp=require('node:child_process');if(!fs.existsSync('./scripts/ensure-deps.js')||!fs.existsSync('./packages/contracts/package.json'))process.exit(0);const r=cp.spawnSync(process.execPath,['./scripts/ensure-deps.js','--no-install'],{stdio:'inherit'});process.exit(r.status??1);\"", - "install:local": "node ./scripts/install-client.js", - "prebuild": "node ./scripts/ensure-deps.js && node ./scripts/session-wire-format-codegen.mjs && node ./scripts/headless-protocol-codegen.mjs && bun run generate:headless-proto:buf", - "build": "node ./scripts/ensure-dir.js ./tmp/tsbuildinfo && tsc -b tsconfig.build.json --force && bun build ./src/cli.ts --target node --packages external --external tree-sitter --external tree-sitter-bash --outfile dist/cli.js && node ./scripts/bundle-runtime-deps.mjs && node ./scripts/copy-themes.js && node ./scripts/copy-db-migrations.js", - "start": "node --enable-source-maps dist/cli.js", - "start:native": "MAESTRO_AGENT_SCRIPT=\"$(pwd)/dist/cli.js\" ./packages/tui-rs/target/release/maestro-tui", - "dev": "node ./scripts/headless-protocol-codegen.mjs && bun run generate:headless-proto:buf && node ./scripts/ensure-dir.js ./tmp/tsbuildinfo && tsc -b tsconfig.build.json --watch --preserveWatchOutput", - "dev:all": "concurrently --names \"cli,test\" --prefix-colors \"cyan,yellow\" \"npm run dev\" \"npm run test:watch\"", - "test:watch": "node ./scripts/run-vitest.js --watch", - "test:fast": "VITEST_FAST=1 node ./scripts/run-vitest.js --run", - "lint": "biome check . && npm run lint:evals", - "setup:worktree": "node scripts/setup-worktree.mjs", - "check:headless-proto:generated": "node scripts/check-headless-proto-generated.mjs", - "verify:headless-proto:sync": "node scripts/verify-headless-proto-sync.mjs", - "lint:headless-proto": "buf lint && bun run verify:headless-proto:sync && bun run check:headless-proto:generated", - "check:drift-surfaces": "node scripts/check-drift-prone-surfaces.mjs", - "check:staged-rollout": "node scripts/check-staged-rollout.mjs", - "check:context-manifest": "tsx scripts/check-context-manifest-contract.ts", - "check:session-wire-contract": "tsx scripts/check-session-wire-contract.ts", - "check:session-replay-fixtures": "tsx scripts/check-session-replay-fixtures.ts", - "check:agent-trajectory-fixtures": "tsx scripts/check-agent-trajectory-fixtures.ts", - "check:agent-trajectory-replay-fixtures": "tsx scripts/check-agent-trajectory-replay-fixtures.ts", - "check:agent-trajectory-score-fixtures": "tsx scripts/check-agent-trajectory-score-fixtures.ts", - "check:agent-trajectory-inspection-fixtures": "tsx scripts/check-agent-trajectory-inspection-fixtures.ts", - "check:agent-trajectory-scenario-fixtures": "tsx scripts/check-agent-trajectory-scenario-fixtures.ts", - "check:slack-contract-lab-scenarios": "tsx scripts/check-slack-contract-lab-scenarios.ts", - "check:scripted-scenario-fixtures": "tsx scripts/check-scripted-scenario-fixtures.ts", - "check:evidence-integrity": "tsx scripts/check-evidence-integrity.ts", - "check:scenario-replay-gate": "node scripts/run-scenario-replay-gate.mjs", - "check:codex-parity": "node scripts/check-codex-parity-conformance.mjs", - "check:codex-operating-layer": "node scripts/check-codex-operating-layer-conformance.mjs", - "lint:evals": "bun run lint:headless-proto && node scripts/ensure-deps.js --no-install --workspace @evalops/contracts && node scripts/verify-evals.js && node scripts/verify-tool-versions.js && node scripts/validate-system-paths.js && node scripts/validate-package-boundaries.js && node scripts/validate-public-package-deps.js && node scripts/check-public-surface-boundary.mjs && npm run check:context-manifest && npm run check:session-wire-contract && npm run check:evidence-integrity && npm run check:session-replay-fixtures && npm run check:agent-trajectory-fixtures && npm run check:agent-trajectory-replay-fixtures && npm run check:agent-trajectory-score-fixtures && npm run check:agent-trajectory-inspection-fixtures && npm run check:agent-trajectory-scenario-fixtures && npm run check:slack-contract-lab-scenarios && npm run check:scripted-scenario-fixtures && node scripts/session-wire-format-codegen.mjs --check && node scripts/headless-protocol-codegen.mjs --check && npm run check:drift-surfaces && npm run check:staged-rollout && npm run check:codex-parity && npm run check:codex-operating-layer && npm run developer-surface:check", - "platform:sdk-smoke": "tsx scripts/check-platform-sdk-contract.ts", - "platform:agentruntime-e2e": "tsx scripts/smoke-platform-agentruntime-lifecycle.ts", - "platform:timeline-e2e": "tsx scripts/smoke-platform-timeline-e2e.ts", - "platform:a2a-delegation-live": "tsx scripts/smoke-platform-a2a-delegation-live.ts", - "platform:a2a-evidence-verify": "tsx scripts/verify-platform-a2a-live-evidence.ts", - "developer-surface:check": "node scripts/check-developer-surface.mjs", - "format": "biome format .", - "check": "npm run lint && npm run check --workspaces --if-present && tsc -p tsconfig.build.json --noEmit", - "evals": "npm run build && node scripts/run-evals.js", - "evals:skill-package": "bunx tsx scripts/evals/run-skill-package-evals.ts", - "evals:pipeline-tool-integration": "bun run build && bunx tsx scripts/evals/run-pipeline-tool-integration-evals.ts", - "evals:shared-memory-integration": "bun run build && bunx tsx scripts/evals/run-shared-memory-integration-evals.ts", - "evals:platform-fermata-scenario-suite": "bun run build && bunx tsx scripts/evals/run-platform-fermata-scenario-suite.ts", - "evals:openrouter-live-smoke": "bun run build && bunx tsx scripts/evals/run-openrouter-live-smoke.ts", - "evals:openrouter-approvals-judge": "bun run build && bunx tsx scripts/evals/run-openrouter-approvals-judge-evals.ts", - "evals:openrouter-tool-surface-judge": "bun run build && bunx tsx scripts/evals/run-openrouter-tool-surface-judge-evals.ts", - "telemetry:report": "node scripts/telemetry-report.js", - "device-identity:harness": "MAESTRO_DEVICE_IDENTITY_ALLOW_TEST_HELPER=1 node ./scripts/run-vitest.js --run test/oauth-device-identity-harness.test.ts", - "generate-models": "bun scripts/generate-models.ts", - "generate:headless-protocol": "node scripts/headless-protocol-codegen.mjs", - "generate:session-wire-format": "node scripts/session-wire-format-codegen.mjs", - "check:session-wire-format:generated": "node scripts/session-wire-format-codegen.mjs --check", - "generate:headless-proto:buf": "buf generate --template buf.gen.yaml && bunx biome check --write --unsafe packages/contracts/src/proto/maestro/v1/headless_pb.ts", - "test": "node ./scripts/run-vitest.js --run", - "test:coverage": "node ./scripts/run-vitest.js --run --coverage", - "prepublishOnly": "npm run clean && npm run build && npm run verify:runtime-deps", - "bun:install": "bun install", - "bun:cli": "bun run ./src/cli.ts", - "bun:watch": "bun run --watch ./src/cli.ts", - "web": "node dist/web-server.js", - "web:rust-control": "packages/control-plane-rs/target/release/maestro-control-plane", - "web:dev": "node ./scripts/ensure-deps.js --workspace @evalops/contracts && concurrently --names \"server,ui\" --prefix-colors \"blue,green\" \"tsx --watch src/web-server.ts\" \"bun run dev:web\"", - "web:dev:local": "MAESTRO_WEB_REQUIRE_KEY=0 MAESTRO_WEB_REQUIRE_REDIS=0 MAESTRO_WEB_ORIGIN=http://localhost:3000 npm run web:dev", - "bun:lint": "bunx biome check . && bun run lint:evals", - "bun:test": "node ./scripts/run-vitest.js --run", - "bun:test:fast": "VITEST_FAST=1 node ./scripts/run-vitest.js --run", - "bun:check": "bun run bun:lint && bunx tsc --noEmit", - "bun:compile": "npm run build && bun build ./dist/cli.js --compile --external tree-sitter --external tree-sitter-bash --outfile dist/maestro-bun", - "bun:compile:bytecode": "npm run build && bun build ./dist/cli.js --compile --bytecode --external tree-sitter --external tree-sitter-bash --outfile dist/maestro-bun-bytecode", - "bun:evals": "bun run build && bun run ./scripts/run-evals.js", - "compile:binary": "npm run bun:compile && echo \"Binary ready at dist/maestro-bun\"", - "cli": "node ./dist/cli.js", - "verify-build": "bun scripts/verify-build.ts", - "verify-build:packages": "VERIFY_PACKAGES=1 bun scripts/verify-build.ts", - "release:check": "node scripts/release-readiness.js release", - "release:check:ci": "node scripts/release-readiness.js ci", - "ci:plan": "node scripts/plan-ci-checks.mjs", - "pr:ready": "node scripts/pr-ready-to-merge.mjs", - "pr:feedback": "node scripts/pr-feedback-audit.mjs", - "verify:runtime-deps": "node scripts/check-runtime-deps.js && node scripts/check-docker-runtime-workspaces.mjs && node scripts/check-packed-bundled-workspaces.mjs", - "tui": "npm run cli", - "verify": "npm run format && npm run lint && npm run test && npm run build && npm run smoke && npm run telemetry:report", - "smoke": "node scripts/smoke-cli.js", - "smoke:local-e2e": "node scripts/smoke-cli.js", - "smoke:codex-app-server-live": "node scripts/smoke-codex-app-server-live.mjs", - "smoke:event-bus": "tsx scripts/smoke-maestro-event-bus.ts", - "smoke:a2a-local": "tsx scripts/smoke-maestro-a2a-local.ts", - "smoke:a2a-local-swarm": "tsx scripts/smoke-maestro-a2a-local-swarm.ts", - "smoke:a2a-input-required": "tsx scripts/smoke-maestro-a2a-input-required.ts", - "smoke:a2a-tmux": "bash scripts/smoke-maestro-a2a-tmux.sh", - "a2a": "tsx src/cli.ts a2a", - "a2a:codex-bridge": "python3 scripts/codex-a2a-bridge.py", - "a2a:peer": "tsx src/cli.ts a2a", - "smoke:headless": "node scripts/smoke-headless.js", - "headless:responsiveness": "node scripts/headless-responsiveness-harness.js", - "smoke:pack": "node scripts/smoke-packed-cli.js", - "metadata:sync": "node scripts/sync-package-metadata.js", - "metadata:check": "node scripts/sync-package-metadata.js --check", - "cutover:check": "node scripts/check-package-cutover-readiness.js", - "factory:import": "npm run build && node dist/scripts/import-factory-config.js", - "factory:export": "npm run build && node dist/scripts/export-factory-config.js", - "version:patch": "node scripts/version.js patch", - "version:minor": "node scripts/version.js minor", - "version:major": "node scripts/version.js major", - "version:sync": "node scripts/sync-versions.js", - "openapi:generate": "bun scripts/generate-openapi.ts", - "openapi:check": "bun scripts/generate-openapi.ts --check", - "openapi:serve": "bun scripts/serve-openapi.ts", - "nix:update-hash": "bash scripts/update-nix-hash.sh", - "dev:web": "bun run --filter @evalops/maestro-web dev", - "dev:tui": "bun run --filter @evalops/tui dev", - "dev:packages": "concurrently --names \"tui,web\" --prefix-colors \"magenta,green\" \"bun run dev:tui\" \"bun run dev:web\"", - "guardian": "bash scripts/guardian.sh", - "guardian:install-hook": "node scripts/install-guardian-hook.js", - "build:all": "bun run --filter @evalops/contracts build && bun run --filter @evalops/consumer build && bun run --filter @evalops/tui build && bun run --filter @evalops/maestro-web build && bun run build && bun run --filter @evalops/ai build", - "test:all": "npm run test && npm run test --workspaces --if-present", - "db:generate": "MAESTRO_DATABASE_TYPE=postgres drizzle-kit generate", - "db:migrate": "bun run src/db/migrate.ts", - "db:migrate:status": "bun run -e \"import('./src/db/migrate.js').then(m => m.getMigrationStatus()).then(console.log)\"", - "db:studio": "drizzle-kit studio", - "db:seed": "bun run src/db/seed.ts", - "db:check": "bun run src/db/check.ts", - "vscode:build": "npx nx run vscode-extension:build", - "vscode:package": "npx nx run vscode-extension:package", - "vscode:publish": "npx nx run vscode-extension:publish", - "tui-rs:build": "cd packages/tui-rs && cargo build --release", - "control-plane-rs:build": "cd packages/control-plane-rs && cargo build --release --bin maestro-control-plane", - "control-plane-rs:check": "cd packages/control-plane-rs && cargo check --bin maestro-control-plane", - "rust:harness": "bash scripts/rust-local-harness.sh", - "tui-rs:build:debug": "cd packages/tui-rs && cargo build", - "tui-rs:check": "cd packages/tui-rs && cargo check", - "tui-rs:test": "cd packages/tui-rs && cargo test" - }, - "dependencies": { - "@aws-sdk/client-bedrock-runtime": "^3.1020.0", - "@bufbuild/protobuf": "^2.11.0", - "@crosscopy/clipboard": "^0.2.8", - "@daytonaio/sdk": "^0.155.0", - "@modelcontextprotocol/sdk": "^1.29.0", - "@opentelemetry/api": "^1.9.1", - "@opentelemetry/auto-instrumentations-node": "^0.75.0", - "@opentelemetry/resources": "^2.6.1", - "@opentelemetry/sdk-node": "0.217.0", - "@opentelemetry/semantic-conventions": "^1.40.0", - "@sentry/node": "^10.53.1", - "@sinclair/typebox": "^0.34.49", - "ajv": "^8.18.0", - "ajv-formats": "^3.0.1", - "bcrypt": "^6.0.0", - "chalk": "^5.6.2", - "clipboardy": "^4.0.0", - "diff": "^8.0.4", - "dotenv": "^16.6.1", - "drizzle-orm": "0.45.2", - "exceljs": "^4.4.0", - "fflate": "^0.8.2", - "glob": "^13.0.6", - "ioredis": "^5.10.1", - "jiti": "^2.6.1", - "jose": "^6.2.2", - "js-yaml": "^4.1.1", - "jsonc-parser": "^3.3.1", - "jsonwebtoken": "^9.0.3", - "jszip": "^3.10.1", - "luxon": "^3.7.2", - "mammoth": "^1.12.0", - "marked": "^17.0.5", - "mime-types": "^3.0.2", - "minimatch": "^10.2.5", - "nats": "^2.29.3", - "openai": "^6.33.0", - "otplib": "^13.4.0", - "partial-json": "^0.1.7", - "pdf-parse": "^2.4.5", - "postgres": "^3.4.8", - "smol-toml": "^1.6.1", - "string-width": "^8.2.0", - "uuid": "^14.0.0", - "vscode-jsonrpc": "^8.2.1", - "ws": "^8.20.0", - "yaml": "^2.8.3", - "zod": "^4.3.6", - "zod-validation-error": "^5.0.0" - }, - "devDependencies": { - "@bufbuild/buf": "^1.67.0", - "@bufbuild/protoc-gen-es": "2.12.0", - "@biomejs/biome": "^1.9.4", - "@google/genai": "^1.50.1", - "@smithy/types": "^4.13.1", - "@types/bcrypt": "^6.0.0", - "@types/diff": "^7.0.2", - "@types/js-yaml": "^4.0.9", - "@types/jsonwebtoken": "^9.0.10", - "@types/luxon": "^3.7.1", - "@types/mime-types": "^3.0.1", - "@types/node": "^24.12.0", - "@types/pdf-parse": "^1.1.5", - "@types/uuid": "^11.0.0", - "@vitest/coverage-v8": "^4.1.2", - "concurrently": "^9.2.1", - "drizzle-kit": "1.0.0-beta.21", - "esbuild": "^0.27.4", - "fast-check": "^4.6.0", - "google-auth-library": "^10.6.2", - "husky": "^9.1.7", - "nx": "22.6.5", - "tsx": "^4.21.0", - "typescript": "^5.9.3", - "vitest": "^4.1.2" - }, - "keywords": [ - "maestro", - "evalops", - "ai", - "llm", - "cli", - "tui", - "agent" - ], - "author": "EvalOps", - "license": "BUSL-1.1", - "maestro": { - "canonicalPackageName": "@evalops/maestro", - "packageAliases": [ - "@evalops/maestro", - "@evalops-jh/maestro" - ] - }, - "repository": { - "type": "git", - "url": "git+https://github.com/evalops/maestro.git" - }, - "engines": { - "node": ">=20.0.0", - "bun": ">=1.1.0" - }, - "overrides": { - "jws": ">=4.0.1", - "rollup": ">=4.59.0", - "koa": ">=2.16.4", - "axios": ">=1.15.0", - "follow-redirects": ">=1.16.0", - "@isaacs/brace-expansion": ">=5.0.1", - "picomatch": ">=4.0.4", - "qs": ">=6.14.2" - }, - "optionalDependencies": { - "sharp": "0.34.5", - "tree-sitter": "^0.25.0", - "tree-sitter-bash": "^0.25.1" - }, - "packageManager": "bun@1.3.6", - "trustedDependencies": [ - "electron", - "tree-sitter", - "tree-sitter-bash" - ] + "name": "@evalops/maestro", + "description": "Maestro by EvalOps - Deterministic coding agent with TUI/CLI and Web UI for AI-assisted development", + "version": "0.10.21", + "private": false, + "type": "module", + "workspaces": [ + "packages/*" + ], + "bin": { + "maestro": "dist/cli.js" + }, + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist", + "skills" + ], + "maestroRuntimeWorkspaces": [ + "@evalops/contracts", + "@evalops/tui" + ], + "scripts": { + "clean": "node ./scripts/clean-paths.js dist ./tmp/tsbuildinfo/composer.tsbuildinfo", + "prepare": "husky", + "postinstall": "node -e \"const fs=require('node:fs');const cp=require('node:child_process');if(!fs.existsSync('./scripts/ensure-deps.js')||!fs.existsSync('./packages/contracts/package.json'))process.exit(0);const r=cp.spawnSync(process.execPath,['./scripts/ensure-deps.js','--no-install'],{stdio:'inherit'});process.exit(r.status??1);\"", + "install:local": "node ./scripts/install-client.js", + "prebuild": "node ./scripts/ensure-deps.js && node ./scripts/session-wire-format-codegen.mjs && node ./scripts/headless-protocol-codegen.mjs && bun run generate:headless-proto:buf", + "build": "node ./scripts/ensure-dir.js ./tmp/tsbuildinfo && tsc -b tsconfig.build.json --force && bun build ./src/cli.ts --target node --packages external --external tree-sitter --external tree-sitter-bash --outfile dist/cli.js && node ./scripts/bundle-runtime-deps.mjs && node ./scripts/copy-themes.js && node ./scripts/copy-db-migrations.js", + "start": "node --enable-source-maps dist/cli.js", + "start:native": "MAESTRO_AGENT_SCRIPT=\"$(pwd)/dist/cli.js\" ./packages/tui-rs/target/release/maestro-tui", + "dev": "node ./scripts/headless-protocol-codegen.mjs && bun run generate:headless-proto:buf && node ./scripts/ensure-dir.js ./tmp/tsbuildinfo && tsc -b tsconfig.build.json --watch --preserveWatchOutput", + "dev:all": "concurrently --names \"cli,test\" --prefix-colors \"cyan,yellow\" \"npm run dev\" \"npm run test:watch\"", + "test:watch": "node ./scripts/run-vitest.js --watch", + "test:fast": "VITEST_FAST=1 node ./scripts/run-vitest.js --run", + "lint": "biome check . && npm run lint:evals", + "setup:worktree": "node scripts/setup-worktree.mjs", + "check:headless-proto:generated": "node scripts/check-headless-proto-generated.mjs", + "verify:headless-proto:sync": "node scripts/verify-headless-proto-sync.mjs", + "lint:headless-proto": "buf lint && bun run verify:headless-proto:sync && bun run check:headless-proto:generated", + "check:drift-surfaces": "node scripts/check-drift-prone-surfaces.mjs", + "check:staged-rollout": "node scripts/check-staged-rollout.mjs", + "check:context-manifest": "tsx scripts/check-context-manifest-contract.ts", + "check:session-wire-contract": "tsx scripts/check-session-wire-contract.ts", + "check:session-replay-fixtures": "tsx scripts/check-session-replay-fixtures.ts", + "check:agent-trajectory-fixtures": "tsx scripts/check-agent-trajectory-fixtures.ts", + "check:agent-trajectory-replay-fixtures": "tsx scripts/check-agent-trajectory-replay-fixtures.ts", + "check:agent-trajectory-score-fixtures": "tsx scripts/check-agent-trajectory-score-fixtures.ts", + "check:agent-trajectory-inspection-fixtures": "tsx scripts/check-agent-trajectory-inspection-fixtures.ts", + "check:agent-trajectory-scenario-fixtures": "tsx scripts/check-agent-trajectory-scenario-fixtures.ts", + "check:slack-contract-lab-scenarios": "tsx scripts/check-slack-contract-lab-scenarios.ts", + "check:scripted-scenario-fixtures": "tsx scripts/check-scripted-scenario-fixtures.ts", + "check:evidence-integrity": "tsx scripts/check-evidence-integrity.ts", + "check:scenario-replay-gate": "node scripts/run-scenario-replay-gate.mjs", + "check:codex-parity": "node scripts/check-codex-parity-conformance.mjs", + "check:codex-operating-layer": "node scripts/check-codex-operating-layer-conformance.mjs", + "lint:evals": "bun run lint:headless-proto && node scripts/ensure-deps.js --no-install --workspace @evalops/contracts && node scripts/verify-evals.js && node scripts/verify-tool-versions.js && node scripts/validate-system-paths.js && node scripts/validate-package-boundaries.js && node scripts/validate-public-package-deps.js && node scripts/check-public-surface-boundary.mjs && npm run check:context-manifest && npm run check:session-wire-contract && npm run check:evidence-integrity && npm run check:session-replay-fixtures && npm run check:agent-trajectory-fixtures && npm run check:agent-trajectory-replay-fixtures && npm run check:agent-trajectory-score-fixtures && npm run check:agent-trajectory-inspection-fixtures && npm run check:agent-trajectory-scenario-fixtures && npm run check:slack-contract-lab-scenarios && npm run check:scripted-scenario-fixtures && node scripts/session-wire-format-codegen.mjs --check && node scripts/headless-protocol-codegen.mjs --check && npm run check:drift-surfaces && npm run check:staged-rollout && npm run check:codex-parity && npm run check:codex-operating-layer && npm run developer-surface:check", + "platform:sdk-smoke": "tsx scripts/check-platform-sdk-contract.ts", + "platform:agentruntime-e2e": "tsx scripts/smoke-platform-agentruntime-lifecycle.ts", + "platform:timeline-e2e": "tsx scripts/smoke-platform-timeline-e2e.ts", + "platform:a2a-delegation-live": "tsx scripts/smoke-platform-a2a-delegation-live.ts", + "platform:a2a-evidence-verify": "tsx scripts/verify-platform-a2a-live-evidence.ts", + "developer-surface:check": "node scripts/check-developer-surface.mjs", + "format": "biome format .", + "check": "npm run lint && npm run check --workspaces --if-present && tsc -p tsconfig.build.json --noEmit", + "evals": "npm run build && node scripts/run-evals.js", + "evals:skill-package": "bunx tsx scripts/evals/run-skill-package-evals.ts", + "evals:pipeline-tool-integration": "bun run build && bunx tsx scripts/evals/run-pipeline-tool-integration-evals.ts", + "evals:shared-memory-integration": "bun run build && bunx tsx scripts/evals/run-shared-memory-integration-evals.ts", + "evals:platform-fermata-scenario-suite": "bun run build && bunx tsx scripts/evals/run-platform-fermata-scenario-suite.ts", + "evals:openrouter-live-smoke": "bun run build && bunx tsx scripts/evals/run-openrouter-live-smoke.ts", + "evals:openrouter-approvals-judge": "bun run build && bunx tsx scripts/evals/run-openrouter-approvals-judge-evals.ts", + "evals:openrouter-tool-surface-judge": "bun run build && bunx tsx scripts/evals/run-openrouter-tool-surface-judge-evals.ts", + "telemetry:report": "node scripts/telemetry-report.js", + "device-identity:harness": "MAESTRO_DEVICE_IDENTITY_ALLOW_TEST_HELPER=1 node ./scripts/run-vitest.js --run test/oauth-device-identity-harness.test.ts", + "generate-models": "bun scripts/generate-models.ts", + "generate:headless-protocol": "node scripts/headless-protocol-codegen.mjs", + "generate:session-wire-format": "node scripts/session-wire-format-codegen.mjs", + "check:session-wire-format:generated": "node scripts/session-wire-format-codegen.mjs --check", + "generate:headless-proto:buf": "buf generate --template buf.gen.yaml && bunx biome check --write --unsafe packages/contracts/src/proto/maestro/v1/headless_pb.ts", + "test": "node ./scripts/run-vitest.js --run", + "test:coverage": "node ./scripts/run-vitest.js --run --coverage", + "prepublishOnly": "npm run clean && npm run build && npm run verify:runtime-deps", + "bun:install": "bun install", + "bun:cli": "bun run ./src/cli.ts", + "bun:watch": "bun run --watch ./src/cli.ts", + "web": "node dist/web-server.js", + "web:rust-control": "packages/control-plane-rs/target/release/maestro-control-plane", + "web:dev": "node ./scripts/ensure-deps.js --workspace @evalops/contracts && concurrently --names \"server,ui\" --prefix-colors \"blue,green\" \"tsx --watch src/web-server.ts\" \"bun run dev:web\"", + "web:dev:local": "MAESTRO_WEB_REQUIRE_KEY=0 MAESTRO_WEB_REQUIRE_REDIS=0 MAESTRO_WEB_ORIGIN=http://localhost:3000 npm run web:dev", + "bun:lint": "bunx biome check . && bun run lint:evals", + "bun:test": "node ./scripts/run-vitest.js --run", + "bun:test:fast": "VITEST_FAST=1 node ./scripts/run-vitest.js --run", + "bun:check": "bun run bun:lint && bunx tsc --noEmit", + "bun:compile": "npm run build && bun build ./dist/cli.js --compile --external tree-sitter --external tree-sitter-bash --outfile dist/maestro-bun", + "bun:compile:bytecode": "npm run build && bun build ./dist/cli.js --compile --bytecode --external tree-sitter --external tree-sitter-bash --outfile dist/maestro-bun-bytecode", + "bun:evals": "bun run build && bun run ./scripts/run-evals.js", + "compile:binary": "npm run bun:compile && echo \"Binary ready at dist/maestro-bun\"", + "cli": "node ./dist/cli.js", + "verify-build": "bun scripts/verify-build.ts", + "verify-build:packages": "VERIFY_PACKAGES=1 bun scripts/verify-build.ts", + "release:check": "node scripts/release-readiness.js release", + "release:check:ci": "node scripts/release-readiness.js ci", + "ci:plan": "node scripts/plan-ci-checks.mjs", + "pr:ready": "node scripts/pr-ready-to-merge.mjs", + "pr:feedback": "node scripts/pr-feedback-audit.mjs", + "verify:runtime-deps": "node scripts/check-runtime-deps.js && node scripts/check-docker-runtime-workspaces.mjs && node scripts/check-packed-bundled-workspaces.mjs", + "tui": "npm run cli", + "verify": "npm run format && npm run lint && npm run test && npm run build && npm run smoke && npm run telemetry:report", + "smoke": "node scripts/smoke-cli.js", + "smoke:local-e2e": "node scripts/smoke-cli.js", + "smoke:codex-app-server-live": "node scripts/smoke-codex-app-server-live.mjs", + "smoke:event-bus": "tsx scripts/smoke-maestro-event-bus.ts", + "smoke:a2a-local": "tsx scripts/smoke-maestro-a2a-local.ts", + "smoke:a2a-input-required": "tsx scripts/smoke-maestro-a2a-input-required.ts", + "smoke:a2a-tmux": "bash scripts/smoke-maestro-a2a-tmux.sh", + "a2a": "tsx src/cli.ts a2a", + "a2a:codex-bridge": "python3 scripts/codex-a2a-bridge.py", + "a2a:peer": "tsx src/cli.ts a2a", + "smoke:headless": "node scripts/smoke-headless.js", + "headless:responsiveness": "node scripts/headless-responsiveness-harness.js", + "smoke:pack": "node scripts/smoke-packed-cli.js", + "metadata:sync": "node scripts/sync-package-metadata.js", + "metadata:check": "node scripts/sync-package-metadata.js --check", + "cutover:check": "node scripts/check-package-cutover-readiness.js", + "factory:import": "npm run build && node dist/scripts/import-factory-config.js", + "factory:export": "npm run build && node dist/scripts/export-factory-config.js", + "version:patch": "node scripts/version.js patch", + "version:minor": "node scripts/version.js minor", + "version:major": "node scripts/version.js major", + "version:sync": "node scripts/sync-versions.js", + "openapi:generate": "bun scripts/generate-openapi.ts", + "openapi:check": "bun scripts/generate-openapi.ts --check", + "openapi:serve": "bun scripts/serve-openapi.ts", + "nix:update-hash": "bash scripts/update-nix-hash.sh", + "dev:web": "bun run --filter @evalops/maestro-web dev", + "dev:tui": "bun run --filter @evalops/tui dev", + "dev:packages": "concurrently --names \"tui,web\" --prefix-colors \"magenta,green\" \"bun run dev:tui\" \"bun run dev:web\"", + "guardian": "bash scripts/guardian.sh", + "guardian:install-hook": "node scripts/install-guardian-hook.js", + "build:all": "bun run --filter @evalops/contracts build && bun run --filter @evalops/consumer build && bun run --filter @evalops/tui build && bun run --filter @evalops/maestro-web build && bun run build && bun run --filter @evalops/ai build", + "test:all": "npm run test && npm run test --workspaces --if-present", + "db:generate": "MAESTRO_DATABASE_TYPE=postgres drizzle-kit generate", + "db:migrate": "bun run src/db/migrate.ts", + "db:migrate:status": "bun run -e \"import('./src/db/migrate.js').then(m => m.getMigrationStatus()).then(console.log)\"", + "db:studio": "drizzle-kit studio", + "db:seed": "bun run src/db/seed.ts", + "db:check": "bun run src/db/check.ts", + "vscode:build": "npx nx run vscode-extension:build", + "vscode:package": "npx nx run vscode-extension:package", + "vscode:publish": "npx nx run vscode-extension:publish", + "tui-rs:build": "cd packages/tui-rs && cargo build --release", + "control-plane-rs:build": "cd packages/control-plane-rs && cargo build --release --bin maestro-control-plane", + "control-plane-rs:check": "cd packages/control-plane-rs && cargo check --bin maestro-control-plane", + "rust:harness": "bash scripts/rust-local-harness.sh", + "tui-rs:build:debug": "cd packages/tui-rs && cargo build", + "tui-rs:check": "cd packages/tui-rs && cargo check", + "tui-rs:test": "cd packages/tui-rs && cargo test" + }, + "dependencies": { + "@aws-sdk/client-bedrock-runtime": "^3.1020.0", + "@bufbuild/protobuf": "^2.11.0", + "@crosscopy/clipboard": "^0.2.8", + "@daytonaio/sdk": "^0.155.0", + "@modelcontextprotocol/sdk": "^1.29.0", + "@opentelemetry/api": "^1.9.1", + "@opentelemetry/auto-instrumentations-node": "^0.75.0", + "@opentelemetry/resources": "^2.6.1", + "@opentelemetry/sdk-node": "0.217.0", + "@opentelemetry/semantic-conventions": "^1.40.0", + "@sentry/node": "^10.53.1", + "@sinclair/typebox": "^0.34.49", + "ajv": "^8.18.0", + "ajv-formats": "^3.0.1", + "bcrypt": "^6.0.0", + "chalk": "^5.6.2", + "clipboardy": "^4.0.0", + "diff": "^8.0.4", + "dotenv": "^16.6.1", + "drizzle-orm": "0.45.2", + "exceljs": "^4.4.0", + "fflate": "^0.8.2", + "glob": "^13.0.6", + "ioredis": "^5.10.1", + "jiti": "^2.6.1", + "jose": "^6.2.2", + "js-yaml": "^4.1.1", + "jsonc-parser": "^3.3.1", + "jsonwebtoken": "^9.0.3", + "jszip": "^3.10.1", + "luxon": "^3.7.2", + "mammoth": "^1.12.0", + "marked": "^17.0.5", + "mime-types": "^3.0.2", + "minimatch": "^10.2.5", + "nats": "^2.29.3", + "openai": "^6.33.0", + "otplib": "^13.4.0", + "partial-json": "^0.1.7", + "pdf-parse": "^2.4.5", + "postgres": "^3.4.8", + "smol-toml": "^1.6.1", + "string-width": "^8.2.0", + "uuid": "^14.0.0", + "vscode-jsonrpc": "^8.2.1", + "ws": "^8.20.0", + "yaml": "^2.8.3", + "zod": "^4.3.6", + "zod-validation-error": "^5.0.0" + }, + "devDependencies": { + "@bufbuild/buf": "^1.67.0", + "@bufbuild/protoc-gen-es": "2.12.0", + "@biomejs/biome": "^1.9.4", + "@google/genai": "^1.50.1", + "@smithy/types": "^4.13.1", + "@types/bcrypt": "^6.0.0", + "@types/diff": "^7.0.2", + "@types/js-yaml": "^4.0.9", + "@types/jsonwebtoken": "^9.0.10", + "@types/luxon": "^3.7.1", + "@types/mime-types": "^3.0.1", + "@types/node": "^24.12.0", + "@types/pdf-parse": "^1.1.5", + "@types/uuid": "^11.0.0", + "@vitest/coverage-v8": "^4.1.2", + "concurrently": "^9.2.1", + "drizzle-kit": "1.0.0-beta.21", + "esbuild": "^0.27.4", + "fast-check": "^4.6.0", + "google-auth-library": "^10.6.2", + "husky": "^9.1.7", + "nx": "22.6.5", + "tsx": "^4.21.0", + "typescript": "^5.9.3", + "vitest": "^4.1.2" + }, + "keywords": [ + "maestro", + "evalops", + "ai", + "llm", + "cli", + "tui", + "agent" + ], + "author": "EvalOps", + "license": "BUSL-1.1", + "maestro": { + "canonicalPackageName": "@evalops/maestro", + "packageAliases": [ + "@evalops/maestro", + "@evalops-jh/maestro" + ] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/evalops/maestro.git" + }, + "engines": { + "node": ">=20.0.0", + "bun": ">=1.1.0" + }, + "overrides": { + "jws": ">=4.0.1", + "rollup": ">=4.59.0", + "koa": ">=2.16.4", + "axios": ">=1.15.0", + "follow-redirects": ">=1.16.0", + "@isaacs/brace-expansion": ">=5.0.1", + "picomatch": ">=4.0.4", + "qs": ">=6.14.2" + }, + "optionalDependencies": { + "sharp": "0.34.5", + "tree-sitter": "^0.25.0", + "tree-sitter-bash": "^0.25.1" + }, + "packageManager": "bun@1.3.6", + "trustedDependencies": [ + "electron", + "tree-sitter", + "tree-sitter-bash" + ] } diff --git a/packages/slack-agent/test/tools-status.test.ts b/packages/slack-agent/test/tools-status.test.ts index f916b7552..e757807af 100644 --- a/packages/slack-agent/test/tools-status.test.ts +++ b/packages/slack-agent/test/tools-status.test.ts @@ -2,6 +2,52 @@ import { describe, expect, it, vi } from "vitest"; import type { ExecOptions, Executor } from "../src/sandbox.js"; import { type ContainerHealth, createStatusTool } from "../src/tools/status.js"; +vi.mock("node:child_process", () => ({ + exec: vi.fn( + ( + cmd: string, + _options: unknown, + callback: (error: Error | null, stdout: string, stderr: string) => void, + ) => { + if (cmd.includes("docker inspect")) { + callback( + null, + JSON.stringify([ + { + Id: "abcdef1234567890", + Name: "/test-container", + Config: { Image: "node:20-slim" }, + State: { + StartedAt: new Date(Date.now() - 1000).toISOString(), + Status: "running", + }, + }, + ]), + "", + ); + return; + } + + if (cmd.includes("docker stats")) { + callback( + null, + JSON.stringify({ + CPUPerc: "1.23%", + MemUsage: "12MiB / 1GiB", + MemPerc: "1.17%", + NetIO: "1kB / 2kB", + BlockIO: "0B / 0B", + }), + "", + ); + return; + } + + callback(new Error(`unexpected command: ${cmd}`), "", ""); + }, + ), +})); + // Mock executor factory function createMockExecutor( responses: Record< @@ -159,7 +205,7 @@ describe("createStatusTool", () => { const health = result.details as ContainerHealth; expect(health.environment).toBe("docker"); - }); + }, 15_000); }); describe("output formatting", () => { diff --git a/scripts/ci-nx-tests.sh b/scripts/ci-nx-tests.sh index 9aac05235..181ad7309 100644 --- a/scripts/ci-nx-tests.sh +++ b/scripts/ci-nx-tests.sh @@ -26,6 +26,33 @@ affected_projects_log="nx-affected-projects.log" git diff --name-only "$NX_BASE" "$NX_HEAD" | tee "$changed_files_log" +changed_files_match() { + local pattern="$1" + grep -qE "$pattern" "$changed_files_log" +} + +run_ci_guardrail_tests() { + if ! changed_files_match '^(\.github/workflows/.*|scripts/ci-nx-tests\.sh|scripts/(plan-ci-checks|plan-nx-test-command)\.mjs|test/scripts/ci-guardrails\.test\.ts)$'; then + return 0 + fi + + echo "Running CI guardrail tests for workflow/planner changes..." + node ./scripts/run-vitest.js --run test/scripts/ci-guardrails.test.ts +} + +run_runtime_package_validators() { + if ! changed_files_match '^(package\.json|packages/[^/]+/package\.json|scripts/(bundle-runtime-deps|check-docker-runtime-workspaces|check-packed-bundled-workspaces|runtime-workspaces)\.mjs|scripts/(check-runtime-deps|validate-public-package-deps)\.js)$'; then + return 0 + fi + + echo "Running runtime package validators..." + node scripts/validate-public-package-deps.js + npm run build + node scripts/check-runtime-deps.js + node scripts/check-docker-runtime-workspaces.mjs + node scripts/check-packed-bundled-workspaces.mjs +} + run_shared_memory_tests() { if git diff --name-only "$NX_BASE" "$NX_HEAD" | grep -qE '^(src/shared-memory/|test/shared-memory/|src/config/env-vars\.ts|src/cli/commands/memory\.ts|src/cli/help\.ts|src/session/manager\.ts)'; then echo "Running shared memory tests..." @@ -34,6 +61,8 @@ run_shared_memory_tests() { } node scripts/ensure-deps.js --no-install --workspace @evalops/contracts --workspace @evalops/tui +run_ci_guardrail_tests +run_runtime_package_validators nx_plan="$(node scripts/plan-nx-test-command.mjs --base "$NX_BASE" --head "$NX_HEAD")" nx_mode="$(printf '%s\n' "$nx_plan" | sed -n '1p')" diff --git a/scripts/plan-ci-checks.mjs b/scripts/plan-ci-checks.mjs index 310ab8bfb..4d1683282 100755 --- a/scripts/plan-ci-checks.mjs +++ b/scripts/plan-ci-checks.mjs @@ -64,15 +64,45 @@ function isNestedReadme(path, prefix) { return rest.includes("/") && rest.endsWith("/README.md"); } +const CI_GUARDRAIL_FILES = new Set([ + "scripts/ci-nx-tests.sh", + "scripts/plan-ci-checks.mjs", + "scripts/plan-nx-test-command.mjs", + "test/scripts/ci-guardrails.test.ts", +]); +const RUNTIME_PACKAGE_VALIDATOR_FILES = new Set([ + "scripts/bundle-runtime-deps.mjs", + "scripts/check-docker-runtime-workspaces.mjs", + "scripts/check-packed-bundled-workspaces.mjs", + "scripts/check-runtime-deps.js", + "scripts/runtime-workspaces.mjs", + "scripts/validate-public-package-deps.js", +]); + +function isPackageManifest(path) { + return path === "package.json" || /^packages\/[^/]+\/package\.json$/.test(path); +} + +function isTestFile(path) { + return /(^|\/)test\/.*\.(test|spec)\.[cm]?[jt]sx?$/.test(path); +} + function shouldSkipCoverageForPath(path) { return ( + path.startsWith(".github/workflows/") || (path.startsWith("docs/") && path.endsWith(".md")) || + CI_GUARDRAIL_FILES.has(path) || + RUNTIME_PACKAGE_VALIDATOR_FILES.has(path) || + isPackageManifest(path) || + isTestFile(path) || isNestedReadme(path, "examples") || isNestedReadme(path, "packages") || isNestedReadme(path, "src") || + path === "CHANGELOG.md" || path === "CONTRIBUTING.md" || path === "CODE_OF_CONDUCT.md" || path === "SECURITY.md" || + path === "openapi.json" || path === "todo.md" || (hasNoSlash(path) && path.startsWith("LICENSE")) ); diff --git a/scripts/plan-nx-test-command.mjs b/scripts/plan-nx-test-command.mjs index fd4bf7fe1..a2612198b 100644 --- a/scripts/plan-nx-test-command.mjs +++ b/scripts/plan-nx-test-command.mjs @@ -3,6 +3,7 @@ import { execFileSync } from "node:child_process"; import process from "node:process"; import { pathToFileURL } from "node:url"; +import { getRuntimeWorkspacePackages } from "./runtime-workspaces.mjs"; const FORCE_ALL_PATTERNS = [ /^nx\.json$/, @@ -12,6 +13,22 @@ const FORCE_ALL_PATTERNS = [ /^package-lock\.json$/, /^packages\/[^/]+\/project\.json$/, ]; +const PACKAGE_MANIFEST_PATTERN = /^packages\/[^/]+\/package\.json$/; +const RELEASE_METADATA_FILES = new Set(["CHANGELOG.md"]); +const CI_GUARDRAIL_FILES = new Set([ + "scripts/ci-nx-tests.sh", + "scripts/plan-ci-checks.mjs", + "scripts/plan-nx-test-command.mjs", + "test/scripts/ci-guardrails.test.ts", +]); +const RUNTIME_PACKAGE_VALIDATOR_FILES = new Set([ + "scripts/bundle-runtime-deps.mjs", + "scripts/check-docker-runtime-workspaces.mjs", + "scripts/check-packed-bundled-workspaces.mjs", + "scripts/check-runtime-deps.js", + "scripts/runtime-workspaces.mjs", + "scripts/validate-public-package-deps.js", +]); function parseArgs(argv) { const args = { @@ -58,6 +75,140 @@ function stableJson(value) { return JSON.stringify(stableValue(value)); } +function asStringSet(value) { + return new Set( + (Array.isArray(value) ? value : []) + .filter((item) => typeof item === "string" && item.length > 0) + .sort(), + ); +} + +function setEquals(left, right) { + if (left.size !== right.size) { + return false; + } + for (const value of left) { + if (!right.has(value)) { + return false; + } + } + return true; +} + +function clonePackage(pkg) { + return pkg && typeof pkg === "object" + ? JSON.parse(JSON.stringify(pkg)) + : {}; +} + +function normalizeDependencySection({ + allowedAddedNames, + basePackage, + headPackage, + section, +}) { + const baseSection = + basePackage[section] && typeof basePackage[section] === "object" + ? basePackage[section] + : undefined; + const headSection = + headPackage[section] && typeof headPackage[section] === "object" + ? headPackage[section] + : undefined; + const names = new Set([ + ...Object.keys(baseSection ?? {}), + ...Object.keys(headSection ?? {}), + ]); + + for (const name of names) { + const baseHas = Boolean(baseSection && Object.hasOwn(baseSection, name)); + const headHas = Boolean(headSection && Object.hasOwn(headSection, name)); + if (name.startsWith("@evalops/") && baseHas && headHas) { + baseSection[name] = "__internal_workspace_version__"; + headSection[name] = "__internal_workspace_version__"; + continue; + } + if (!baseHas && headHas && allowedAddedNames.has(name)) { + delete headSection[name]; + } + } +} + +function removeEmptyDependencySections(pkg) { + for (const section of [ + "dependencies", + "devDependencies", + "optionalDependencies", + "peerDependencies", + ]) { + if ( + pkg[section] && + typeof pkg[section] === "object" && + Object.keys(pkg[section]).length === 0 + ) { + delete pkg[section]; + } + } +} + +function normalizeRuntimeWorkspaceMetadata(basePackage, headPackage) { + const baseRuntimeWorkspaces = asStringSet( + basePackage.maestroRuntimeWorkspaces ?? basePackage.bundleDependencies, + ); + const headRuntimeWorkspaces = asStringSet( + headPackage.maestroRuntimeWorkspaces ?? headPackage.bundleDependencies, + ); + if (!setEquals(baseRuntimeWorkspaces, headRuntimeWorkspaces)) { + return; + } + + delete basePackage.bundleDependencies; + delete basePackage.bundledDependencies; + delete basePackage.maestroRuntimeWorkspaces; + delete headPackage.bundleDependencies; + delete headPackage.bundledDependencies; + delete headPackage.maestroRuntimeWorkspaces; +} + +export function packageManifestReleaseMetadataOnlyChanged({ + allowedRootDependencyNames = [], + basePackage, + headPackage, + isRootPackage = false, +}) { + const normalizedBase = clonePackage(basePackage); + const normalizedHead = clonePackage(headPackage); + const allowedAddedNames = new Set( + isRootPackage ? allowedRootDependencyNames : [], + ); + + delete normalizedBase.version; + delete normalizedHead.version; + + if (isRootPackage) { + normalizeRuntimeWorkspaceMetadata(normalizedBase, normalizedHead); + } + + for (const section of [ + "dependencies", + "devDependencies", + "optionalDependencies", + "peerDependencies", + ]) { + normalizeDependencySection({ + allowedAddedNames, + basePackage: normalizedBase, + headPackage: normalizedHead, + section, + }); + } + + removeEmptyDependencySections(normalizedBase); + removeEmptyDependencySections(normalizedHead); + + return stableJson(normalizedBase) === stableJson(normalizedHead); +} + function packageJsonScriptsOnlyChanged(basePackage, headPackage) { const keys = new Set([ ...Object.keys(basePackage ?? {}), @@ -83,35 +234,59 @@ function normalizeChangedFiles(changedFiles) { .sort((left, right) => left.localeCompare(right)); } +function isHandledOutsideNx(file) { + return ( + CI_GUARDRAIL_FILES.has(file) || + RUNTIME_PACKAGE_VALIDATOR_FILES.has(file) || + file.startsWith(".github/workflows/") + ); +} + export function planNxTestCommand({ basePackage, changedFiles, headPackage, + handledOutsideNxFiles = [], + packageJsonMetadataOnlyFiles = [], + releaseMetadataOnlyFiles = [], rootProjectJsonOnlyRemovesTestSelfBuild = false, }) { const normalizedChangedFiles = normalizeChangedFiles(changedFiles); const hasPackageJsonChange = normalizedChangedFiles.includes("package.json"); + const handledOutsideNxSet = new Set(handledOutsideNxFiles); + const packageJsonMetadataOnlySet = new Set(packageJsonMetadataOnlyFiles); + const releaseMetadataOnlySet = new Set(releaseMetadataOnlyFiles); const packageJsonIsScriptsOnly = hasPackageJsonChange && packageJsonScriptsOnlyChanged(basePackage, headPackage); + const isFilteredMetadataOnlyFile = (file) => + (file === "package.json" && + (packageJsonIsScriptsOnly || packageJsonMetadataOnlySet.has(file))) || + (PACKAGE_MANIFEST_PATTERN.test(file) && + packageJsonMetadataOnlySet.has(file)) || + releaseMetadataOnlySet.has(file) || + handledOutsideNxSet.has(file); const forceAll = normalizedChangedFiles.some((file) => { - if (file === "package.json" && packageJsonIsScriptsOnly) { + if (isFilteredMetadataOnlyFile(file)) { return false; } if (file === "project.json" && rootProjectJsonOnlyRemovesTestSelfBuild) { return false; } - return file === "package.json" || FORCE_ALL_PATTERNS.some((pattern) => pattern.test(file)); + return ( + file === "package.json" || + FORCE_ALL_PATTERNS.some((pattern) => pattern.test(file)) + ); }); if (forceAll) { return { files: [], mode: "all" }; } - const affectedFiles = packageJsonIsScriptsOnly - ? normalizedChangedFiles.filter((file) => file !== "package.json") - : normalizedChangedFiles; + const affectedFiles = normalizedChangedFiles.filter( + (file) => !isFilteredMetadataOnlyFile(file), + ); if (affectedFiles.length === 0) { return { files: [], mode: "none" }; @@ -125,13 +300,101 @@ function git(args) { } function readPackageAt(ref) { + return readJsonAt(ref, "package.json"); +} + +function readJsonAt(ref, path) { try { - return JSON.parse(git(["show", `${ref}:package.json`])); + return JSON.parse(git(["show", `${ref}:${path}`])); } catch { return null; } } +function openApiInfoVersionOnlyChanged(base, head) { + const normalizedBase = clonePackage(base); + const normalizedHead = clonePackage(head); + if ( + normalizedBase.info && + typeof normalizedBase.info === "object" && + normalizedHead.info && + typeof normalizedHead.info === "object" + ) { + delete normalizedBase.info.version; + delete normalizedHead.info.version; + } + return stableJson(normalizedBase) === stableJson(normalizedHead); +} + +async function runtimeWorkspaceDependencyNames(rootPackage) { + if (!rootPackage || typeof rootPackage !== "object") { + return []; + } + const names = new Set(); + for (const workspacePackage of await getRuntimeWorkspacePackages(rootPackage)) { + for (const section of [ + "dependencies", + "optionalDependencies", + "peerDependencies", + ]) { + const deps = workspacePackage.data[section]; + if (!deps || typeof deps !== "object" || Array.isArray(deps)) { + continue; + } + for (const name of Object.keys(deps)) { + names.add(name); + } + } + } + return Array.from(names).sort(); +} + +async function metadataOnlyPackageFiles(base, head, changedFiles, headPackage) { + const allowedRootDependencyNames = await runtimeWorkspaceDependencyNames(headPackage); + const metadataFiles = []; + for (const file of changedFiles) { + if (file !== "package.json" && !PACKAGE_MANIFEST_PATTERN.test(file)) { + continue; + } + const baseJson = readJsonAt(base, file); + const headJson = readJsonAt(head, file); + if ( + packageManifestReleaseMetadataOnlyChanged({ + allowedRootDependencyNames, + basePackage: baseJson, + headPackage: headJson, + isRootPackage: file === "package.json", + }) + ) { + metadataFiles.push(file); + } + } + return metadataFiles; +} + +function metadataOnlyReleaseFiles(base, head, changedFiles) { + const metadataFiles = []; + for (const file of changedFiles) { + if (RELEASE_METADATA_FILES.has(file)) { + metadataFiles.push(file); + continue; + } + if (file !== "openapi.json") { + continue; + } + const baseJson = readJsonAt(base, file); + const headJson = readJsonAt(head, file); + if (openApiInfoVersionOnlyChanged(baseJson, headJson)) { + metadataFiles.push(file); + } + } + return metadataFiles; +} + +function handledOutsideNxFiles(changedFiles) { + return changedFiles.filter(isHandledOutsideNx); +} + function rootProjectJsonOnlyRemovesTestSelfBuild(base, head, changedFiles) { if (changedFiles.length !== 1 || changedFiles[0] !== "project.json") { return false; @@ -155,15 +418,28 @@ function rootProjectJsonOnlyRemovesTestSelfBuild(base, head, changedFiles) { ); } -function main() { +async function main() { const args = parseArgs(process.argv.slice(2)); const changedFiles = git(["diff", "--name-only", args.base, args.head]) .split("\n") .filter(Boolean); + const headPackage = readPackageAt(args.head); const plan = planNxTestCommand({ basePackage: readPackageAt(args.base), changedFiles, - headPackage: readPackageAt(args.head), + handledOutsideNxFiles: handledOutsideNxFiles(changedFiles), + headPackage, + packageJsonMetadataOnlyFiles: await metadataOnlyPackageFiles( + args.base, + args.head, + changedFiles, + headPackage, + ), + releaseMetadataOnlyFiles: metadataOnlyReleaseFiles( + args.base, + args.head, + changedFiles, + ), rootProjectJsonOnlyRemovesTestSelfBuild: rootProjectJsonOnlyRemovesTestSelfBuild( args.base, @@ -177,7 +453,7 @@ function main() { if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { try { - main(); + await main(); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exit(1); diff --git a/scripts/smoke-maestro-a2a-local-swarm.ts b/scripts/smoke-maestro-a2a-local-swarm.ts deleted file mode 100644 index aefa6b67b..000000000 --- a/scripts/smoke-maestro-a2a-local-swarm.ts +++ /dev/null @@ -1,815 +0,0 @@ -import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; -import { once } from "node:events"; -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; -import net from "node:net"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { - buildA2AUserMessage, - getA2ATask, - sendA2AMessage, - type A2AServiceConfig, -} from "../src/platform/a2a-client.js"; -import { - listA2APeerCandidatesWithPlatform, - type PlatformAgentRegistryAgent, -} from "../src/platform/agent-registry-client.js"; -import { SwarmExecutor } from "../src/agent/swarm/executor.js"; -import type { SwarmConfig, SwarmState } from "../src/agent/swarm/types.js"; - -const ORGANIZATION_ID = "org_local_a2a_swarm"; -const WORKSPACE_ID = "workspace_local_a2a_swarm"; -const REGISTRY_TOKEN = "local-a2a-swarm-token"; -const CONTROL_READY_TIMEOUT_MS = 120_000; -const REGISTRY_READY_TIMEOUT_MS = 30_000; -const SKILL_ID = "maestro.subagent.code-review"; -const DENIED_TASK_CLASS = "credential.materialization"; -const RESUME_TASK_ID = "local-swarm-resume-task"; - -type MockAgent = PlatformAgentRegistryAgent & { - currentObjectiveIds?: string[]; - heartbeatReceived?: boolean; -}; - -type CapturedRequest = { - body: Record; - headers: IncomingMessage["headers"]; - method?: string; - url?: string; -}; - -type MockRegistry = { - baseUrl: string; - close: () => Promise; - requests: CapturedRequest[]; - agents: Map; - waitForAgents: (count: number) => Promise; -}; - -type ControlPlaneInstance = { - agentId: string; - name: string; - baseUrl: string; - tasksPath: string; - process: ChildProcessWithoutNullStreams; - stderr: () => string; -}; - -type EnvSnapshot = Record; - -function delay(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -async function openPort(): Promise { - const server = net.createServer(); - await new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(0, "127.0.0.1", resolve); - }); - const address = server.address(); - if (address === null || typeof address === "string") { - server.close(); - throw new Error("failed to allocate a local TCP port"); - } - const port = address.port; - await new Promise((resolve, reject) => { - server.close((error) => (error ? reject(error) : resolve())); - }); - return port; -} - -function readBody(request: IncomingMessage): Promise { - return new Promise((resolve, reject) => { - let body = ""; - request.setEncoding("utf8"); - request.on("data", (chunk) => { - body += chunk; - }); - request.on("end", () => resolve(body)); - request.on("error", reject); - }); -} - -function respondJson( - response: ServerResponse, - status: number, - body: Record, -): void { - response.writeHead(status, { - "Content-Type": "application/json", - "Connect-Protocol-Version": "1", - }); - response.end(JSON.stringify(body)); -} - -function stringValue( - record: Record, - key: string, -): string | undefined { - const value = record[key]; - return typeof value === "string" && value.trim() ? value.trim() : undefined; -} - -function stringList(record: Record, key: string): string[] { - const value = record[key]; - return Array.isArray(value) - ? value.filter((item): item is string => typeof item === "string") - : []; -} - -function objectValue( - record: Record, - key: string, -): Record | undefined { - const value = record[key]; - return value && typeof value === "object" && !Array.isArray(value) - ? (value as Record) - : undefined; -} - -function skillList(agent: MockAgent): Array> { - const skills = agent.a2a?.skills; - return Array.isArray(skills) - ? skills.filter( - (skill): skill is Record => - Boolean(skill) && typeof skill === "object" && !Array.isArray(skill), - ) - : []; -} - -function skillAllowsTaskClass( - agent: MockAgent, - skillId: string | undefined, - taskClass: string | undefined, -): boolean { - if (!taskClass) { - return true; - } - const skills = skillList(agent).filter( - (skill) => !skillId || stringValue(skill, "id") === skillId, - ); - if (skills.length === 0) { - return false; - } - return skills.some((skill) => { - const denied = new Set(stringList(skill, "deniedTaskClasses")); - if (denied.has(taskClass)) { - return false; - } - const allowed = new Set(stringList(skill, "allowedTaskClasses")); - return allowed.size === 0 || allowed.has(taskClass); - }); -} - -function agentHasSkill(agent: MockAgent, skillId: string | undefined): boolean { - if (!skillId) { - return true; - } - return skillList(agent).some((skill) => stringValue(skill, "id") === skillId); -} - -function agentHasSurface(agent: MockAgent, surface: string | undefined): boolean { - if (!surface) { - return true; - } - return (agent.surfaces ?? []).includes(surface); -} - -function agentHasCapability( - agent: MockAgent, - capability: string | undefined, -): boolean { - if (!capability) { - return true; - } - return (agent.capabilities ?? []).includes(capability); -} - -function buildAgentFromRegister(body: Record): MockAgent { - const a2a = objectValue(body, "a2a"); - const now = new Date().toISOString(); - return { - id: stringValue(body, "id"), - workspaceId: stringValue(body, "workspaceId") ?? WORKSPACE_ID, - name: stringValue(body, "name"), - description: stringValue(body, "description"), - agentType: stringValue(body, "agentType") ?? "maestro", - capabilities: stringList(body, "capabilities"), - surfaces: stringList(body, "surfaces"), - surfaceTypes: stringList(body, "surfaceTypes"), - ownerId: stringValue(body, "ownerId"), - status: "AGENT_STATUS_IDLE", - heartbeatReceived: false, - createdAt: now, - updatedAt: now, - a2a: a2a as MockAgent["a2a"], - capacity: { - current: 0, - max: 2, - remaining: 2, - reservedDelegationCount: 0, - }, - }; -} - -function applyHeartbeat(agent: MockAgent, body: Record): MockAgent { - const now = new Date().toISOString(); - const a2a = objectValue(body, "a2a") as MockAgent["a2a"] | undefined; - return { - ...agent, - status: stringValue(body, "status") ?? agent.status, - lastHeartbeatAt: now, - heartbeatReceived: true, - updatedAt: now, - currentObjectiveIds: stringList(body, "currentObjectiveIds"), - surfaces: stringValue(body, "surface") - ? [stringValue(body, "surface") as string, "maestro"] - : agent.surfaces, - surfaceTypes: stringValue(body, "surfaceType") - ? [stringValue(body, "surfaceType") as string] - : agent.surfaceTypes, - a2a: a2a ?? agent.a2a, - }; -} - -function filterAgents( - agents: Iterable, - body: Record, -): MockAgent[] { - const workspaceId = stringValue(body, "workspaceId") ?? WORKSPACE_ID; - const capability = stringValue(body, "capability"); - const surface = stringValue(body, "surface"); - const status = stringValue(body, "status"); - const skillId = - stringValue(body, "a2aSkillId") ?? stringValue(body, "a2a_skill_id"); - const taskClass = - stringValue(body, "taskClass") ?? stringValue(body, "task_class"); - const limit = Number(body.limit); - return [...agents] - .filter((agent) => agent.workspaceId === workspaceId) - .filter((agent) => !status || agent.status === status) - .filter((agent) => agentHasCapability(agent, capability)) - .filter((agent) => agentHasSurface(agent, surface)) - .filter((agent) => agentHasSkill(agent, skillId)) - .filter((agent) => skillAllowsTaskClass(agent, skillId, taskClass)) - .slice(0, Number.isFinite(limit) && limit > 0 ? limit : undefined); -} - -async function startMockRegistry(): Promise { - const port = await openPort(); - const agents = new Map(); - const requests: CapturedRequest[] = []; - const server = createServer(async (request, response) => { - const rawBody = await readBody(request); - const body = rawBody.trim() - ? (JSON.parse(rawBody) as Record) - : {}; - requests.push({ - body, - headers: request.headers, - method: request.method, - url: request.url, - }); - - if (request.method !== "POST") { - respondJson(response, 405, { error: "method not allowed" }); - return; - } - - if (request.url === "/agents.v1.AgentService/Register") { - const agent = buildAgentFromRegister(body); - if (!agent.id) { - respondJson(response, 400, { error: "missing id" }); - return; - } - agents.set(agent.id, agent); - respondJson(response, 200, { agent }); - return; - } - - if (request.url === "/agents.v1.AgentService/Update") { - const id = stringValue(body, "id"); - if (!id) { - respondJson(response, 400, { error: "missing id" }); - return; - } - const existing = agents.get(id); - const updated = { - ...(existing ?? buildAgentFromRegister({ ...body, id })), - ...body, - updatedAt: new Date().toISOString(), - } as MockAgent; - agents.set(id, updated); - respondJson(response, 200, { agent: updated }); - return; - } - - if (request.url === "/agents.v1.AgentService/Heartbeat") { - const id = stringValue(body, "agentId"); - if (!id) { - respondJson(response, 400, { error: "missing agentId" }); - return; - } - const existing = - agents.get(id) ?? - buildAgentFromRegister({ - id, - workspaceId: WORKSPACE_ID, - name: id, - agentType: "maestro", - capabilities: [], - surfaces: ["a2a", "maestro"], - a2a: objectValue(body, "a2a"), - }); - agents.set(id, applyHeartbeat(existing, body)); - respondJson(response, 200, { - nextHeartbeatBy: new Date(Date.now() + 60_000).toISOString(), - }); - return; - } - - if (request.url === "/agents.v1.AgentService/List") { - const filtered = filterAgents(agents.values(), body); - respondJson(response, 200, { - agents: filtered, - total: filtered.length, - discoveryEvidence: { - schema: "evalops.local-a2a-swarm.discovery.v1", - decision: filtered.length > 0 ? "allow" : "deny", - workspaceId: stringValue(body, "workspaceId") ?? WORKSPACE_ID, - capability: stringValue(body, "capability"), - a2aSkillId: stringValue(body, "a2aSkillId"), - taskClass: stringValue(body, "taskClass"), - candidateCount: agents.size, - matchedCount: filtered.length, - }, - }); - return; - } - - respondJson(response, 404, { error: "unknown method" }); - }); - - await new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(port, "127.0.0.1", resolve); - }); - - return { - baseUrl: `http://127.0.0.1:${port}`, - requests, - agents, - close: async () => { - await new Promise((resolve, reject) => { - server.close((error) => (error ? reject(error) : resolve())); - }); - }, - waitForAgents: async (count: number) => { - const deadline = Date.now() + REGISTRY_READY_TIMEOUT_MS; - while (Date.now() < deadline) { - const heartbeated = [...agents.values()].filter( - (agent) => agent.heartbeatReceived && agent.a2a?.publicEndpointUrl, - ); - if (heartbeated.length >= count) { - return; - } - await delay(100); - } - throw new Error( - `mock Agent Registry saw ${agents.size} registered agents, expected ${count}`, - ); - }, - }; -} - -async function waitForHealth( - baseUrl: string, - stderr: () => string, -): Promise { - const deadline = Date.now() + CONTROL_READY_TIMEOUT_MS; - while (Date.now() < deadline) { - try { - const response = await fetch(`${baseUrl}/healthz`); - if (response.ok) { - return; - } - } catch { - // The Rust server may still be compiling or binding the port. - } - await delay(250); - } - throw new Error(`Rust control-plane did not become ready:\n${stderr()}`); -} - -async function startControlPlane(input: { - agentId: string; - name: string; - response: string; - port: number; - registryUrl: string; - rootDir: string; - objectiveId: string; - seedResumeTask?: boolean; -}): Promise { - const baseUrl = `http://127.0.0.1:${input.port}`; - const tasksPath = join(input.rootDir, `${input.agentId}-tasks.json`); - if (input.seedResumeTask) { - await seedInputRequiredTask(tasksPath); - } - let stderr = ""; - const child = spawn( - "cargo", - [ - "run", - "--quiet", - "--manifest-path", - "packages/control-plane-rs/Cargo.toml", - "--bin", - "maestro-control-plane", - ], - { - env: { - ...process.env, - MAESTRO_A2A_AGENT_ID: input.agentId, - MAESTRO_A2A_AGENT_NAME: input.name, - MAESTRO_A2A_CURRENT_OBJECTIVE_IDS: input.objectiveId, - MAESTRO_A2A_FAKE_RESPONSE: input.response, - MAESTRO_A2A_INTERNAL_URL: baseUrl, - MAESTRO_A2A_MAX_CONCURRENT_OBJECTIVES: "2", - MAESTRO_A2A_PLATFORM_HEARTBEAT_INTERVAL_MS: "500", - MAESTRO_A2A_PLATFORM_REGISTER: "1", - MAESTRO_A2A_PLATFORM_STATUS: "AGENT_STATUS_IDLE", - MAESTRO_A2A_PUBLIC_URL: baseUrl, - MAESTRO_A2A_TASKS_FILE: tasksPath, - MAESTRO_AGENT_REGISTRY_SERVICE_TOKEN: REGISTRY_TOKEN, - MAESTRO_AGENT_REGISTRY_SERVICE_URL: input.registryUrl, - MAESTRO_AGENT_REGISTRY_ORG_ID: ORGANIZATION_ID, - MAESTRO_AGENT_REGISTRY_WORKSPACE_ID: WORKSPACE_ID, - MAESTRO_CONTROL_HOST: "127.0.0.1", - MAESTRO_WEB_REQUIRE_KEY: "0", - PORT: String(input.port), - }, - stdio: ["ignore", "ignore", "pipe"], - }, - ); - child.stderr.on("data", (chunk: Buffer) => { - stderr += chunk.toString("utf8"); - }); - await waitForHealth(baseUrl, () => stderr); - return { - agentId: input.agentId, - name: input.name, - baseUrl, - tasksPath, - process: child, - stderr: () => stderr, - }; -} - -async function seedInputRequiredTask(path: string): Promise { - await writeFile( - path, - `${JSON.stringify( - { - tasks: [ - { - id: RESUME_TASK_ID, - contextId: "local-swarm-resume-context", - status: { - state: "TASK_STATE_INPUT_REQUIRED", - message: { - messageId: "local-swarm-resume-question", - contextId: "local-swarm-resume-context", - role: "ROLE_AGENT", - parts: [ - { - text: "Need one more bounded instruction before finishing.", - mediaType: "text/plain", - }, - ], - }, - }, - history: [ - { - messageId: "local-swarm-resume-user", - contextId: "local-swarm-resume-context", - role: "ROLE_USER", - parts: [ - { - text: "Start a resumable local swarm task.", - mediaType: "text/plain", - }, - ], - }, - ], - metadata: { - workspaceId: WORKSPACE_ID, - source: "smoke-maestro-a2a-local-swarm", - }, - }, - ], - }, - null, - 2, - )}\n`, - "utf8", - ); -} - -async function stopProcess(child: ChildProcessWithoutNullStreams): Promise { - if (child.exitCode !== null || child.signalCode !== null) { - return; - } - child.kill("SIGTERM"); - await Promise.race([once(child, "exit"), delay(2_000)]); - if (child.exitCode === null && child.signalCode === null) { - child.kill("SIGKILL"); - } -} - -function snapshotEnv(keys: string[]): EnvSnapshot { - return Object.fromEntries(keys.map((key) => [key, process.env[key]])); -} - -function restoreEnv(snapshot: EnvSnapshot): void { - for (const [key, value] of Object.entries(snapshot)) { - if (value === undefined) { - delete process.env[key]; - } else { - process.env[key] = value; - } - } -} - -function configurePlatformEnv(registryUrl: string): EnvSnapshot { - const keys = [ - "MAESTRO_AGENT_REGISTRY_SERVICE_URL", - "MAESTRO_AGENT_REGISTRY_SERVICE_TOKEN", - "MAESTRO_AGENT_REGISTRY_ORG_ID", - "MAESTRO_AGENT_REGISTRY_WORKSPACE_ID", - "MAESTRO_AGENT_REGISTRY_TIMEOUT_MS", - "MAESTRO_AGENT_REGISTRY_MAX_ATTEMPTS", - ]; - const snapshot = snapshotEnv(keys); - process.env.MAESTRO_AGENT_REGISTRY_SERVICE_URL = registryUrl; - process.env.MAESTRO_AGENT_REGISTRY_SERVICE_TOKEN = REGISTRY_TOKEN; - process.env.MAESTRO_AGENT_REGISTRY_ORG_ID = ORGANIZATION_ID; - process.env.MAESTRO_AGENT_REGISTRY_WORKSPACE_ID = WORKSPACE_ID; - process.env.MAESTRO_AGENT_REGISTRY_TIMEOUT_MS = "1500"; - process.env.MAESTRO_AGENT_REGISTRY_MAX_ATTEMPTS = "1"; - return snapshot; -} - -async function provePolicyDenial(registryUrl: string): Promise { - const snapshot = configurePlatformEnv(registryUrl); - try { - const denied = await listA2APeerCandidatesWithPlatform({ - workspaceId: WORKSPACE_ID, - capability: "code:review", - surface: "a2a", - status: "AGENT_STATUS_IDLE", - skillId: SKILL_ID, - taskClass: DENIED_TASK_CLASS, - requireA2ADispatch: true, - eligibleForDelegation: true, - }); - return denied?.length ?? 0; - } finally { - restoreEnv(snapshot); - } -} - -function peerConfig(instance: ControlPlaneInstance): A2AServiceConfig { - return { - baseUrl: instance.baseUrl, - workspaceId: WORKSPACE_ID, - organizationId: ORGANIZATION_ID, - token: REGISTRY_TOKEN, - agentId: instance.agentId, - actorId: "local-a2a-swarm-smoke", - timeoutMs: 1_500, - maxAttempts: 1, - }; -} - -async function proveResume(instance: ControlPlaneInstance, taskId: string) { - const config = peerConfig(instance); - const response = await sendA2AMessage(config, { - message: buildA2AUserMessage({ - messageId: `local-swarm-resume-${Date.now()}`, - contextId: "local-swarm-resume-context", - taskId, - text: "Resume this existing A2A task and return the deterministic response again.", - }), - configuration: { - acceptedOutputModes: ["text/plain"], - returnImmediately: false, - }, - }); - const task = await getA2ATask(config, response.task.id); - if (task.id !== taskId) { - throw new Error(`resume created sibling task ${task.id}, expected ${taskId}`); - } - if (task.status.state !== "TASK_STATE_COMPLETED") { - throw new Error(`resumed task ended in ${task.status.state}`); - } - return { - taskId: task.id, - state: task.status.state, - }; -} - -function taskText(state: SwarmState, taskId: string): string | undefined { - return state.teammates.find((teammate) => - teammate.completedTasks.includes(taskId), - )?.output; -} - -async function runSwarm( - registryUrl: string, - rootDir: string, -): Promise { - const planFile = join(rootDir, "local-a2a-swarm-plan.md"); - await writeFile( - planFile, - [ - "# Local A2A Swarm Smoke", - "", - "- alpha-review: prove Platform-discovered peer alpha can complete remote A2A work.", - "- beta-review: prove Platform-discovered peer beta can complete remote A2A work.", - ].join("\n"), - "utf8", - ); - const config: SwarmConfig = { - teammateCount: 2, - planFile, - cwd: process.cwd(), - mode: "smart", - modelProvider: "anthropic", - transport: "a2a", - tasks: [ - { - id: "alpha-review", - prompt: "Return the alpha deterministic A2A swarm response.", - subagentType: "review", - }, - { - id: "beta-review", - prompt: "Return the beta deterministic A2A swarm response.", - subagentType: "review", - }, - ], - a2a: { - discover: true, - workspaceId: WORKSPACE_ID, - capability: "code:review", - surface: "a2a", - skillId: SKILL_ID, - preferInternalEndpoint: true, - tasksPath: join(rootDir, "swarm-a2a-tasks.json"), - timeoutMs: 1_500, - maxAttempts: 1, - maxWaitMs: 20_000, - pollIntervalMs: 100, - }, - taskTimeout: 20_000, - }; - const snapshot = configurePlatformEnv(registryUrl); - try { - const executor = new SwarmExecutor(config); - const result = await executor.execute(); - if (result.status !== "completed") { - throw new Error(`A2A swarm did not complete: ${result.status}`); - } - if ( - taskText(result, "alpha-review") !== "A2A local swarm response from alpha" - ) { - throw new Error("alpha task did not return the alpha peer response"); - } - if (taskText(result, "beta-review") !== "A2A local swarm response from beta") { - throw new Error("beta task did not return the beta peer response"); - } - return result; - } finally { - restoreEnv(snapshot); - } -} - -async function main(): Promise { - const rootDir = await mkdtemp(join(tmpdir(), "maestro-a2a-local-swarm-")); - const registry = await startMockRegistry(); - const instances: ControlPlaneInstance[] = []; - try { - await mkdir(rootDir, { recursive: true }); - const alphaPort = await openPort(); - const betaPort = await openPort(); - instances.push( - await startControlPlane({ - agentId: "maestro-a2a-local-alpha", - name: "Maestro Local A2A Alpha", - response: "A2A local swarm response from alpha", - port: alphaPort, - registryUrl: registry.baseUrl, - rootDir, - objectiveId: "objective-alpha", - seedResumeTask: true, - }), - ); - instances.push( - await startControlPlane({ - agentId: "maestro-a2a-local-beta", - name: "Maestro Local A2A Beta", - response: "A2A local swarm response from beta", - port: betaPort, - registryUrl: registry.baseUrl, - rootDir, - objectiveId: "objective-beta", - }), - ); - await registry.waitForAgents(2); - const deniedCandidateCount = await provePolicyDenial(registry.baseUrl); - if (deniedCandidateCount !== 0) { - throw new Error( - `denied discovery returned ${deniedCandidateCount} candidates`, - ); - } - const swarm = await runSwarm(registry.baseUrl, rootDir); - const completedExecutions = swarm.teammates - .map((teammate) => teammate.a2a) - .filter((a2a): a2a is NonNullable => Boolean(a2a)); - const peersUsed = new Set(completedExecutions.map((a2a) => a2a.peer)); - if (peersUsed.size !== 2) { - throw new Error( - `expected swarm to use both local peers, used ${[...peersUsed].join(", ")}`, - ); - } - const alpha = instances.find( - (instance) => instance.name === "Maestro Local A2A Alpha", - ); - if (!alpha) { - throw new Error("missing alpha control plane"); - } - const resume = await proveResume(alpha, RESUME_TASK_ID); - const ledger = JSON.parse( - await readFile(join(rootDir, "swarm-a2a-tasks.json"), "utf8"), - ) as Record; - console.log( - JSON.stringify( - { - ok: true, - registry: { - url: registry.baseUrl, - registeredAgents: [...registry.agents.keys()], - registerCount: registry.requests.filter((request) => - request.url?.endsWith("/Register"), - ).length, - heartbeatCount: registry.requests.filter((request) => - request.url?.endsWith("/Heartbeat"), - ).length, - heartbeatReceivedAgents: [...registry.agents.values()].filter( - (agent) => agent.heartbeatReceived, - ).length, - listCount: registry.requests.filter((request) => - request.url?.endsWith("/List"), - ).length, - policyDeniedCandidateCount: deniedCandidateCount, - }, - swarm: { - id: swarm.id, - status: swarm.status, - completedTasks: [...swarm.completedTasks], - peersUsed: [...peersUsed], - remoteTasks: completedExecutions.map((a2a) => ({ - peer: a2a.peer, - source: a2a.source, - taskId: a2a.taskId, - contextId: a2a.contextId, - skillId: a2a.skillId, - })), - ledgerTasks: Array.isArray(ledger.tasks) - ? ledger.tasks.length - : undefined, - }, - resume, - }, - null, - 2, - ), - ); - } finally { - await Promise.all( - instances.map((instance) => stopProcess(instance.process)), - ); - await registry.close(); - if (process.env.MAESTRO_A2A_LOCAL_SWARM_KEEP_TMP !== "1") { - await rm(rootDir, { recursive: true, force: true }); - } - } -} - -main().catch((error: unknown) => { - console.error(error instanceof Error ? error.stack : String(error)); - process.exit(1); -}); diff --git a/scripts/verify-platform-a2a-live-evidence.ts b/scripts/verify-platform-a2a-live-evidence.ts index a916e5ef7..906acdffb 100644 --- a/scripts/verify-platform-a2a-live-evidence.ts +++ b/scripts/verify-platform-a2a-live-evidence.ts @@ -399,11 +399,17 @@ function verifyGithubEvidence( integerStringField(github, "actionsRunId") ?? integerStringField(github, "ghaRunId"); const runUrl = optionalString(github, "runUrl"); - if (runUrl && !/\/actions\/runs\/[1-9]\d*(?:$|[/?#])/u.test(runUrl)) { + const runUrlId = runUrl ? githubActionsRunIdFromUrl(runUrl) : undefined; + if (runUrl && !runUrlId) { throw new Error( `Platform A2A evidence GitHub run URL is not dereferenceable: ${runUrl}`, ); } + if (runId && runUrlId && runUrlId !== runId) { + throw new Error( + `Platform A2A evidence GitHub run URL id ${runUrlId} does not match runId ${runId}`, + ); + } const pullRequestNumber = positiveIntegerField(github, "pullRequestNumber") ?? positiveIntegerField(github, "prNumber") ?? @@ -441,6 +447,7 @@ async function verifyDereferenceableGithubEvidence( "Platform A2A evidence requires dereferenceable GitHub metadata but has no Actions run id", ); } + requireHttpsGithubServerUrl(github.serverUrl); const env = options.env ?? process.env; const apiClient = options.githubApiClient ?? defaultGithubApiClient; const run = requireRecord( @@ -476,6 +483,22 @@ async function verifyDereferenceableGithubEvidence( return true; } +function githubActionsRunIdFromUrl(value: string): string | undefined { + return /\/actions\/runs\/([1-9]\d*)(?:$|[/?#])/u.exec(value)?.[1]; +} + +function requireHttpsGithubServerUrl(serverUrl: string | undefined): void { + if (!serverUrl) { + return; + } + const url = new URL(serverUrl); + if (url.protocol !== "https:") { + throw new Error( + `Platform A2A evidence GitHub server URL must use HTTPS when dereference is required: ${serverUrl}`, + ); + } +} + function githubServerUrl(value: string | undefined): string | undefined { if (!value) { return undefined; diff --git a/src/agent/transport.ts b/src/agent/transport.ts index 9bf38101f..2b300c6e1 100644 --- a/src/agent/transport.ts +++ b/src/agent/transport.ts @@ -262,6 +262,8 @@ const REPO_PATH_ARGUMENTS_BY_TOOL = new Map([ const GIT_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX = "git:"; const RUN_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX = "run:"; +// Keep network-backed READ_ONLY_TOOLS out of reusable caches even if metadata is absent. +const NETWORK_BACKED_REUSABLE_TOOL_DENYLIST = new Set(["extract_document"]); const REQUIRED_REPO_PATH_ARGUMENT_TOOLS = new Set(["read", "ls", "list"]); @@ -483,6 +485,9 @@ function getReusableToolResultCacheKey( } const toolName = tool.name.toLowerCase(); const cacheKey = `${toolCall.name}:${stableStringify(toolCall.arguments)}`; + if (NETWORK_BACKED_REUSABLE_TOOL_DENYLIST.has(toolName)) { + return undefined; + } if (isGitSnapshotReusableToolCall(tool, toolCall, cwd)) { return `${GIT_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX}${cacheKey}`; } diff --git a/src/telemetry/cli-command-aggregator.ts b/src/telemetry/cli-command-aggregator.ts index a867db77e..8e4ba8f76 100644 --- a/src/telemetry/cli-command-aggregator.ts +++ b/src/telemetry/cli-command-aggregator.ts @@ -27,6 +27,7 @@ const LOCK_RETRY_MS = 5; const DEFAULT_LOCK_TIMEOUT_MS = 5_000; const LOCK_STALE_GRACE_MS = 1_000; let globalAggregator: CliCommandAggregator | null = null; +const inProcessBufferLockQueues = new Map>(); export class CliCommandAggregator { private readonly bufferMs: number; @@ -149,6 +150,15 @@ export class CliCommandAggregator { private async withBufferLock(operation: () => Promise): Promise { const lockFile = `${this.bufferFile}.lock`; + await runWithInProcessBufferLock(lockFile, () => + this.withBufferFileLock(lockFile, operation), + ); + } + + private async withBufferFileLock( + lockFile: string, + operation: () => Promise, + ): Promise { const deadline = Date.now() + this.lockTimeoutMs; let handle: Awaited> | undefined; while (!handle) { @@ -273,6 +283,28 @@ export class CliCommandAggregator { } } +async function runWithInProcessBufferLock( + lockFile: string, + operation: () => Promise, +): Promise { + const previous = inProcessBufferLockQueues.get(lockFile) ?? Promise.resolve(); + let releaseCurrent: () => void = () => undefined; + const current = new Promise((resolve) => { + releaseCurrent = resolve; + }); + const queued = previous.catch(() => undefined).then(() => current); + inProcessBufferLockQueues.set(lockFile, queued); + await previous.catch(() => undefined); + try { + await operation(); + } finally { + releaseCurrent(); + if (inProcessBufferLockQueues.get(lockFile) === queued) { + inProcessBufferLockQueues.delete(lockFile); + } + } +} + export function getGlobalCliCommandAggregator( options: CliCommandAggregatorOptions, ): CliCommandAggregator { diff --git a/test/agent/provider-transport-provider-tools.test.ts b/test/agent/provider-transport-provider-tools.test.ts index 49b80c339..9bbfa899f 100644 --- a/test/agent/provider-transport-provider-tools.test.ts +++ b/test/agent/provider-transport-provider-tools.test.ts @@ -954,7 +954,7 @@ describe("ProviderTransport provider-owned tool events", () => { expect(endEvent?.result).not.toHaveProperty("approvalRequestId"); }); - it("returns workflow-state errors from cached dynamic callbacks", async () => { + it("returns workflow-state errors from repeated dynamic callbacks", async () => { const { bridge, recordObservation } = createObservingPlatformBridge(); const toolExecute = vi.fn(async () => ({ content: [{ type: "text" as const, text: "redacted" }], @@ -1123,14 +1123,14 @@ describe("ProviderTransport provider-owned tool events", () => { toolName: "read", displayName: "Codex dynamic tool: read", summaryLabel: "read", - args: { file_path: "workspace/project/guarded.txt" }, + args: { file_path: "fixtures/guarded.txt" }, partial: assistant, } satisfies AssistantMessageEvent; const result = await options.executeDynamicTool({ type: "toolCall", id: toolCallId, name: "read", - arguments: { file_path: "workspace/project/guarded.txt" }, + arguments: { file_path: "fixtures/guarded.txt" }, }); dynamicResults.push(result); yield { @@ -1202,16 +1202,12 @@ describe("ProviderTransport provider-owned tool events", () => { ).toHaveLength(2); expect(dynamicResults).toEqual([ { - content: [ - { type: "text", text: "dynamic:workspace/project/guarded.txt:1" }, - ], + content: [{ type: "text", text: "dynamic:fixtures/guarded.txt:1" }], isError: false, details: undefined, }, { - content: [ - { type: "text", text: "dynamic:workspace/project/guarded.txt:1" }, - ], + content: [{ type: "text", text: "dynamic:fixtures/guarded.txt:1" }], isError: false, details: undefined, }, @@ -1262,7 +1258,7 @@ describe("ProviderTransport provider-owned tool events", () => { toolName: "read", displayName: "Codex dynamic tool: read", summaryLabel: "read", - args: { path: "docs/evalops.txt" }, + args: { path: "package.json" }, partial: assistant, } satisfies AssistantMessageEvent; resultPromises.push( @@ -1270,7 +1266,7 @@ describe("ProviderTransport provider-owned tool events", () => { type: "toolCall", id: toolCallId, name: "read", - arguments: { path: "docs/evalops.txt" }, + arguments: { path: "package.json" }, }), ); } @@ -1332,7 +1328,7 @@ describe("ProviderTransport provider-owned tool events", () => { expect(toolExecute).toHaveBeenCalledTimes(1); expect(dynamicResults).toEqual( Array.from({ length: repeatedToolCalls }, () => ({ - content: [{ type: "text", text: "dynamic:docs/evalops.txt:1" }], + content: [{ type: "text", text: "dynamic:package.json:1" }], isError: false, details: undefined, })), @@ -1405,7 +1401,7 @@ describe("ProviderTransport provider-owned tool events", () => { type: "toolCall", id: "dynamic-read-before-write", name: "read", - arguments: { path: "/tmp/evalops.txt" }, + arguments: { path: "package.json" }, }), ); const writePromise = options.executeDynamicTool({ @@ -1413,7 +1409,7 @@ describe("ProviderTransport provider-owned tool events", () => { id: "dynamic-write", name: "write", arguments: { - path: "/tmp/evalops.txt", + path: "package.json", content: "new content", }, }); @@ -1423,7 +1419,7 @@ describe("ProviderTransport provider-owned tool events", () => { type: "toolCall", id: "dynamic-read-during-write", name: "read", - arguments: { path: "/tmp/evalops.txt" }, + arguments: { path: "package.json" }, }), ); resolveWrite?.(); @@ -1458,12 +1454,12 @@ describe("ProviderTransport provider-owned tool events", () => { expect(writeToolExecute).toHaveBeenCalledTimes(1); expect(dynamicResults).toEqual([ { - content: [{ type: "text", text: "dynamic:/tmp/evalops.txt:1" }], + content: [{ type: "text", text: "dynamic:package.json:1" }], isError: false, details: undefined, }, { - content: [{ type: "text", text: "dynamic:/tmp/evalops.txt:2" }], + content: [{ type: "text", text: "dynamic:package.json:2" }], isError: false, details: undefined, }, @@ -1515,7 +1511,7 @@ describe("ProviderTransport provider-owned tool events", () => { type: "toolCall", id: toolCallId, name: "read", - arguments: { path: "docs/evalops.txt" }, + arguments: { path: "package.json" }, }); yield { type: "provider_tool_execution_end", @@ -1629,7 +1625,7 @@ describe("ProviderTransport provider-owned tool events", () => { toolCall: { id: `read-call-${streamCount}`, name: "read", - arguments: { file_path: "docs/evalops.txt" }, + arguments: { file_path: "package.json" }, }, partial: assistant, } satisfies AssistantMessageEvent; @@ -1671,7 +1667,7 @@ describe("ProviderTransport provider-owned tool events", () => { .map((item) => (item.type === "text" ? item.text : "")) .join(""), ), - ).toEqual(Array(repeatedToolCalls).fill("read:docs/evalops.txt:1")); + ).toEqual(Array(repeatedToolCalls).fill("read:package.json:1")); expect(readResults.every((event) => event.isError === false)).toBe(true); }); @@ -1716,7 +1712,7 @@ describe("ProviderTransport provider-owned tool events", () => { toolCall: { id: `observed-read-call-${streamCount}`, name: "read", - arguments: { file_path: "docs/evalops.txt" }, + arguments: { file_path: "package.json" }, }, partial: assistant, } satisfies AssistantMessageEvent; @@ -2181,7 +2177,7 @@ describe("ProviderTransport provider-owned tool events", () => { toolCall: { id: `guarded-read-call-${streamCount}`, name: "read", - arguments: { file_path: "workspace/project/guarded.txt" }, + arguments: { file_path: "fixtures/guarded.txt" }, }, partial: assistant, } satisfies AssistantMessageEvent; @@ -2239,8 +2235,8 @@ describe("ProviderTransport provider-owned tool events", () => { .join(""), ), ).toEqual([ - "guarded:workspace/project/guarded.txt:1", - "guarded:workspace/project/guarded.txt:1", + "guarded:fixtures/guarded.txt:1", + "guarded:fixtures/guarded.txt:1", ]); }); diff --git a/test/agent/provider-transport-tool-concurrency.test.ts b/test/agent/provider-transport-tool-concurrency.test.ts index 56d5ed389..ea8aba381 100644 --- a/test/agent/provider-transport-tool-concurrency.test.ts +++ b/test/agent/provider-transport-tool-concurrency.test.ts @@ -3692,6 +3692,155 @@ describe("ProviderTransport tool scheduling", () => { } }); + for (const toolName of ["search", "parallel_ripgrep"] as const) { + it(`does not reuse ${toolName} results when gitignore is bypassed`, async () => { + const tempDir = mkdtempSync(`${tmpdir()}/maestro-cache-no-ignore-`); + try { + execFileSync("git", ["init"], { cwd: tempDir, stdio: "ignore" }); + writeFileSync(resolve(tempDir, ".gitignore"), "*.log\n"); + execFileSync("git", ["add", ".gitignore"], { + cwd: tempDir, + stdio: "ignore", + }); + execFileSync( + "git", + [ + "-c", + "user.name=Maestro Test", + "-c", + "user.email=maestro@example.com", + "commit", + "-m", + "init", + ], + { cwd: tempDir, stdio: "ignore" }, + ); + + let searchExecutionCount = 0; + const searchTool: AgentTool = { + name: toolName, + description: "Search probe that can include ignored files.", + parameters: Type.Object({ + path: Type.String(), + useGitIgnore: Type.Boolean(), + }), + annotations: { + readOnlyHint: true, + }, + execute: async (_toolCallId, args) => { + searchExecutionCount += 1; + return { + content: [ + { + type: "text", + text: `${toolName}:${String(args.useGitIgnore)}:${searchExecutionCount}`, + }, + ], + }; + }, + }; + + let streamCount = 0; + mocks.createProviderStream.mockImplementation(async function* () { + streamCount += 1; + const call = + streamCount === 1 + ? { + id: `${toolName}-no-ignore-1`, + arguments: { path: ".", useGitIgnore: false }, + } + : streamCount === 3 + ? { + id: `${toolName}-no-ignore-2`, + arguments: { path: ".", useGitIgnore: false }, + } + : undefined; + if (call) { + const assistant = assistantMessage([], "toolUse"); + yield { + type: "start", + partial: assistant, + } satisfies AssistantMessageEvent; + yield { + type: "toolcall_end", + toolCall: { + type: "toolCall", + id: call.id, + name: toolName, + arguments: call.arguments, + }, + partial: assistant, + } satisfies AssistantMessageEvent; + yield { + type: "done", + reason: "toolUse", + message: assistant, + } satisfies AssistantMessageEvent; + return; + } + + const assistant = assistantMessage( + [{ type: "text", text: `${toolName} no-ignore complete` }], + "stop", + ); + yield { + type: "start", + partial: assistant, + } satisfies AssistantMessageEvent; + yield { + type: "done", + reason: "stop", + message: assistant, + } satisfies AssistantMessageEvent; + }); + + const transport = new ProviderTransport({ + cwd: tempDir, + maxConcurrentToolExecutions: 4, + platformToolExecutionBridge: false, + }); + const runTurn = (content: string) => { + const userMessage: Message = { + role: "user", + content, + timestamp: Date.now(), + }; + return drain( + transport.run([userMessage], userMessage, { + systemPrompt: "Use the requested tools.", + tools: [searchTool], + model, + }), + ); + }; + + const firstEvents = await runTurn("Search ignored files."); + writeFileSync(resolve(tempDir, "app.log"), "ignored\n"); + const secondEvents = await runTurn("Search ignored files again."); + const toolResultsById = new Map( + [...firstEvents, ...secondEvents] + .filter( + ( + event, + ): event is Extract => + event.type === "tool_execution_end", + ) + .map((event) => [event.toolCallId, event]), + ); + + expect(searchExecutionCount).toBe(2); + expect( + toolResultsById.get(`${toolName}-no-ignore-1`)?.scheduling?.cache, + ).toBe("disabled"); + expect( + toolResultsById.get(`${toolName}-no-ignore-2`)?.scheduling?.cache, + ).toBe("disabled"); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } + }); + } + it("reuses adjacent-turn read results for visible repo paths", async () => { const tempDir = mkdtempSync(`${tmpdir()}/maestro-cache-visible-`); try { @@ -4482,6 +4631,107 @@ describe("ProviderTransport tool scheduling", () => { ); }); + it("does not reuse network-backed built-in read-only results inside a run", async () => { + let extractExecutionCount = 0; + const extractDocumentTool = { + name: "extract_document", + description: "Fetch a remote document and extract text.", + parameters: Type.Object({ url: Type.String() }), + execute: async (_toolCallId: string, args: Record) => { + extractExecutionCount += 1; + return { + content: [ + { + type: "text" as const, + text: `document:${String(args.url)}:${extractExecutionCount}`, + }, + ], + }; + }, + } satisfies AgentTool; + + let streamCount = 0; + mocks.createProviderStream.mockImplementation(async function* () { + streamCount += 1; + if (streamCount === 1) { + const assistant = assistantMessage([], "toolUse"); + yield { + type: "start", + partial: assistant, + } satisfies AssistantMessageEvent; + for (const id of ["extract-1", "extract-2"]) { + yield { + type: "toolcall_end", + toolCall: { + type: "toolCall", + id, + name: "extract_document", + arguments: { url: "https://example.test/doc.pdf" }, + }, + partial: assistant, + } satisfies AssistantMessageEvent; + } + yield { + type: "done", + reason: "toolUse", + message: assistant, + } satisfies AssistantMessageEvent; + return; + } + + const assistant = assistantMessage( + [{ type: "text", text: "documents complete" }], + "stop", + ); + yield { + type: "start", + partial: assistant, + } satisfies AssistantMessageEvent; + yield { + type: "done", + reason: "stop", + message: assistant, + } satisfies AssistantMessageEvent; + }); + + const userMessage: Message = { + role: "user", + content: "Extract the same remote document twice.", + timestamp: Date.now(), + }; + const transport = new ProviderTransport({ + maxConcurrentToolExecutions: 4, + platformToolExecutionBridge: false, + }); + + const events = await drain( + transport.run([userMessage], userMessage, { + systemPrompt: "Use the requested tools.", + tools: [extractDocumentTool], + model, + }), + ); + + const toolResultsById = new Map( + events + .filter( + ( + event, + ): event is Extract => + event.type === "tool_execution_end", + ) + .map((event) => [event.toolCallId, event]), + ); + + expect(extractExecutionCount).toBe(2); + expect(toolResultsById.get("extract-1")?.scheduling?.cache).toBe( + "disabled", + ); + expect(toolResultsById.get("extract-2")?.scheduling?.cache).toBe( + "disabled", + ); + }); + it("does not reuse diff results with a custom cwd across adjacent user turns", async () => { let diffExecutionCount = 0; const diffTool: AgentTool = { diff --git a/test/platform/a2a-platform-live-evidence-verify.test.ts b/test/platform/a2a-platform-live-evidence-verify.test.ts index 5ed4e0464..288f807a9 100644 --- a/test/platform/a2a-platform-live-evidence-verify.test.ts +++ b/test/platform/a2a-platform-live-evidence-verify.test.ts @@ -342,6 +342,67 @@ describe("Platform A2A live evidence verifier", () => { } }); + it("rejects non-HTTPS GitHub server URLs before dereferencing", async () => { + const dir = await mkdtemp(join(tmpdir(), "maestro-a2a-evidence-")); + const paths: string[] = []; + try { + const path = await writeEvidenceBundle( + dir, + evidence({ + github: { + repository: "evalops/maestro-internal", + serverUrl: "http://github.example.com", + runId: "26252628231", + runUrl: + "http://github.example.com/evalops/maestro-internal/actions/runs/26252628231", + sha: "1234567890abcdef1234567890abcdef12345678", + pullRequestNumber: 2070, + pullRequestUrl: + "http://github.example.com/evalops/maestro-internal/pull/2070", + }, + }), + ); + await expect( + verifyPlatformA2ALiveEvidenceFile(path, { + requireDereferenceableGithub: true, + githubApiClient: async (apiPath) => { + paths.push(apiPath); + throw new Error("GitHub API client should not be called"); + }, + }), + ).rejects.toThrow(/server URL must use HTTPS/); + expect(paths).toEqual([]); + } finally { + await rm(dir, { force: true, recursive: true }); + } + }); + + it("rejects GitHub run URLs that do not match the run id", async () => { + const dir = await mkdtemp(join(tmpdir(), "maestro-a2a-evidence-")); + try { + const path = await writeEvidenceBundle( + dir, + evidence({ + github: { + repository: "evalops/maestro-internal", + runId: "26252628231", + runUrl: + "https://github.com/evalops/maestro-internal/actions/runs/26252628232", + sha: "1234567890abcdef1234567890abcdef12345678", + pullRequestNumber: 2070, + pullRequestUrl: + "https://github.com/evalops/maestro-internal/pull/2070", + }, + }), + ); + await expect(verifyPlatformA2ALiveEvidenceFile(path)).rejects.toThrow( + /run URL id 26252628232 does not match runId 26252628231/, + ); + } finally { + await rm(dir, { force: true, recursive: true }); + } + }); + it("accepts invalid-token rejection evidence when required", async () => { const dir = await mkdtemp(join(tmpdir(), "maestro-a2a-evidence-")); try { diff --git a/test/scripts/ci-guardrails.test.ts b/test/scripts/ci-guardrails.test.ts index 45b4d2b0b..dd173ce5d 100644 --- a/test/scripts/ci-guardrails.test.ts +++ b/test/scripts/ci-guardrails.test.ts @@ -12,7 +12,10 @@ import { summarizeChecks, } from "../../scripts/maestro-merge-queue-status.mjs"; import { planCiChecks } from "../../scripts/plan-ci-checks.mjs"; -import { planNxTestCommand } from "../../scripts/plan-nx-test-command.mjs"; +import { + packageManifestReleaseMetadataOnlyChanged, + planNxTestCommand, +} from "../../scripts/plan-nx-test-command.mjs"; import { collectFeedbackAuditTargets, parseFeedbackAuditArgs, @@ -193,6 +196,37 @@ describe("planCiChecks", () => { ).toBe(true); }); + it("skips coverage for runtime package metadata and test-only changes", () => { + expect( + planCiChecks({ + eventName: "pull_request", + changedFiles: [ + ".github/workflows/ci.yml", + "CHANGELOG.md", + "openapi.json", + "package.json", + "packages/contracts/package.json", + "packages/slack-agent/test/tools-status.test.ts", + "scripts/bundle-runtime-deps.mjs", + "scripts/check-docker-runtime-workspaces.mjs", + "scripts/check-packed-bundled-workspaces.mjs", + "scripts/check-runtime-deps.js", + "scripts/ci-nx-tests.sh", + "scripts/plan-nx-test-command.mjs", + "scripts/runtime-workspaces.mjs", + "scripts/validate-public-package-deps.js", + "test/scripts/ci-guardrails.test.ts", + ], + }), + ).toMatchObject({ + ciInfrastructureOnly: false, + coverage: false, + prChecks: true, + publicMirror: true, + rustHostedConformance: true, + }); + }); + it("runs public mirror checks for mirror config inputs", () => { expect( planCiChecks({ @@ -240,6 +274,37 @@ describe("planCiChecks", () => { }); describe("ci workflow guardrails", () => { + it("runs shell CI guardrails for workflow file changes", () => { + const script = readFileSync( + new URL("../../scripts/ci-nx-tests.sh", import.meta.url), + { encoding: "utf8" }, + ); + const triggerPattern = script.match( + /run_ci_guardrail_tests\(\) \{[\s\S]*?changed_files_match '([^']+)'/, + )?.[1]; + + expect(triggerPattern).toBeDefined(); + const regex = new RegExp(triggerPattern ?? ""); + expect(regex.test(".github/workflows/ci.yml")).toBe(true); + expect(regex.test("scripts/ci-nx-tests.sh")).toBe(true); + }); + + it("builds dist before the runtime dependency validator", () => { + const script = readFileSync( + new URL("../../scripts/ci-nx-tests.sh", import.meta.url), + { encoding: "utf8" }, + ); + const runtimeValidatorBody = + script.match( + /run_runtime_package_validators\(\) \{([\s\S]*?)\n\}/, + )?.[1] ?? ""; + + expect(runtimeValidatorBody).not.toBe(""); + expect(runtimeValidatorBody.indexOf("npm run build")).toBeLessThan( + runtimeValidatorBody.indexOf("node scripts/check-runtime-deps.js"), + ); + }); + it("hard-bounds long-running Nx and coverage phases", () => { const workflow = parse( readFileSync(new URL("../../.github/workflows/ci.yml", import.meta.url), { @@ -259,7 +324,7 @@ describe("ci workflow guardrails", () => { ]), ); - expect(prCheckTimeouts.get("Test (Nx affected)")).toBe(45); + expect(prCheckTimeouts.get("Test (Nx affected)")).toBe(60); expect(workflow.jobs?.coverage?.["timeout-minutes"]).toBe(75); expect(coverageTimeouts.get("Run tests with coverage")).toBe(60); }); @@ -625,6 +690,47 @@ describe("planNxTestCommand", () => { }); }); + it("filters release metadata package manifests from affected files", () => { + expect( + planNxTestCommand({ + basePackage, + changedFiles: [ + ".github/workflows/ci.yml", + "CHANGELOG.md", + "openapi.json", + "package.json", + "packages/contracts/package.json", + "packages/slack-agent/test/tools-status.test.ts", + "scripts/ci-nx-tests.sh", + "scripts/check-runtime-deps.js", + "scripts/plan-nx-test-command.mjs", + "scripts/runtime-workspaces.mjs", + "test/scripts/ci-guardrails.test.ts", + ], + handledOutsideNxFiles: [ + ".github/workflows/ci.yml", + "scripts/ci-nx-tests.sh", + "scripts/check-runtime-deps.js", + "scripts/plan-nx-test-command.mjs", + "scripts/runtime-workspaces.mjs", + "test/scripts/ci-guardrails.test.ts", + ], + headPackage: { + ...basePackage, + version: "1.0.1", + }, + packageJsonMetadataOnlyFiles: [ + "package.json", + "packages/contracts/package.json", + ], + releaseMetadataOnlyFiles: ["CHANGELOG.md", "openapi.json"], + }), + ).toEqual({ + files: ["packages/slack-agent/test/tools-status.test.ts"], + mode: "affected-files", + }); + }); + it("skips Nx when package scripts are the only changed files", () => { expect( planNxTestCommand({ @@ -641,6 +747,46 @@ describe("planNxTestCommand", () => { }), ).toEqual({ files: [], mode: "none" }); }); + + it("treats runtime workspace package metadata as release metadata", () => { + expect( + packageManifestReleaseMetadataOnlyChanged({ + allowedRootDependencyNames: ["@bufbuild/protobuf"], + basePackage: { + ...basePackage, + bundleDependencies: ["@evalops/contracts"], + version: "1.0.0", + }, + headPackage: { + ...basePackage, + dependencies: { + ...basePackage.dependencies, + "@bufbuild/protobuf": "^2.11.0", + }, + maestroRuntimeWorkspaces: ["@evalops/contracts"], + version: "1.0.1", + }, + isRootPackage: true, + }), + ).toBe(true); + }); + + it("keeps non-runtime root dependency additions on the full matrix", () => { + expect( + packageManifestReleaseMetadataOnlyChanged({ + allowedRootDependencyNames: ["@bufbuild/protobuf"], + basePackage, + headPackage: { + ...basePackage, + dependencies: { + ...basePackage.dependencies, + "left-pad": "^1.3.0", + }, + }, + isRootPackage: true, + }), + ).toBe(false); + }); }); describe("public mirror ref resolution", () => { diff --git a/test/telemetry/cli-command-aggregator.test.ts b/test/telemetry/cli-command-aggregator.test.ts index 98a92d949..66f11f606 100644 --- a/test/telemetry/cli-command-aggregator.test.ts +++ b/test/telemetry/cli-command-aggregator.test.ts @@ -81,12 +81,14 @@ describe("CLI command telemetry aggregator", () => { clientVersion: "0.10.18", bufferMs: 10_000, bufferFile, + lockTimeoutMs: 0, now: () => now, }); const second = new CliCommandAggregator({ clientVersion: "0.10.18", bufferMs: 10_000, bufferFile, + lockTimeoutMs: 0, now: () => now, }); From 6d4dfee699dbabeaa3d455acc20ec504d9aaf7a1 Mon Sep 17 00:00:00 2001 From: Jonathan Haas Date: Fri, 22 May 2026 16:32:24 -0700 Subject: [PATCH 2/3] test: allow public nx timeout bound --- test/scripts/ci-guardrails.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/scripts/ci-guardrails.test.ts b/test/scripts/ci-guardrails.test.ts index dd173ce5d..63d9926bd 100644 --- a/test/scripts/ci-guardrails.test.ts +++ b/test/scripts/ci-guardrails.test.ts @@ -324,7 +324,9 @@ describe("ci workflow guardrails", () => { ]), ); - expect(prCheckTimeouts.get("Test (Nx affected)")).toBe(60); + const nxTimeout = prCheckTimeouts.get("Test (Nx affected)"); + expect(nxTimeout).toBeGreaterThanOrEqual(45); + expect(nxTimeout).toBeLessThanOrEqual(60); expect(workflow.jobs?.coverage?.["timeout-minutes"]).toBe(75); expect(coverageTimeouts.get("Run tests with coverage")).toBe(60); }); From 73f2277362c9f72cfc95a22d7ab45c90a5539f16 Mon Sep 17 00:00:00 2001 From: Jonathan Haas Date: Fri, 22 May 2026 16:34:20 -0700 Subject: [PATCH 3/3] ci: match public guardrail timeout --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 53b9286b3..24800da14 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,7 +37,7 @@ jobs: java-version: "21" - name: Test (Nx affected) - timeout-minutes: 45 + timeout-minutes: 60 env: NX_BASE: ${{ github.event.pull_request.base.sha || 'HEAD~1' }} NX_HEAD: ${{ github.event.pull_request.head.sha || 'HEAD' }}