Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e06a47fac5 |
@@ -0,0 +1,186 @@
|
||||
# Quality-Rails Probe Inventory — RI-3-001
|
||||
|
||||
- **Task:** RI-3-001 (SDLC-D-037 first half; PRD § Release Integrity Workstream, RI-N4)
|
||||
- **Date:** 2026-08-18
|
||||
- **Base:** `origin/next` @ `8199261c` (branch `docs/ri-050-qr-probe-inventory`)
|
||||
- **Follow-up:** RI-3-002 consumes the dispositions here when building the single TS evaluator.
|
||||
|
||||
## 0. Scope and method
|
||||
|
||||
Every mechanism in this repository that verifies a quality, integrity, safety, or release
|
||||
property — TypeScript checks, shell probes, pipeline steps, git hooks, and installer-side
|
||||
assertions — gets one row. Each row's "what it actually verifies" was written from the
|
||||
probe's **code**, not its name or docs. Framework tool unit/regression suites (git wrappers,
|
||||
wake, tmux, orchestrator, …) are treated as one enforcement surface (`test:framework-shell`)
|
||||
because they test tool behavior rather than repo quality; their wiring integrity is itself
|
||||
guarded by `check-test-enumeration.sh`, and the quality-relevant members are rowed
|
||||
individually.
|
||||
|
||||
**Kinds:** `ts` (TypeScript/Node check), `shell` (bash/python probe), `pipeline-step`
|
||||
(exists only inside a Woodpecker pipeline).
|
||||
|
||||
**Enforcement points:** `local` (operator-invoked), `pre-commit`, `pre-push`,
|
||||
`CI ci.yml#<step>`, `publish.yml#<step>` (CI on push to main/next), `turbo <task>`,
|
||||
`agent-runtime` (framework hooks on an agent host), `installer` (host install path),
|
||||
`unwired`.
|
||||
|
||||
**Dispositions** (recommendations for RI-3-002): `preserve` (keep as-is; already the
|
||||
canonical or a correct guard-of-the-guard), `strengthen` (keep, but a concrete gap must
|
||||
close — usually absorption into the TS evaluator), `strengthen (review)` (viable retirement
|
||||
candidate once the evaluator absorbs it; do not retire yet). Note: RI-N4 requires that
|
||||
effective shell probes be **absorbed before** their independent paths retire — no row here
|
||||
is marked `retire` because no absorption exists yet.
|
||||
|
||||
## 1. Inventory
|
||||
|
||||
### 1.1 Repo-level gate tasks (pnpm / turbo)
|
||||
|
||||
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||
| ------------------------------------- | ------------------------------------------------------------------------------------ | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `pnpm preflight` (checkout preflight) | `scripts/preflight.mjs` | ts | Six gate binaries (eslint, husky, prettier, tsc, turbo, vitest) exist and are executable in `node_modules/.bin` (exit 42 if not); no stale `.mosaic-test-work/web-build.lock` (exit 43); `apps/web/.next` is a real directory (not a symlink), every entry owned by the current uid, and its `.mosaic-source-hash` fingerprint + `.mosaic-symlink-manifest` hash match the certified build written by `scripts/build-web.mjs` | `pre-push`; inside `pnpm typecheck` (→ `CI ci.yml#typecheck`, verify-release `typecheck` stage) | QC-1 Checkout integrity | preserve | Blocks a poisoned/stale generated `.next` from faking a green typecheck (the five-month-stale-`.next` class); trust chain is self-contained per-checkout. |
|
||||
| `pnpm typecheck` | root `package.json` → `turbo run typecheck` | ts | Per-package `tsc --noEmit` (all 20 packages); turbo `typecheck` depends on `^build`, so package builds must succeed first; prefixed by checkout preflight | `CI ci.yml#typecheck`; `pre-push`; verify-release `typecheck` stage; `turbo typecheck` | QC-2 Workspace typecheck | preserve | The single workspace-wide type gate; CI and hooks invoke the same task, no divergent checklist. |
|
||||
| `pnpm lint` | root `package.json` → `turbo run lint` | ts | Per-package `eslint src` under root `eslint.config.mjs` (ignores `dist`, `.next`, `framework/**`, etc.) | `CI ci.yml#lint`; `pre-push`; verify-release `lint` stage; `turbo lint` | QC-3 Workspace lint | preserve | Same-task invocation from every surface; no second lint definition. |
|
||||
| `pnpm format:check` | root `package.json` → `prettier --check` | ts | Prettier parse/format equality over `**/*.{ts,tsx,js,jsx,json,md}` minus `.prettierignore` (generated trees, `docs/scratchpads/`, venvs, …) | `CI ci.yml#format`; `pre-push`; verify-release `format` stage | QC-4 Format check | preserve | Single formatter, single ignore list, enforced identically everywhere. |
|
||||
| `pnpm test` | root `package.json` `test` = `test:checkout` && `turbo run test` && `test:installer` | ts | (a) `node --test scripts/*.test.mjs` — checkout-tool units; (b) per-package `vitest run` (mosaic appends the 47-command `test:framework-shell` chain); (c) `tools/install-next-lane.test.sh`; turbo `test` declares DB env vars and depends on `^build` | `CI ci.yml#test` (with `DATABASE_URL` + `db:migrate` first); verify-release `test` stage; `turbo test` | QC-5 Test suite execution | preserve | One composed test command; the chain property (any link red ⇒ step red) is the gate. |
|
||||
| `pnpm build` | root `package.json` → `turbo run build` | ts | Per-package build (`tsc`/Next) with `^build` dependency and `dist/**` outputs | `publish.yml#build`; verify-release `build` stage; `turbo build` | QC-6 Workspace build | preserve | Publish artifacts derive from the same build task CI verifies. |
|
||||
|
||||
### 1.2 Framework quality shell probes (`packages/mosaic/framework/tools/quality/`)
|
||||
|
||||
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||
| ------------------------------------------- | ----------------------------------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
||||
| Sanitization gate | `scripts/verify-sanitized.sh` | shell | Built-in self-test first (planted identity/structural/YAML+service fixtures; exit 2 if the regexes or extension coverage break), then: (1) identity denylist grep (`jarvis\|jason\|woltje\|brain.woltje.com\|/home/jwoltje\|\bPDA\b`) over all shipped text files **including** `examples/`; (2) structural grep for private `$HOME/src` defaults in shipped scripts **excluding** `examples/`. Any hit ⇒ exit 1 | `CI ci.yml#sanitization`; verify-release `sanitization` stage | QC-7 Framework sanitization | preserve | Labeled one-time regression guard with a self-test that prevents silent no-op; correctly scoped (identity vs structural) and documented as not a general PII detector. |
|
||||
| Resident-context budget | `scripts/check-resident-budget.sh` (+ `--self-test`) | shell | Self-test of the comparator, then `wc -l` vs per-file ceilings (CONSTITUTION 120, AGENTS 120, each RUNTIME.md 90); missing file ⇒ fail; over ceiling ⇒ exit 1 | `CI ci.yml#sanitization` (both modes); verify-release `sanitization` stage | QC-8 Resident-context budget | preserve | Caps the container (lines), never the wording — the deliberate anti-drift design (DESIGN §7); CI-enforceable half only, by design. |
|
||||
| Test-membership enumeration guard (#1017) | `scripts/check-test-enumeration.sh` + `test-enumeration-exclusions.txt` | shell | Parses surface S1 (`packages/mosaic` `test:framework-shell` via JSON+shlex) and S2 (every `framework/tools/\*.sh | .py`token in`ci.yml`, comment lines stripped); population = `_test_.sh`under`framework/tools`; FAILS on: suite-shaped file on disk neither enumerated nor signed-excluded; surface naming a path missing on disk (both directions); exclusion without reason / stale / outside population / contradicting enumeration. Proves **naming, not reachability** (stated in-file) | `CI ci.yml#sanitization` (direct line); link [0] of `test:framework-shell` (thus `CI ci.yml#test`); verify-release `sanitization` stage | QC-9 Test-membership enumeration | preserve | Makes silent under-run impossible; invoked from both surfaces it audits so severing the chain cannot silence it. |
|
||||
| Enumeration-guard needles | `scripts/test-check-test-enumeration.sh` | shell | Needle/control fixtures driven through `--root`: every promised failure mode must trip the guard **on its own words**, plus controls that must pass (null-case defense); covers commented-out ci.yml lines (F1) and line-range parsing (n2b) | `test:framework-shell` → `CI ci.yml#test`; verify-release `test` stage | QC-9 Test-membership enumeration | preserve | Guard-of-the-guard with both polarities; same canonical check by design. |
|
||||
| Upgrade manifest guard (#791 HARD GATE) | `scripts/test-upgrade-manifest-guard.sh` | shell | Keep-mode `install.sh` upgrade against seeded throwaway `MOSAIC_HOME`: every operator sentinel — including an **unanticipated** one — survives byte-identical with unchanged mtime; framework files still update; retired framework files pruned; matrix run with rsync present AND absent (keep path must be rsync-independent); fail-closed matrix (empty/operator-only/malformed/missing manifest aborts loudly, operator files untouched); operator secret never appears in installer output | `CI ci.yml#upgrade-guard`; verify-release `upgrade-guard` stage | QC-10 Upgrade/install safety | preserve | The operator-data hard gate for the `mosaic update` path; negative controls are load-bearing and documented. |
|
||||
| Upgrade rollback gate (#791 B1) | `scripts/test-upgrade-rollback.sh` | shell | Mid-sync failure (PATH-shadowing `cp` shim) must trigger snapshot restore: restore message fires, corrupted file restored, target byte-identical to pre-upgrade; control installer with `set -E` stripped must NOT roll back (proves errtrace is load-bearing); plus signal/exit-guard controls | `CI ci.yml#upgrade-guard`; verify-release `upgrade-guard` stage | QC-10 Upgrade/install safety | preserve | Proves the rollback trap actually fires; the `-E`-stripped control keeps Part A honest. |
|
||||
| Durable-snapshot gate (#791 PR2) | `scripts/test-upgrade-durable-snapshot.sh` | shell | Pre-update snapshot taken before any mutation (0700/0600 perms, secret never logged, retention-pruned); post-sync verify net restores operator files a manifest bug lets the sync touch; CWE-59 symlink-leaf guard proven with a portable cp shim in both polarities (write-through-link must not happen); v1→v2 migration semantics (intended `bin/` removal not healed) | `CI ci.yml#upgrade-guard`; verify-release `upgrade-guard` stage | QC-10 Upgrade/install safety | preserve | Covers tampering and leak vectors the manifest guard cannot see; the shim rationale (busybox vs GNU cp) is documented in-file. |
|
||||
| Install migration matrix (v2→v3) | `scripts/test-install-migration.sh` | shell | Fixture matrix running the real installer with `MOSAIC_SYNC_ONLY=1`: fresh install seeds + stamps version 3; legacy user-edited AGENTS overwritten with `.pre-constitution.bak` preserved (and idempotent); tuned STANDARDS overwritten; operator files (SOUL, credentials) preserved. Mirrors the TS suite `packages/mosaic/src/config/file-adapter.test.ts` — both installers must behave identically | `CI ci.yml#upgrade-guard`; verify-release `upgrade-guard` stage | QC-10 Upgrade/install safety | preserve | Pins the shell/TS installer parity contract; removal would orphan that parity requirement. |
|
||||
| Enforcement verification probe (bash) | `scripts/verify.sh` | shell | Attempts **real commits** in the target repo: planted type error must produce a commit blocked with `error`; planted `any` must trip `no-explicit-any`; planted lint error must trip `prettier`; gitleaks binary must exist (3a) and detect a planted AWS key via `gitleaks git --pre-commit --staged --redact` (3b). Verdicts are output-grep matches on hook stderr | `local` via installed `mosaic-quality-verify` on scaffolded target projects; **not run in this repo's CI** | QC-20 Downstream enforcement verification | strengthen (review) | Mechanism is genuinely behavioral (stronger than file presence) but verdict logic is grep-on-output and it is unwired here; absorb as the evaluator's enforcement-probe check (the RI-N4 evaluator invokes it or reimplements it) before retiring the shell path. |
|
||||
| Enforcement verification probe (PowerShell) | `scripts/verify.ps1` | shell | Windows port of `verify.sh`: same planted-commit tests with `$output -match` matching; no gitleaks self-test parity beyond the same checks | `local` (Windows operator); no Windows CI runner exists | QC-20 Downstream enforcement verification | strengthen (review) | A hand-maintained twin of `verify.sh` with no CI coverage — exactly the drift shape the single evaluator removes; retire after the TS evaluator owns the probe. |
|
||||
| Quality template installer (bash) | `scripts/install.sh` | shell | Copies template files (`.husky/pre-commit` incl. mandatory gitleaks, `.lintstagedrc.js`, `.eslintrc.js`, `tsconfig.json`, `.woodpecker.yml`, `.gitleaks.toml`) into a target project; **warns** (does not verify) about `package.json` snippet merge; no post-condition check | `local` / via `mosaic-quality-apply` | QC-21 Downstream rails scaffolding | strengthen (review) | Duplicates the TS `quality-rails init` scaffolder for a different template set; converging on one scaffolder (with post-scaffold verification) is prerequisite to retiring this path. |
|
||||
| Quality template installer (PowerShell) | `scripts/install.ps1` | shell | Windows twin of the template copy above | `local` (Windows operator) | QC-21 Downstream rails scaffolding | strengthen (review) | Same twin-drift risk as `verify.ps1`; no runner exercises it. |
|
||||
| `mosaic-quality-verify` adapter | `framework/tools/_scripts/mosaic-quality-verify` | shell | Thin adapter: validates target dir exists, asserts `verify.sh` present+executable, `cd` target, exec it. No verdict logic of its own | `local` (installed framework bin) | QC-20 Downstream enforcement verification | preserve | Already the thin-adapter shape RI-N4 prescribes for shell surfaces. |
|
||||
| `mosaic-quality-apply` adapter | `framework/tools/_scripts/mosaic-quality-apply` | shell | Thin adapter: arg validation then exec of quality `install.sh --template … --target …` | `local` (installed framework bin) | QC-21 Downstream rails scaffolding | preserve | Thin adapter, no separate verdict; disposition follows its target script's convergence. |
|
||||
| Roster schema regression | `scripts/test-roster-schema.py` | shell | jsonschema `Draft202012Validator` over `fleet/roster.schema.json` with valid/invalid connector-kind fixtures (tmux/discord/matrix conditional fields) | **unwired** — not on S1 or S2, not signed-excluded; also outside the enumeration guard's `*.sh` population, so the guard cannot see it | QC-5 Test suite execution | strengthen (review) | A real regression suite that currently runs nowhere; wire it into a CI surface or sign an exclusion — leaving it invisible re-arms the exact gap #1017 closed. |
|
||||
| Framework shell chain (S1) | `packages/mosaic/package.json` `test:framework-shell` | shell | 47-command `&&` chain: enumeration guard + needles, 14 lease-broker/mutator-gate python unitests, `check-runtime-launches.py`, and ~30 framework-tool shell suites (git wrappers, wake, woodpecker, tmux, glpi, orchestrator, `_scripts`). Quality-relevant members rowed separately below | `turbo test` → `CI ci.yml#test`; verify-release `test` stage | QC-5 Test suite execution | preserve | The chain is the execution surface the enumeration guard audits; known residuals: a failing link stops later suites (measured in #1270 — suites after position 44 had not run), and the guard proves naming, not reachability. |
|
||||
|
||||
### 1.3 Framework runtime hooks and their harnesses (agent-host enforcement)
|
||||
|
||||
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||
| ------------------------------------- | ----------------------------------------------------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | --------------------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| QA edit hook seam | `framework/tools/qa/qa-hook-stdin.sh` (+ `qa-hook-handler.sh`) | shell | PostToolUse stdin hook: extracts edited file from the tool JSON (jq or grep fallback), skips non-JS/TS, then the deps-preflight gate — exits 1 with the legible sentinel `deps not installed — run pnpm install` when `node_modules/.bin` is missing/empty (the #856 false-red class); the downstream handler only files QA remediation **report templates** (no verification logic) | `agent-runtime` (framework `runtime/claude/settings.json` PostToolUse); never CI | QC-16 Agent-runtime edit-time checks | strengthen (review) | The sentinel gate is real enforcement; the handler's report-filing adds no verdict and its name promises more than the code does — evaluator absorption should keep the sentinel, drop the report theater. |
|
||||
| Typecheck-on-edit hook | `framework/tools/qa/typecheck-hook.sh` | shell | PostToolUse: for edited `.ts/.tsx`, finds nearest `tsconfig.json` and runs `tsc --noEmit`, surfacing errors nonzero to the agent immediately | `agent-runtime` (framework `runtime/claude/settings.json` PostToolUse) | QC-16 Agent-runtime edit-time checks | strengthen (review) | Edit-time duplicate of QC-2 with independent invocation logic; keep behavior, converge invocation through the evaluator adapter. |
|
||||
| Deps-preflight harness | `framework/tools/qa/test-deps-preflight.sh` | shell | Five assertions against the seam incl. a documented RED control (raw `not found`), sentinel behavior for missing and empty `.bin`, and no-false-positive once populated | `test:framework-shell` → `CI ci.yml#test` | QC-16 Agent-runtime edit-time checks | preserve | Guard-of-the-check with a red control; keeps the sentinel from regressing. |
|
||||
| Prompt-helper RCE regression | `framework/tools/_scripts/test-mosaic-init-rce.sh` | shell | Sources the prompt helpers and proves a literal `$(touch /tmp/pwned)` answer round-trips verbatim and never executes (no `/tmp/pwned` created) | `test:framework-shell` → `CI ci.yml#test` | QC-5 Test suite execution | preserve | Cheap, load-bearing security regression on the installer's input path. |
|
||||
| Install-ordering harness (#869 C2) | `framework/tools/_scripts/test-install-ordering-guard.sh` | shell | Drives `mosaic-link-runtime-assets` with a fake `mosaic` on PATH: probe ok ⇒ settings copied + exit 0; probe fail ⇒ exit 1 with degraded outcome but all other runtime files still copied; `--allow-inactive-enforcement` forwarded; no-mosaic-on-PATH ⇒ python3 fallback strips enforcement hooks and exits 1; fallback + flag ⇒ wires as-is, exit 0 | `test:framework-shell` → `CI ci.yml#test` | QC-17 Lease-enforcement wiring safety | preserve | Exercises the shell wiring seam independently of the TS guard's own spec suite (complementary coverage, by design). |
|
||||
| Fleet-transport harness (#1240) | `framework/tools/_scripts/test-fleet-transport-check.sh` | shell | Extracts the shipped `check_fleet_transport`/`fleet_declared_transport` functions **from the shipped scripts** (fails loud if extraction yields nothing) and drives both implementations (mosaic-doctor + `tools/install.sh`) from one case table | `test:framework-shell` → `CI ci.yml#test` | QC-18 Operator-host drift audit | preserve | The anti-drift harness for the one rule shipped twice; extraction-from-source keeps it from testing a stale copy. |
|
||||
| Terminal-green contract (RM-61/#1000) | `framework/tools/woodpecker/test-terminal-green-contract.sh` + `verify-terminal-green.py` | shell | Red-first fixtures: pipeline JSON variants (service failure, step failure, cancelled, etc.) must produce the correct terminal-green verdict; controls must pass | `test:framework-shell` → `CI ci.yml#test` | QC-5 Test suite execution | preserve | Keeps the CI-wait wrapper's green-detection honest; a false green here would poison every merge gate that trusts `pr-ci-wait.sh`. |
|
||||
| Lease-gate launch invariant | `framework/tools/lease-broker/check-runtime-launches.py` | shell | Scans production roots (`packages/`, `apps/`, `plugins/`, `tools/`) across sh/py/ts/yaml suffixes for Claude/Pi process launches **outside** the lease gate; allowlist-based; fails CI on violation | `test:framework-shell` → `CI ci.yml#test` | QC-15 Lease-gate architecture invariant | preserve | The only architectural "no ungated launches" rail; grep+allowlist is the right cost/benefit for this invariant. |
|
||||
|
||||
### 1.4 TypeScript quality logic (`@mosaicstack/quality-rails` + mosaic CLI)
|
||||
|
||||
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||
| ---------------------------------------- | ---------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- | ------------------------------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `quality-rails check` | `packages/quality-rails/src/cli.ts` (`mosaic quality-rails check --project`) | ts | **Expected-file presence only**: loops `expectedFilesForKind` (node: `.eslintrc`, `biome.json`, `.githooks/pre-commit`, `PR-CHECKLIST.md`; python: `pyproject.toml`+hooks+checklist; rust: `rustfmt.toml`+…) and exits 1 listing missing paths. Does not execute any linter, formatter, hook, or scanner | `local` (operator CLI); **no CI wiring in this repo** | QC-19 Downstream rails presence check | strengthen | This is the RI-N4 evaluator seed. Today presence ≠ parity (explicitly called out by RI-N4): it must grow typed verdicts (`passed/failed/blocked/error/not-applicable`), check versioning/subject/reason, digested definitions, and absorb the effective shell probes (QC-20 first). |
|
||||
| `quality-rails doctor` | `packages/quality-rails/src/cli.ts` | ts | Same presence data as `check`, printed with ok/missing lines; **cannot fail** (no nonzero exit on missing files) | `local` (operator CLI) | QC-19 Downstream rails presence check | strengthen | A doctor that cannot fail is advisory; fold into `check` (or return typed states) when the evaluator lands. |
|
||||
| `quality-rails init` | `packages/quality-rails/src/cli.ts` + `scaffolder.ts`/`templates.ts` | ts | Scaffolds rails files per detected kind/profile (linters/formatters lists are advisory strings; hooks flag always true); writes files, prints follow-ups — no post-condition verification | `local` (operator CLI) | QC-21 Downstream rails scaffolding | strengthen (review) | Second scaffolding path alongside quality `install.sh` (§1.2); converge on one with post-scaffold verification before retiring either. |
|
||||
| Lease activation probe (#869 C1, hidden) | `packages/mosaic/src/commands/lease-activation-probe.ts` | ts | Real capability probe, not file presence: resolves the installed mosaic CLI and requires it to advertise the exact `{name, version}` activation contract; all deps injectable; registered as hidden CLI command and consumed by C2/C5 | `local` (hidden CLI + consumed by C2/C5); spec-tested via `lease-activation-probe.spec.ts` in `turbo test` | QC-17 Lease-enforcement wiring safety | preserve | The versioned-contract probe is precisely the fail-closed capability check RI-N2 generalizes; already typed and injectable. |
|
||||
| Install-ordering guard (#869 C2, hidden) | `packages/mosaic/src/commands/install-ordering-guard.ts` | ts | Decides whether enforcement hook entries are written into the `~/.claude/settings.json` the framework reseed ships: not activatable ⇒ strip hooks + nonzero loud outcome (default); explicit per-invocation `--allow-inactive-enforcement` opt-out wires-with-warning. Never touches the runtime gate's own fail-closed behavior | `installer` (framework reseed via `mosaic-link-runtime-assets`); spec + shell harness coverage in `turbo test` | QC-17 Lease-enforcement wiring safety | preserve | Correct default-deny with an explicit, non-env opt-out; test-locked from both the TS and shell sides. |
|
||||
| Lease doctor check (#869 C5) | `packages/mosaic/src/commands/lease-doctor-check.ts` | ts | Combines hook-wiring detection in `~/.claude/settings.json` with C1 activatable and C3 broker-supervisor health: wired ∧ (¬activatable ∨ ¬healthy) ⇒ loud `[ERROR]` that forces `mosaic doctor` exit 1 regardless of the bash audit's own exit | `local` (inside `mosaic doctor`); spec coverage in `turbo test` | QC-17 Lease-enforcement wiring safety | preserve | Closes the "bricked host looks green" hole; cannot be masked by the bash script — that composition is the point. |
|
||||
| `mosaic doctor` (framework drift audit) | `packages/mosaic/src/commands/launch.ts` (`doctor`) + `framework/tools/_scripts/mosaic-doctor` | shell+ts | Bash audit of the installed framework home: ~40 expected files/dirs present; runtime files are copies (not symlinks) matching source (`cmp`) or composed runtime-contract markers; hard-gates block present in AGENTS.md; sequential-thinking MCP configured; fleet transport binary present per roster (warn); legacy symlink trees gone; skills synced — **warn-based, exit 1 only with `--fail-on-warn`**, plus C5's forced error | `local` (operator audit) | QC-18 Operator-host drift audit | preserve | Host-state audit CI cannot see (user files by design, DESIGN §7); advisory exit is the documented contract — do not silently change it. |
|
||||
| `mosaic gateway doctor` | `packages/mosaic/src/commands/gateway-doctor.ts` | ts | Probes per-service health (PostgreSQL, Valkey, pgvector) via `@mosaicstack/storage`, reports tier and JSON; exit 1 only when at least one **required** service fails (yellow stays 0) | `local` (operator) | QC-18 Operator-host drift audit | preserve | Service health with correct red/yellow exit semantics; JSON mode exists for scripting. |
|
||||
| `mosaic gateway verify` | `packages/mosaic/src/commands/gateway/verify.ts` | ts | Post-install liveness: daemon meta via HTTP with retries, admin token on file, bootstrap endpoint reachable; aggregated pass/fail | `local`; consumed by `tools/e2e-install-test.sh` | QC-18 Operator-host drift audit | preserve | The first-run proof the installer E2E relies on; retry-aware so startup races don't false-red. |
|
||||
| `mosaic fleet doctor` | `packages/mosaic/src/commands/fleet-reconciler-command.ts` | ts | Classifies local roster-owned drift (no mutation) from the parsed v2 roster | `local` (operator) | QC-18 Operator-host drift audit | preserve | Dry-run classification is the correct non-mutating audit shape. |
|
||||
|
||||
### 1.5 Git hooks (developer machine)
|
||||
|
||||
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||
| ------------------------- | --------------------------------------------------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| Pre-commit staged hygiene | `.husky/pre-commit` → `npx lint-staged` (`.lintstagedrc`) | shell | On staged files only: `prettier --write` + `eslint --fix` for ts/tsx/js/jsx; `prettier --write` for json/md/yaml/yml. **Mutating** (fixes and re-stages); commit blocks only if a fixer itself fails | `pre-commit` (every local commit; hooks activated by `install-hooks.mjs` via `core.hooksPath .husky/_`) | QC-13 Staged-change hygiene | preserve | Correct scoped fast gate; note it auto-fixes rather than rejects (deliberate). Gap: no secret scan here — see §3. |
|
||||
| Pre-push gate | `.husky/pre-push` | shell | `pnpm preflight && pnpm typecheck && pnpm lint && pnpm format:check` (no test run — documented in AGENTS.md) | `pre-push` | QC-14 Pre-push gate | preserve | Composes QC-1..4 exactly as specified in AGENTS.md; tests intentionally left to CI. |
|
||||
| Hook installer | `scripts/install-hooks.mjs` (`pnpm prepare`) | ts | Stages husky hooks into a scratch repo first, asserts husky produced its `h` shim, quarantines incomplete previous sets, verifies idempotence via full directory snapshot comparison, then sets `core.hooksPath`; skips cleanly with `HUSKY=0` or no git | `installer` (runs on `pnpm install`) | QC-13 Staged-change hygiene | preserve | Self-verifying wiring for the hook gates — a corrupted half-install cannot silently disable them. |
|
||||
|
||||
### 1.6 CI pipeline steps (`.woodpecker/`)
|
||||
|
||||
Step-to-probe mapping for container steps: `ci.yml#sanitization` = QC-7+QC-8+QC-9 (rows §1.2, plus `apk add bash` env prep); `ci.yml#upgrade-guard` = QC-10 (rows §1.2, plus `apk add rsync`); `ci.yml#typecheck`/`#lint`/`#format`/`#test` = QC-2/3/4/5 (rows §1.1). Rows below are mechanisms that exist only in a pipeline.
|
||||
|
||||
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||
| -------------------------------------- | -------------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | ----------------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------- |
|
||||
| Frozen install | `ci.yml#install` | pipeline-step | `pnpm install --frozen-lockfile --prefer-offline` against the baked ci-base store — lockfile supply integrity; a drifted lockfile fails the build before any gate runs | `CI ci.yml#install` | QC-1 Checkout integrity | preserve | Lockfile-pinned dep resolution is the supply-chain floor under every later gate. |
|
||||
| Test-step readiness prelude | `ci.yml#test` prologue | pipeline-step | Installs pinned `@earendil-works/[email protected]` (Invariant R suite requires the real binary) + openssl; waits up to 60×1s on `pg_isready` for the `ci-postgres` service and fails fast if it never comes up; runs `db:migrate` before tests | `CI ci.yml#test` | QC-5 Test suite execution | preserve | Fail-fast environment preconditions — a missing service produces a legible failure, not a wall of red tests. |
|
||||
| Publish verify step (pending RI-1-001) | `publish.yml#verify` (branch `feat/ri-050-publish-gate` @ `46784c8d`, not yet on next) | pipeline-step | (a) Commit identity: fails closed if `CI_COMMIT_SHA` empty, `git rev-parse HEAD` empty, or the two differ; (b) runs the canonical `pnpm verify:release`. **Every publish effect depends on this step; it carries no path filter** | `publish.yml#verify` | QC-11 Terminal release verification | preserve | The RI-N1 exact-commit binding; until it merges, publish steps on next depend on `build` only (see §3 gap 1). |
|
||||
| Publish error classification | `publish.yml#publish-npm` | pipeline-step | Publishes `@mosaicstack/*` (minus web) and classifies outcome: success, or the **only tolerated failure** = already-published (EPUBLISHCONFLICT / "cannot publish over" / "previously published"); explicit fatal on npm `E404/E401/ENEEDAUTH/ECONNREFUSED/ETIMEDOUT/ENOTFOUND` and on any unrecognized failure (replacing the old ` | | echo` that hid a registry 404) | `publish.yml#publish-npm` (main/tags, path-filtered on `packages/**`) | QC-12 Publish-effect integrity | preserve | Converts silent publish fall-on-floor into loud failure; allowlist-of-one error tolerance is the right shape. |
|
||||
| Next-lane publish assertions | `publish.yml#publish-next-npm` | pipeline-step | Guards: branch must be `next`, `CI_PIPELINE_NUMBER` required; registry dist-tags JSON must be usable; walks all manifests, strictly parses stable semver, rewrites `X.Y.(Z+1)-next.<N>`; publishes with `--tag next` (never latest); post-publish asserts `npm view @mosaicstack/mosaic@next` resolves to the exact expected version | `publish.yml#publish-next-npm` (push/manual on next) | QC-12 Publish-effect integrity | preserve | Durable prerelease lane with end-to-end resolution proof — the published artifact is verified, not assumed. |
|
||||
| Image destination policy | `publish.yml#build-gateway` / `#build-appservice` / `#build-web` | pipeline-step | Kaniko builds with destination policy: `next` ⇒ sha-tag only (fatal if a tag event sneaks in); `main` ⇒ sha + `latest`; tag events ⇒ sha + `<tag>`; anything else fatal. Path filters only skip **effects**, never the verify step | `publish.yml#build-*` | QC-12 Publish-effect integrity | preserve | Fail-closed tagging matrix; the exclude-list default-safe design keeps stale images impossible. |
|
||||
|
||||
Adjacent pipeline surface (not a probe): `.woodpecker/ci-image.yml` rebuilds the ci-base image on `pnpm-lock.yaml`/`Dockerfile.ci` change with an immutable `lock-<hash>` tag; pipelines consume `:latest`. Recorded for completeness — no code-quality property is checked.
|
||||
|
||||
### 1.7 Root installer tooling (`tools/`)
|
||||
|
||||
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||
| --------------------------- | --------------------------------------------------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ------------------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Next-lane installer test | `tools/install-next-lane.test.sh` (`pnpm test:installer`) | shell | Drives `tools/install.sh --next` with faked `node`/`npm` binaries (no network): Node 20 must be rejected; installs must pin **exact** versions (mutable `@next` forbidden); fast path must not unexpectedly fall back to source; gateway-install failure takes the documented fallback | `turbo`-external tail of `pnpm test` → `CI ci.yml#test` | QC-5 Test suite execution | preserve | Hermetic (shimmed) regression net for the installer lane; runs as part of the standard test command. |
|
||||
| Clean-container install E2E | `tools/e2e-install-test.sh` | shell | Full first-run flow in a node:22-alpine container: `install.sh --yes` → `mosaic wizard` (non-interactive) → `mosaic gateway install` → `mosaic gateway verify` exit check (with EXPECTED-SKIP if the installed CLI predates `gateway verify`); skips gracefully without Docker | `local` (manual; requires Docker); **not wired in CI** | QC-5 Test suite execution | strengthen (review) | The only end-to-end proof of the install→verify path; currently operator-initiated only — wire into a periodic/manual CI lane or sign its exclusion explicitly. |
|
||||
| Host installer advisories | `tools/install.sh` (`--check`; `check_fleet_transport`) | shell | `--check` = version comparison only, no install; `check_fleet_transport` warns (non-blocking, by design — tmux is the fleet's dependency, not mosaic's) when the roster-declared transport binary is absent, naming exactly what it blocks; PATH-persistence warnings | `installer` (operator-run) | QC-18 Operator-host drift audit | preserve | Advisory-by-design warnings; the parallel doctor check is drift-tested by §1.3's harness. |
|
||||
|
||||
### 1.8 Pending workstream additions (branch `feat/ri-050-publish-gate` @ `46784c8d`)
|
||||
|
||||
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||
| ------------------------------- | ---------------------------------------------------- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | ----------------------------------- | ----------- | ---------------------------------------------------------------------------------------------- |
|
||||
| Canonical terminal verification | `scripts/verify-release.mjs` (`pnpm verify:release`) | ts | One command replaying the full mandatory set as stages — sanitization, upgrade-guard, typecheck (incl. preflight), lint, format, test, build — mirroring `ci.yml` step-for-step; fail-fast on first failing command; requires `bash`+`rsync` on PATH; `--stage <name>` for wiring smoke-tests only | `publish.yml#verify` (pending); `local` (`pnpm verify:release`) | QC-11 Terminal release verification | preserve | The RI-N1 canonical command — CI and publication share one semantic checklist by construction. |
|
||||
| Verify-parity contract test | `scripts/verify-release.test.mjs` | ts | Parses the real `ci.yml`/`publish.yml`: stage table must match ci.yml step-for-step; every publish-effect step (name `publish*` or image-pushing) must transitively depend on `verify`; commit-identity assertion must be present; `verify` must carry no path filter | `test:checkout` → `CI ci.yml#test` (once merged) | QC-11 Terminal release verification | preserve | Guard-of-the-guard at checkout time — the two surfaces cannot drift apart silently. |
|
||||
|
||||
## 2. Canonical check set
|
||||
|
||||
The deduplicated checks every row above maps onto. IDs are stable for RI-3-002 to consume.
|
||||
|
||||
- **QC-1 Checkout integrity.** Owns: the checkout can run its gates — frozen-lockfile dependency resolution, required gate binaries present, no stale build lock, and the `apps/web/.next` generated-state trust chain (real directory, uid ownership, certified source fingerprint, certified symlink manifest). Implemented by `scripts/preflight.mjs` + frozen install steps.
|
||||
- **QC-2 Workspace typecheck.** Owns workspace-wide TypeScript soundness: per-package `tsc --noEmit` over built dependencies (`turbo typecheck`). The single definition invoked by CI, pre-push, and terminal verification.
|
||||
- **QC-3 Workspace lint.** Owns static-analysis policy: per-package ESLint under the root config. One config, one task, every surface.
|
||||
- **QC-4 Format check.** Owns formatting uniformity: Prettier check with the repo ignore list. (The pre-commit variant additionally fixes; the verdict form is this check.)
|
||||
- **QC-5 Test suite execution.** Owns execution of all test surfaces: checkout script units (`node --test`), per-package Vitest suites (including the framework shell chain and its python unitests), the installer-lane shim test, and — once wired — `test-roster-schema.py` and container E2E. Also owns guards-of-the-gate that live inside the chain (terminal-green contract, RCE regression).
|
||||
- **QC-6 Workspace build.** Owns artifact buildability: `turbo build` producing the artifacts publication consumes.
|
||||
- **QC-7 Framework sanitization.** Owns the open-source guarantee for the shipped framework package: no operator-identity tokens anywhere (examples included), no private `$HOME` defaults in shipped scripts, with a self-test that keeps the regexes honest.
|
||||
- **QC-8 Resident-context budget.** Owns the line-count ceilings on framework files injected into every agent's context (Constitution, dispatcher, RUNTIME.md slices) — the CI-enforceable half of the resident-prompt budget.
|
||||
- **QC-9 Test-membership enumeration.** Owns the property that no test suite can silently fall out of CI: disk population vs parsed enumeration surfaces, both-directions staleness, and signed exclusions with reasons. Includes its needle/control harness.
|
||||
- **QC-10 Upgrade/install safety.** Owns the #791 family: operator-path byte-identity across keep-mode upgrades (manifest guard), mid-failure rollback (errtrace-proven), durable pre-update snapshot + verify net + CWE-59 leaf guard, and the v2→v3 migration matrix with shell/TS parity.
|
||||
- **QC-11 Terminal release verification.** Owns the RI-N1 exact-commit binding: commit-identity assertion plus one canonical command (`pnpm verify:release`) replaying the complete mandatory set, with every publish effect depending on it; plus the checkout-time parity/DAG contract test that keeps pipeline and command in sync.
|
||||
- **QC-12 Publish-effect integrity.** Owns publication correctness: npm publish error classification (only already-published tolerated), next-lane versioning and post-publish resolution proof, and image destination/tag policy.
|
||||
- **QC-13 Staged-change hygiene.** Owns commit-time hygiene on staged files (prettier/eslint fix-and-restage) and the self-verifying hook wiring that guarantees the gates are actually installed.
|
||||
- **QC-14 Pre-push gate.** Owns the local push composition: preflight + typecheck + lint + format:check (tests deliberately deferred to CI).
|
||||
- **QC-15 Lease-gate architecture invariant.** Owns "no ungated runtime launches in production code": the scan + allowlist over `packages/`, `apps/`, `plugins/`, `tools/`.
|
||||
- **QC-16 Agent-runtime edit-time checks.** Owns edit-time feedback on agent hosts: the deps-preflight legibility sentinel and typecheck-on-edit, plus their regression harnesses.
|
||||
- **QC-17 Lease-enforcement wiring safety.** Owns the #869 C1/C2/C5 trio: activation capability probe (versioned contract), enforcement-hook wiring gate (default-deny with explicit opt-out), and the doctor check that surfaces a bricked host — with their shell/TS harnesses.
|
||||
- **QC-18 Operator-host drift audit.** Owns host-state health CI cannot see: `mosaic doctor` drift audit (+ fleet transport, both implementations), `fleet doctor` roster classification, `gateway doctor`/`gateway verify` service health, and installer advisories. Advisory exits are part of the contract.
|
||||
- **QC-19 Downstream rails presence check.** Owns "does a scaffolded project still carry its rails files" — today the TS `quality-rails check/doctor` presence loop; per RI-N4 this is the seed that must become the typed evaluator (presence alone is explicitly not parity).
|
||||
- **QC-20 Downstream enforcement verification.** Owns "do the rails actually block" on scaffolded projects: the behavioral planted-commit probe (type error, `any`, lint, gitleaks secret) currently in `verify.sh`/`verify.ps1` behind the `mosaic-quality-verify` adapter.
|
||||
- **QC-21 Downstream rails scaffolding.** Owns putting rails files into a target project: the shell template installer (+ PowerShell twin) and the TS `quality-rails init` scaffolder — currently two paths that must converge.
|
||||
|
||||
## 3. Coverage gaps
|
||||
|
||||
Enforced nowhere but implied, or named in docs/tooling but not wired:
|
||||
|
||||
1. **Publication not yet bound to verification on `next`.** At this base (`8199261c`), `publish.yml` publish steps depend on `build` only; the `verify` step and `scripts/verify-release.mjs` exist on `feat/ri-050-publish-gate` (`46784c8d`) but are not merged. Until RI-1-001 lands, AC-RI-1's negative control cannot hold on the real pipeline.
|
||||
2. **Playwright E2E unwired.** `apps/web` ships `test:e2e` (`playwright test`) with real suites (`admin/auth/chat/navigation.spec.ts`); neither `pnpm test` nor any CI step invokes it. The web UI's user flows are verified only when an operator runs them manually.
|
||||
3. **No secret scanning on this repo.** The framework's own template pre-commit makes gitleaks **required**, and `verify.sh` proves detection with a planted key — but this repository's `.husky/pre-commit` (lint-staged only) and CI run no secret scan. The repo ships the control it does not use.
|
||||
4. **No dependency audit.** The quality `.woodpecker.yml` templates and `docs/CI-SETUP.md` specify `npm audit --audit-level=high` as a pipeline stage; nothing equivalent runs for this repo.
|
||||
5. **No coverage thresholds.** Templates enforce 80% Jest coverage thresholds; this repo's Vitest configs collect coverage with no thresholds — coverage is measured nowhere and enforced nowhere.
|
||||
6. **`test-roster-schema.py` invisible.** A real jsonschema regression suite wired to no surface and invisible to the enumeration guard (its population is `*.sh`; the suite is `.py`). Either enumerate it or sign an exclusion — silence here is the #1017 defect shape.
|
||||
7. **Presence-checker expectations ≠ this repo.** `quality-rails check` expects `.eslintrc`, `biome.json`, `.githooks/pre-commit`, `PR-CHECKLIST.md` for node projects — none describe this monorepo (husky, flat eslint config, no biome, no PR-CHECKLIST.md). The evaluator's check set must be per-subject (versioned, digested), not one global file list.
|
||||
8. **Chain-ordering residual (documented).** `test:framework-shell` is one `&&` chain: a failing link skips every later suite while the step still fails (measured in #1270 — four suites after position 44 had not run since a prior merge). The enumeration guard proves naming, not reachability; both residuals are in-file documented but structurally unfixed.
|
||||
9. **Signed-exclusion burndown open.** 16 signed exclusions remain in `test-enumeration-exclusions.txt`; several are "unmeasured in CI image" or blocked on missing CI tooling (tmux, setsid) — tracked under #1017/#1271. Each is an enforcement promise deferred, not delivered.
|
||||
10. **Windows twins unexercised.** `verify.ps1`, `install.ps1`, `mosaic-doctor.ps1` have no runner anywhere (no Windows CI); behavioral drift from their bash twins is undetectable by construction.
|
||||
11. **QA hook name vs behavior.** `qa-hook-handler.sh` files remediation report templates but performs no verification; the seam's actual gate value is only the deps-preflight sentinel. Anything relying on "QA automation hook" as a check is relying on report-filing.
|
||||
12. **Two test paths, one gated.** CI runs tests against ci-postgres (`DATABASE_URL` set); the local PGlite path is the documented default (AGENTS.md) until KBN-101-02/101-05. Only the CI path is enforced by pipeline.
|
||||
|
||||
## 4. Disposition summary
|
||||
|
||||
| disposition | rows | checks |
|
||||
| ------------------- | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| preserve | 43 | Every canonical owner (QC-1..QC-18) plus correct guards-of-the-guard and thin adapters: all of §1.1, the CI-invoked framework probes and adapters in §1.2, all of §1.3, the C1/C2/C5 trio and doctors in §1.4, all of §1.5, all pipeline-only steps in §1.6, §1.7 rows 1 and 3, and §1.8. |
|
||||
| strengthen | 2 | `quality-rails check` and `quality-rails doctor` (QC-19) — the RI-N4 evaluator seed: typed verdicts, versioned/digested check definitions, per-subject check sets. |
|
||||
| strengthen (review) | 9 | `verify.sh` + `verify.ps1` (QC-20), quality `install.sh`/`install.ps1` + `quality-rails init` (QC-21 — scaffold-path convergence), `test-roster-schema.py` (QC-5 — wire or sign), `qa-hook-stdin.sh` seam + `typecheck-hook.sh` (QC-16), `tools/e2e-install-test.sh` (QC-5 — CI lane). |
|
||||
| retire | 0 | None meet the bar: RI-N4 requires effective shell probes be **absorbed before** their paths retire, and no absorption exists yet. The `strengthen (review)` rows are the retirement candidates for RI-3-002 once the evaluator owns their behavior. |
|
||||
|
||||
Row total: 54. Canonical checks: 21 (QC-1..QC-21).
|
||||
@@ -0,0 +1,253 @@
|
||||
import { mkdirSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { normalizeGate, countAIFindings, runGate, runGates } from '../src/gate-runner.js';
|
||||
|
||||
function makeTmpDir(): string {
|
||||
const dir = join(tmpdir(), `macp-gate-${randomUUID()}`);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
describe('normalizeGate', () => {
|
||||
it('normalizes a string to mechanical gate', () => {
|
||||
expect(normalizeGate('echo test')).toEqual({
|
||||
command: 'echo test',
|
||||
type: 'mechanical',
|
||||
fail_on: 'blocker',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes an object gate with defaults', () => {
|
||||
expect(normalizeGate({ command: 'lint' })).toEqual({
|
||||
command: 'lint',
|
||||
type: 'mechanical',
|
||||
fail_on: 'blocker',
|
||||
});
|
||||
});
|
||||
|
||||
it('preserves explicit type and fail_on', () => {
|
||||
expect(normalizeGate({ command: 'review', type: 'ai-review', fail_on: 'any' })).toEqual({
|
||||
command: 'review',
|
||||
type: 'ai-review',
|
||||
fail_on: 'any',
|
||||
});
|
||||
});
|
||||
|
||||
it('handles non-string/non-object input', () => {
|
||||
expect(normalizeGate(42)).toEqual({ command: '', type: 'mechanical', fail_on: 'blocker' });
|
||||
expect(normalizeGate(null)).toEqual({ command: '', type: 'mechanical', fail_on: 'blocker' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('countAIFindings', () => {
|
||||
it('returns zeros for non-object', () => {
|
||||
expect(countAIFindings(null)).toEqual({ blockers: 0, total: 0 });
|
||||
expect(countAIFindings('string')).toEqual({ blockers: 0, total: 0 });
|
||||
expect(countAIFindings([])).toEqual({ blockers: 0, total: 0 });
|
||||
});
|
||||
|
||||
it('counts from stats block', () => {
|
||||
const output = { stats: { blockers: 2, should_fix: 3, suggestions: 1 } };
|
||||
expect(countAIFindings(output)).toEqual({ blockers: 2, total: 6 });
|
||||
});
|
||||
|
||||
it('counts from findings array when stats has no blockers', () => {
|
||||
const output = {
|
||||
stats: { blockers: 0 },
|
||||
findings: [{ severity: 'blocker' }, { severity: 'warning' }, { severity: 'blocker' }],
|
||||
};
|
||||
expect(countAIFindings(output)).toEqual({ blockers: 2, total: 3 });
|
||||
});
|
||||
|
||||
it('uses stats blockers over findings array when stats has blockers', () => {
|
||||
const output = {
|
||||
stats: { blockers: 5 },
|
||||
findings: [{ severity: 'blocker' }, { severity: 'warning' }],
|
||||
};
|
||||
// stats.blockers = 5, total from stats = 5+0+0 = 5, findings not used for total since stats total is non-zero
|
||||
expect(countAIFindings(output)).toEqual({ blockers: 5, total: 5 });
|
||||
});
|
||||
|
||||
it('counts findings length as total when stats has zero total', () => {
|
||||
const output = {
|
||||
findings: [{ severity: 'warning' }, { severity: 'info' }],
|
||||
};
|
||||
expect(countAIFindings(output)).toEqual({ blockers: 0, total: 2 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('runGate', () => {
|
||||
let tmp: string;
|
||||
let logPath: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tmp = makeTmpDir();
|
||||
logPath = join(tmp, 'gate.log');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('passes mechanical gate on exit 0', () => {
|
||||
const result = runGate('echo hello', tmp, logPath, 30);
|
||||
expect(result.passed).toBe(true);
|
||||
expect(result.exit_code).toBe(0);
|
||||
expect(result.type).toBe('mechanical');
|
||||
expect(result.output).toContain('hello');
|
||||
});
|
||||
|
||||
it('fails mechanical gate on non-zero exit', () => {
|
||||
const result = runGate('exit 1', tmp, logPath, 30);
|
||||
expect(result.passed).toBe(false);
|
||||
expect(result.exit_code).toBe(1);
|
||||
});
|
||||
|
||||
it('ci-pipeline always passes', () => {
|
||||
const result = runGate({ command: 'anything', type: 'ci-pipeline' }, tmp, logPath, 30);
|
||||
expect(result.passed).toBe(true);
|
||||
expect(result.type).toBe('ci-pipeline');
|
||||
expect(result.output).toBe('CI pipeline gate placeholder');
|
||||
});
|
||||
|
||||
it('empty command passes', () => {
|
||||
const result = runGate({ command: '' }, tmp, logPath, 30);
|
||||
expect(result.passed).toBe(true);
|
||||
});
|
||||
|
||||
it('ai-review gate parses JSON output', () => {
|
||||
const json = JSON.stringify({ stats: { blockers: 0, should_fix: 1 } });
|
||||
const result = runGate({ command: `echo '${json}'`, type: 'ai-review' }, tmp, logPath, 30);
|
||||
expect(result.passed).toBe(true);
|
||||
expect(result.blockers).toBe(0);
|
||||
expect(result.findings).toBe(1);
|
||||
});
|
||||
|
||||
it('ai-review gate fails on blockers', () => {
|
||||
const json = JSON.stringify({ stats: { blockers: 2 } });
|
||||
const result = runGate({ command: `echo '${json}'`, type: 'ai-review' }, tmp, logPath, 30);
|
||||
expect(result.passed).toBe(false);
|
||||
expect(result.blockers).toBe(2);
|
||||
});
|
||||
|
||||
it('ai-review gate with fail_on=any fails on any findings', () => {
|
||||
const json = JSON.stringify({ stats: { blockers: 0, should_fix: 1 } });
|
||||
const result = runGate(
|
||||
{ command: `echo '${json}'`, type: 'ai-review', fail_on: 'any' },
|
||||
tmp,
|
||||
logPath,
|
||||
30,
|
||||
);
|
||||
expect(result.passed).toBe(false);
|
||||
expect(result.fail_on).toBe('any');
|
||||
});
|
||||
|
||||
it('ai-review gate fails on invalid JSON output', () => {
|
||||
const result = runGate({ command: 'echo "not json"', type: 'ai-review' }, tmp, logPath, 30);
|
||||
expect(result.passed).toBe(false);
|
||||
expect(result.parse_error).toBeDefined();
|
||||
});
|
||||
|
||||
it('writes to log file', () => {
|
||||
runGate('echo logged', tmp, logPath, 30);
|
||||
const log = readFileSync(logPath, 'utf-8');
|
||||
expect(log).toContain('COMMAND: echo logged');
|
||||
expect(log).toContain('logged');
|
||||
expect(log).toContain('EXIT:');
|
||||
});
|
||||
});
|
||||
|
||||
describe('runGates', () => {
|
||||
let tmp: string;
|
||||
let logPath: string;
|
||||
let eventsPath: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tmp = makeTmpDir();
|
||||
logPath = join(tmp, 'gates.log');
|
||||
eventsPath = join(tmp, 'events.ndjson');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('runs multiple gates and returns results', () => {
|
||||
const { allPassed, gateResults } = runGates(
|
||||
['echo one', 'echo two'],
|
||||
tmp,
|
||||
logPath,
|
||||
30,
|
||||
eventsPath,
|
||||
'task-1',
|
||||
);
|
||||
expect(allPassed).toBe(true);
|
||||
expect(gateResults).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('reports failure when any gate fails', () => {
|
||||
const { allPassed, gateResults } = runGates(
|
||||
['echo ok', 'exit 1'],
|
||||
tmp,
|
||||
logPath,
|
||||
30,
|
||||
eventsPath,
|
||||
'task-2',
|
||||
);
|
||||
expect(allPassed).toBe(false);
|
||||
expect(gateResults[0]!.passed).toBe(true);
|
||||
expect(gateResults[1]!.passed).toBe(false);
|
||||
});
|
||||
|
||||
it('emits events for each gate', () => {
|
||||
runGates(['echo test'], tmp, logPath, 30, eventsPath, 'task-3');
|
||||
const events = readFileSync(eventsPath, 'utf-8')
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map((l) => JSON.parse(l));
|
||||
expect(events).toHaveLength(2); // started + passed
|
||||
expect(events[0].event_type).toBe('rail.check.started');
|
||||
expect(events[1].event_type).toBe('rail.check.passed');
|
||||
});
|
||||
|
||||
it('skips gates with empty command (non ci-pipeline)', () => {
|
||||
const { gateResults } = runGates(
|
||||
[{ command: '', type: 'mechanical' }, 'echo real'],
|
||||
tmp,
|
||||
logPath,
|
||||
30,
|
||||
eventsPath,
|
||||
'task-4',
|
||||
);
|
||||
expect(gateResults).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('does not skip ci-pipeline even with empty command', () => {
|
||||
const { gateResults } = runGates(
|
||||
[{ command: '', type: 'ci-pipeline' }],
|
||||
tmp,
|
||||
logPath,
|
||||
30,
|
||||
eventsPath,
|
||||
'task-5',
|
||||
);
|
||||
expect(gateResults).toHaveLength(1);
|
||||
expect(gateResults[0]!.passed).toBe(true);
|
||||
});
|
||||
|
||||
it('emits failed event with correct message', () => {
|
||||
runGates(['exit 42'], tmp, logPath, 30, eventsPath, 'task-6');
|
||||
const events = readFileSync(eventsPath, 'utf-8')
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map((l) => JSON.parse(l));
|
||||
const failEvent = events.find(
|
||||
(e: Record<string, unknown>) => e.event_type === 'rail.check.failed',
|
||||
);
|
||||
expect(failEvent).toBeDefined();
|
||||
expect(failEvent.message).toContain('Gate failed (');
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,5 @@
|
||||
import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { Command } from 'commander';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { registerMacpCommand } from './cli.js';
|
||||
|
||||
describe('registerMacpCommand', () => {
|
||||
@@ -78,162 +75,3 @@ describe('registerMacpCommand', () => {
|
||||
expect(topLevel).toContain('events');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* RI-N2 fail-closed CLI behavior: an unimplemented capability is a failure,
|
||||
* never a success. Every stub exits nonzero with a typed message, and the
|
||||
* implemented `macp gate` mirrors the typed gate-runner states.
|
||||
*/
|
||||
describe('registerMacpCommand fail-closed (RI-N2)', () => {
|
||||
let tmpDir: string;
|
||||
|
||||
function buildProgram(): Command {
|
||||
const program = new Command();
|
||||
program.exitOverride();
|
||||
program.configureOutput({ writeErr: () => {} });
|
||||
registerMacpCommand(program);
|
||||
return program;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'macp-cli-failclosed-'));
|
||||
process.exitCode = 0;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.exitCode = 0;
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('macp tasks list exits nonzero (unimplemented capability)', async () => {
|
||||
const program = buildProgram();
|
||||
await program.parseAsync(['macp', 'tasks', 'list'], { from: 'user' });
|
||||
expect(process.exitCode).not.toBe(0);
|
||||
});
|
||||
|
||||
it('macp submit exits nonzero with a typed MACP_NOT_IMPLEMENTED message', async () => {
|
||||
const program = buildProgram();
|
||||
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
try {
|
||||
await program.parseAsync(['macp', 'submit', 'spec.json'], { from: 'user' });
|
||||
expect(process.exitCode).not.toBe(0);
|
||||
const errText = errSpy.mock.calls.map((c) => String(c[0])).join('\n');
|
||||
expect(errText).toContain('MACP_NOT_IMPLEMENTED');
|
||||
} finally {
|
||||
errSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('macp events tail exits nonzero (unimplemented capability)', async () => {
|
||||
const program = buildProgram();
|
||||
await program.parseAsync(['macp', 'events', 'tail'], { from: 'user' });
|
||||
expect(process.exitCode).not.toBe(0);
|
||||
});
|
||||
|
||||
it('macp gate runs a green inline command and exits 0', async () => {
|
||||
const program = buildProgram();
|
||||
await program.parseAsync(
|
||||
[
|
||||
'macp',
|
||||
'gate',
|
||||
'exit 0',
|
||||
'--cwd',
|
||||
tmpDir,
|
||||
'--log',
|
||||
path.join(tmpDir, 'g.log'),
|
||||
'--timeout',
|
||||
'10',
|
||||
],
|
||||
{ from: 'user' },
|
||||
);
|
||||
expect(process.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
it('macp gate exits nonzero on a failing command', async () => {
|
||||
const program = buildProgram();
|
||||
await program.parseAsync(
|
||||
[
|
||||
'macp',
|
||||
'gate',
|
||||
'exit 9',
|
||||
'--cwd',
|
||||
tmpDir,
|
||||
'--log',
|
||||
path.join(tmpDir, 'g.log'),
|
||||
'--timeout',
|
||||
'10',
|
||||
],
|
||||
{ from: 'user' },
|
||||
);
|
||||
expect(process.exitCode).not.toBe(0);
|
||||
});
|
||||
|
||||
it('macp gate with an unimplemented ci-pipeline capability exits nonzero', async () => {
|
||||
const program = buildProgram();
|
||||
const specPath = path.join(tmpDir, 'gates.json');
|
||||
fs.writeFileSync(specPath, JSON.stringify([{ type: 'ci-pipeline' }]));
|
||||
await program.parseAsync(
|
||||
[
|
||||
'macp',
|
||||
'gate',
|
||||
specPath,
|
||||
'--cwd',
|
||||
tmpDir,
|
||||
'--log',
|
||||
path.join(tmpDir, 'g.log'),
|
||||
'--timeout',
|
||||
'10',
|
||||
],
|
||||
{ from: 'user' },
|
||||
);
|
||||
expect(process.exitCode).not.toBe(0);
|
||||
});
|
||||
|
||||
it('macp gate --simulate completes (exit 0) but reports simulated results', async () => {
|
||||
const program = buildProgram();
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
try {
|
||||
await program.parseAsync(
|
||||
[
|
||||
'macp',
|
||||
'gate',
|
||||
'exit 0',
|
||||
'--simulate',
|
||||
'--cwd',
|
||||
tmpDir,
|
||||
'--log',
|
||||
path.join(tmpDir, 'g.log'),
|
||||
'--timeout',
|
||||
'10',
|
||||
],
|
||||
{ from: 'user' },
|
||||
);
|
||||
// completes only because the caller explicitly asked to simulate
|
||||
expect(process.exitCode).toBe(0);
|
||||
const outText = logSpy.mock.calls.map((c) => String(c[0])).join('\n');
|
||||
expect(outText).toContain('simulated');
|
||||
expect(outText).toContain('SIMULATED');
|
||||
} finally {
|
||||
logSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('macp gate with an empty spec exits nonzero with a typed error', async () => {
|
||||
const program = buildProgram();
|
||||
await program.parseAsync(
|
||||
[
|
||||
'macp',
|
||||
'gate',
|
||||
' ',
|
||||
'--cwd',
|
||||
tmpDir,
|
||||
'--log',
|
||||
path.join(tmpDir, 'g.log'),
|
||||
'--timeout',
|
||||
'10',
|
||||
],
|
||||
{ from: 'user' },
|
||||
);
|
||||
expect(process.exitCode).not.toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
+19
-129
@@ -1,73 +1,5 @@
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
|
||||
import type { Command } from 'commander';
|
||||
|
||||
import { runGates } from './gate-runner.js';
|
||||
import { MACPCapabilityError, type MacpErrorCode } from './errors.js';
|
||||
|
||||
/**
|
||||
* Load gates from a spec: an existing file (JSON gates array, a JSON object
|
||||
* with `quality_gates`, a JSON gate object, or one command per line) or an
|
||||
* inline command string. Fails closed with a typed capability error when the
|
||||
* spec contains no executable gate definition.
|
||||
*/
|
||||
function loadGateSpec(spec: string): unknown[] {
|
||||
if (existsSync(spec)) {
|
||||
const raw = readFileSync(spec, 'utf-8');
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (Array.isArray(parsed)) {
|
||||
if (parsed.length === 0) {
|
||||
throw new MACPCapabilityError(
|
||||
'MACP_NO_COMMAND',
|
||||
'gate-spec',
|
||||
`gate spec file '${spec}' contains an empty gates array`,
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
if (typeof parsed === 'object' && parsed !== null) {
|
||||
const obj = parsed as Record<string, unknown>;
|
||||
if (Array.isArray(obj['quality_gates'])) {
|
||||
return obj['quality_gates'];
|
||||
}
|
||||
return [parsed];
|
||||
}
|
||||
throw new MACPCapabilityError(
|
||||
'MACP_NO_COMMAND',
|
||||
'gate-spec',
|
||||
`gate spec file '${spec}' parsed to ${typeof parsed} — expected a gates array, a task with quality_gates, or a gate object`,
|
||||
);
|
||||
} catch (exc) {
|
||||
if (exc instanceof MACPCapabilityError) throw exc;
|
||||
// Not JSON — treat each non-empty line as a command gate.
|
||||
const lines = raw
|
||||
.split('\n')
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l.length > 0);
|
||||
if (lines.length > 0) return lines;
|
||||
throw new MACPCapabilityError(
|
||||
'MACP_NO_COMMAND',
|
||||
'gate-spec',
|
||||
`gate spec file '${spec}' contains no gates`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (spec.trim().length > 0) return [spec];
|
||||
throw new MACPCapabilityError('MACP_NO_COMMAND', 'gate-spec', 'gate spec is empty');
|
||||
}
|
||||
|
||||
/** Print a typed not-implemented failure and exit nonzero (RI-N2 fail-closed). */
|
||||
function notImplemented(subcommand: string, capability: string, hint: string): void {
|
||||
const err = new MACPCapabilityError(
|
||||
'MACP_NOT_IMPLEMENTED',
|
||||
capability,
|
||||
`${subcommand} is not implemented in @mosaicstack/macp yet (${capability} capability absent) — ${hint}`,
|
||||
);
|
||||
console.error(`[macp] ${subcommand}: ${err.message} [${err.code}]`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register macp subcommands on an existing Commander program.
|
||||
* This avoids cross-package Commander version mismatches by using the
|
||||
@@ -92,14 +24,15 @@ export function registerMacpCommand(parent: Command): void {
|
||||
'Filter by task type (coding|deploy|research|review|documentation|infrastructure)',
|
||||
)
|
||||
.action((opts: { status?: string; type?: string }) => {
|
||||
// unimplemented capability — a failure, never a success (RI-N2)
|
||||
// not yet wired — task persistence layer is not present in @mosaicstack/macp
|
||||
console.log('[macp] tasks list: not yet wired — use macp package programmatically');
|
||||
if (opts.status) {
|
||||
console.log(` status filter: ${opts.status}`);
|
||||
}
|
||||
if (opts.type) {
|
||||
console.log(` type filter: ${opts.type}`);
|
||||
}
|
||||
notImplemented('tasks list', 'task-persistence', 'use the macp package programmatically');
|
||||
process.exitCode = 0;
|
||||
});
|
||||
|
||||
// ─── submit ──────────────────────────────────────────────────────────────
|
||||
@@ -108,11 +41,12 @@ export function registerMacpCommand(parent: Command): void {
|
||||
.command('submit <path>')
|
||||
.description('Submit a task from a JSON/YAML spec file')
|
||||
.action((specPath: string) => {
|
||||
// unimplemented capability — a failure, never a success (RI-N2)
|
||||
// not yet wired — task submission requires a running MACP server
|
||||
console.log('[macp] submit: not yet wired — use macp package programmatically');
|
||||
console.log(` spec path: ${specPath}`);
|
||||
console.log(' task id: (unavailable — no MACP server connected)');
|
||||
console.log(' status: (unavailable — no MACP server connected)');
|
||||
notImplemented('submit', 'macp-server', 'use the macp package programmatically');
|
||||
process.exitCode = 0;
|
||||
});
|
||||
|
||||
// ─── gate ────────────────────────────────────────────────────────────────
|
||||
@@ -124,58 +58,16 @@ export function registerMacpCommand(parent: Command): void {
|
||||
.option('--cwd <path>', 'Working directory for gate execution', process.cwd())
|
||||
.option('--log <path>', 'Path to write gate log output', '/tmp/macp-gate.log')
|
||||
.option('--timeout <seconds>', 'Gate timeout in seconds', '60')
|
||||
.option(
|
||||
'--simulate',
|
||||
'Simulate gates instead of executing them; results are typed simulated and never satisfy a check',
|
||||
)
|
||||
.action(
|
||||
(
|
||||
spec: string,
|
||||
opts: { failOn: string; cwd: string; log: string; timeout: string; simulate?: boolean },
|
||||
) => {
|
||||
let gates: unknown[];
|
||||
try {
|
||||
gates = loadGateSpec(spec);
|
||||
} catch (exc) {
|
||||
if (exc instanceof MACPCapabilityError) {
|
||||
console.error(`[macp] gate: ${exc.message} [${exc.code}]`);
|
||||
} else {
|
||||
console.error(`[macp] gate: ${String(exc)}`);
|
||||
}
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
const timeoutSec = Number.parseInt(opts.timeout, 10) || 60;
|
||||
const eventsPath = `${opts.log}.events.ndjson`;
|
||||
const { state, gateResults } = runGates(
|
||||
gates,
|
||||
opts.cwd,
|
||||
opts.log,
|
||||
timeoutSec,
|
||||
eventsPath,
|
||||
'macp-cli-gate',
|
||||
{
|
||||
simulate: opts.simulate,
|
||||
},
|
||||
);
|
||||
|
||||
for (const r of gateResults) {
|
||||
const label = r.command || r.type;
|
||||
const reason = r.reason ? ` — ${r.reason}` : '';
|
||||
console.log(`[macp] gate ${r.status}: ${label}${reason}`);
|
||||
}
|
||||
if (opts.simulate) {
|
||||
console.log(
|
||||
'[macp] SIMULATED run — every result is typed simulated and can never satisfy a gate, dependency, or release check',
|
||||
);
|
||||
}
|
||||
|
||||
// Simulated runs may complete (exit 0) only because the caller
|
||||
// explicitly passed --simulate; the typed state stays 'simulated'.
|
||||
process.exitCode = state === 'passed' || state === 'simulated' ? 0 : 1;
|
||||
},
|
||||
);
|
||||
.action((spec: string, opts: { failOn: string; cwd: string; log: string; timeout: string }) => {
|
||||
// not yet wired — gate execution requires a task context and event sink
|
||||
console.log('[macp] gate: not yet wired — use macp package programmatically');
|
||||
console.log(` spec: ${spec}`);
|
||||
console.log(` fail-on: ${opts.failOn}`);
|
||||
console.log(` cwd: ${opts.cwd}`);
|
||||
console.log(` log: ${opts.log}`);
|
||||
console.log(` timeout: ${opts.timeout}s`);
|
||||
process.exitCode = 0;
|
||||
});
|
||||
|
||||
// ─── events ──────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -187,16 +79,14 @@ export function registerMacpCommand(parent: Command): void {
|
||||
.option('--file <path>', 'Path to the MACP events NDJSON file')
|
||||
.option('--follow', 'Follow the file for new events (like tail -f)')
|
||||
.action((opts: { file?: string; follow?: boolean }) => {
|
||||
// unimplemented capability — a failure, never a success (RI-N2)
|
||||
// not yet wired — event streaming requires a live event source
|
||||
console.log('[macp] events tail: not yet wired — use macp package programmatically');
|
||||
if (opts.file) {
|
||||
console.log(` file: ${opts.file}`);
|
||||
}
|
||||
if (opts.follow) {
|
||||
console.log(' mode: follow');
|
||||
}
|
||||
notImplemented('events tail', 'event-source', 'use the macp package programmatically');
|
||||
process.exitCode = 0;
|
||||
});
|
||||
}
|
||||
|
||||
// Re-export so CLI consumers can surface typed capability codes.
|
||||
export type { MacpErrorCode };
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
/** Typed error code from the closed MACP_ERROR_CODES set. */
|
||||
export type MacpErrorCode = (typeof MACP_ERROR_CODES)[number];
|
||||
/**
|
||||
* Typed fail-closed capability errors (RI-N2, SDLC-D-035).
|
||||
*
|
||||
* MACP must fail closed when a required capability (executor, reviewer,
|
||||
* command, CI provider, human authority) is absent. These typed codes mirror
|
||||
* the Forge failure vocabulary (FORGE_NO_*) so both packages speak the same
|
||||
* language: an unimplemented capability is a failure, never a stub success.
|
||||
*/
|
||||
|
||||
/** Closed set of typed MACP capability error codes. */
|
||||
export const MACP_ERROR_CODES = [
|
||||
'MACP_NOT_IMPLEMENTED',
|
||||
'MACP_NO_COMMAND',
|
||||
'MACP_NO_REVIEWER',
|
||||
'MACP_NO_CI_PIPELINE',
|
||||
'MACP_NO_PROVIDER',
|
||||
'MACP_AUTHORITY_REQUIRED',
|
||||
] as const;
|
||||
|
||||
/** Raised when a required capability is missing and execution must fail closed. */
|
||||
export class MACPCapabilityError extends Error {
|
||||
/** Typed error code from the closed MACP_ERROR_CODES set. */
|
||||
readonly code: MacpErrorCode;
|
||||
/** The missing capability, e.g. `ci-provider`, `task-persistence`, `command`. */
|
||||
readonly capability: string;
|
||||
|
||||
constructor(code: MacpErrorCode, capability: string, message: string) {
|
||||
super(message);
|
||||
this.name = 'MACPCapabilityError';
|
||||
this.code = code;
|
||||
this.capability = capability;
|
||||
}
|
||||
}
|
||||
@@ -1,429 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { countAIFindings, normalizeGate, runGate, runGates } from './gate-runner.js';
|
||||
|
||||
function makeTmpDir(): string {
|
||||
return fs.mkdtempSync(path.join(os.tmpdir(), 'macp-gate-'));
|
||||
}
|
||||
|
||||
describe('normalizeGate', () => {
|
||||
it('normalizes a string to mechanical gate', () => {
|
||||
expect(normalizeGate('echo test')).toEqual({
|
||||
command: 'echo test',
|
||||
type: 'mechanical',
|
||||
fail_on: 'blocker',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes an object gate with defaults', () => {
|
||||
expect(normalizeGate({ command: 'lint' })).toEqual({
|
||||
command: 'lint',
|
||||
type: 'mechanical',
|
||||
fail_on: 'blocker',
|
||||
});
|
||||
});
|
||||
|
||||
it('preserves explicit type and fail_on', () => {
|
||||
expect(normalizeGate({ command: 'review', type: 'ai-review', fail_on: 'any' })).toEqual({
|
||||
command: 'review',
|
||||
type: 'ai-review',
|
||||
fail_on: 'any',
|
||||
});
|
||||
});
|
||||
|
||||
it('handles non-string/non-object input', () => {
|
||||
expect(normalizeGate(42)).toEqual({ command: '', type: 'mechanical', fail_on: 'blocker' });
|
||||
expect(normalizeGate(null)).toEqual({ command: '', type: 'mechanical', fail_on: 'blocker' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('countAIFindings', () => {
|
||||
it('returns zeros for non-object', () => {
|
||||
expect(countAIFindings(null)).toEqual({ blockers: 0, total: 0 });
|
||||
expect(countAIFindings('string')).toEqual({ blockers: 0, total: 0 });
|
||||
expect(countAIFindings([])).toEqual({ blockers: 0, total: 0 });
|
||||
});
|
||||
|
||||
it('counts from stats block', () => {
|
||||
const output = { stats: { blockers: 2, should_fix: 3, suggestions: 1 } };
|
||||
expect(countAIFindings(output)).toEqual({ blockers: 2, total: 6 });
|
||||
});
|
||||
|
||||
it('counts from findings array when stats has no blockers', () => {
|
||||
const output = {
|
||||
stats: { blockers: 0 },
|
||||
findings: [{ severity: 'blocker' }, { severity: 'warning' }, { severity: 'blocker' }],
|
||||
};
|
||||
expect(countAIFindings(output)).toEqual({ blockers: 2, total: 3 });
|
||||
});
|
||||
|
||||
it('uses stats blockers over findings array when stats has blockers', () => {
|
||||
const output = {
|
||||
stats: { blockers: 5 },
|
||||
findings: [{ severity: 'blocker' }, { severity: 'warning' }],
|
||||
};
|
||||
// stats.blockers = 5, total from stats = 5+0+0 = 5, findings not used for total since stats total is non-zero
|
||||
expect(countAIFindings(output)).toEqual({ blockers: 5, total: 5 });
|
||||
});
|
||||
|
||||
it('counts findings length as total when stats has zero total', () => {
|
||||
const output = {
|
||||
findings: [{ severity: 'warning' }, { severity: 'info' }],
|
||||
};
|
||||
expect(countAIFindings(output)).toEqual({ blockers: 0, total: 2 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('runGate', () => {
|
||||
let tmp: string;
|
||||
let logPath: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tmp = makeTmpDir();
|
||||
logPath = path.join(tmp, 'gate.log');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('passes mechanical gate on exit 0', () => {
|
||||
const result = runGate('echo hello', tmp, logPath, 30);
|
||||
expect(result.passed).toBe(true);
|
||||
expect(result.exit_code).toBe(0);
|
||||
expect(result.type).toBe('mechanical');
|
||||
expect(result.output).toContain('hello');
|
||||
});
|
||||
|
||||
it('fails mechanical gate on non-zero exit', () => {
|
||||
const result = runGate('exit 1', tmp, logPath, 30);
|
||||
expect(result.passed).toBe(false);
|
||||
expect(result.exit_code).toBe(1);
|
||||
});
|
||||
|
||||
it('ci-pipeline fails closed without a CI provider (no placeholder pass)', () => {
|
||||
const result = runGate({ command: 'anything', type: 'ci-pipeline' }, tmp, logPath, 30);
|
||||
expect(result.passed).toBe(false);
|
||||
expect(result.status).toBe('capability_failure');
|
||||
expect(result.capability_code).toBe('MACP_NO_CI_PIPELINE');
|
||||
expect(result.type).toBe('ci-pipeline');
|
||||
expect(result.output).not.toBe('CI pipeline gate placeholder');
|
||||
});
|
||||
|
||||
it('empty command is a typed capability failure, never a pass', () => {
|
||||
const result = runGate({ command: '' }, tmp, logPath, 30);
|
||||
expect(result.passed).toBe(false);
|
||||
expect(result.status).toBe('capability_failure');
|
||||
expect(result.capability_code).toBe('MACP_NO_COMMAND');
|
||||
});
|
||||
|
||||
it('ai-review gate parses JSON output', () => {
|
||||
const json = JSON.stringify({ stats: { blockers: 0, should_fix: 1 } });
|
||||
const result = runGate({ command: `echo '${json}'`, type: 'ai-review' }, tmp, logPath, 30);
|
||||
expect(result.passed).toBe(true);
|
||||
expect(result.blockers).toBe(0);
|
||||
expect(result.findings).toBe(1);
|
||||
});
|
||||
|
||||
it('ai-review gate fails on blockers', () => {
|
||||
const json = JSON.stringify({ stats: { blockers: 2 } });
|
||||
const result = runGate({ command: `echo '${json}'`, type: 'ai-review' }, tmp, logPath, 30);
|
||||
expect(result.passed).toBe(false);
|
||||
expect(result.blockers).toBe(2);
|
||||
});
|
||||
|
||||
it('ai-review gate with fail_on=any fails on any findings', () => {
|
||||
const json = JSON.stringify({ stats: { blockers: 0, should_fix: 1 } });
|
||||
const result = runGate(
|
||||
{ command: `echo '${json}'`, type: 'ai-review', fail_on: 'any' },
|
||||
tmp,
|
||||
logPath,
|
||||
30,
|
||||
);
|
||||
expect(result.passed).toBe(false);
|
||||
expect(result.fail_on).toBe('any');
|
||||
});
|
||||
|
||||
it('ai-review gate fails on invalid JSON output', () => {
|
||||
const result = runGate({ command: 'echo "not json"', type: 'ai-review' }, tmp, logPath, 30);
|
||||
expect(result.passed).toBe(false);
|
||||
expect(result.parse_error).toBeDefined();
|
||||
});
|
||||
|
||||
it('writes to log file', () => {
|
||||
runGate('echo logged', tmp, logPath, 30);
|
||||
const log = fs.readFileSync(logPath, 'utf-8');
|
||||
expect(log).toContain('COMMAND: echo logged');
|
||||
expect(log).toContain('logged');
|
||||
expect(log).toContain('EXIT:');
|
||||
});
|
||||
});
|
||||
|
||||
describe('runGates', () => {
|
||||
let tmp: string;
|
||||
let logPath: string;
|
||||
let eventsPath: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tmp = makeTmpDir();
|
||||
logPath = path.join(tmp, 'gates.log');
|
||||
eventsPath = path.join(tmp, 'events.ndjson');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('runs multiple gates and returns results', () => {
|
||||
const { allPassed, gateResults } = runGates(
|
||||
['echo one', 'echo two'],
|
||||
tmp,
|
||||
logPath,
|
||||
30,
|
||||
eventsPath,
|
||||
'task-1',
|
||||
);
|
||||
expect(allPassed).toBe(true);
|
||||
expect(gateResults).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('reports failure when any gate fails', () => {
|
||||
const { allPassed, gateResults } = runGates(
|
||||
['echo ok', 'exit 1'],
|
||||
tmp,
|
||||
logPath,
|
||||
30,
|
||||
eventsPath,
|
||||
'task-2',
|
||||
);
|
||||
expect(allPassed).toBe(false);
|
||||
expect(gateResults[0]!.passed).toBe(true);
|
||||
expect(gateResults[1]!.passed).toBe(false);
|
||||
});
|
||||
|
||||
it('emits events for each gate', () => {
|
||||
runGates(['echo test'], tmp, logPath, 30, eventsPath, 'task-3');
|
||||
const events = fs
|
||||
.readFileSync(eventsPath, 'utf-8')
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map((l) => JSON.parse(l));
|
||||
expect(events).toHaveLength(2); // started + passed
|
||||
expect(events[0].event_type).toBe('rail.check.started');
|
||||
expect(events[1].event_type).toBe('rail.check.passed');
|
||||
});
|
||||
|
||||
it('does not silently skip gates with empty command — they become capability failures', () => {
|
||||
const { gateResults, allPassed, state } = runGates(
|
||||
[{ command: '', type: 'mechanical' }, 'echo real'],
|
||||
tmp,
|
||||
logPath,
|
||||
30,
|
||||
eventsPath,
|
||||
'task-4',
|
||||
);
|
||||
expect(gateResults).toHaveLength(2);
|
||||
expect(gateResults[0]!.status).toBe('capability_failure');
|
||||
expect(gateResults[1]!.status).toBe('passed');
|
||||
expect(allPassed).toBe(false);
|
||||
expect(state).toBe('capability_failure');
|
||||
});
|
||||
|
||||
it('does not skip ci-pipeline even with empty command — typed capability failure', () => {
|
||||
const { gateResults, allPassed, state } = runGates(
|
||||
[{ command: '', type: 'ci-pipeline' }],
|
||||
tmp,
|
||||
logPath,
|
||||
30,
|
||||
eventsPath,
|
||||
'task-5',
|
||||
);
|
||||
expect(gateResults).toHaveLength(1);
|
||||
expect(gateResults[0]!.passed).toBe(false);
|
||||
expect(gateResults[0]!.status).toBe('capability_failure');
|
||||
expect(allPassed).toBe(false);
|
||||
expect(state).toBe('capability_failure');
|
||||
});
|
||||
|
||||
it('emits failed event with correct message', () => {
|
||||
runGates(['exit 42'], tmp, logPath, 30, eventsPath, 'task-6');
|
||||
const events = fs
|
||||
.readFileSync(eventsPath, 'utf-8')
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map((l) => JSON.parse(l));
|
||||
const failEvent = events.find(
|
||||
(e: Record<string, unknown>) => e.event_type === 'rail.check.failed',
|
||||
);
|
||||
expect(failEvent).toBeDefined();
|
||||
expect(failEvent.message).toContain('Gate failed (');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* RI-N2 / SDLC-D-035 fail-closed controls for the MACP gate runner.
|
||||
*
|
||||
* Invariant under test: `passed: true` occurs ONLY when a gate really executed
|
||||
* and really exited green (`status === 'passed'`). Absent capabilities,
|
||||
* manual sign-offs, and simulated runs are typed distinctly and can never
|
||||
* make the aggregate `passed`.
|
||||
*/
|
||||
describe('gate-runner fail-closed (RI-N2)', () => {
|
||||
let tmpDir: string;
|
||||
let logPath: string;
|
||||
let eventsPath: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = makeTmpDir();
|
||||
logPath = path.join(tmpDir, 'gate.log');
|
||||
eventsPath = path.join(tmpDir, 'events.ndjson');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function run(gates: unknown[], options?: { simulate?: boolean }) {
|
||||
return runGates(gates, tmpDir, logPath, 10, eventsPath, 'spec-task', options);
|
||||
}
|
||||
|
||||
// ─── positive controls ───────────────────────────────────────────────────
|
||||
|
||||
it('a really-executed green command gate still passes', () => {
|
||||
const result = run([{ command: 'exit 0', type: 'mechanical' }]);
|
||||
expect(result.gateResults[0]!.status).toBe('passed');
|
||||
expect(result.gateResults[0]!.passed).toBe(true);
|
||||
expect(result.allPassed).toBe(true);
|
||||
expect(result.state).toBe('passed');
|
||||
});
|
||||
|
||||
it('explicit simulate completes and types every result simulated', () => {
|
||||
const result = run([{ command: 'exit 0', type: 'mechanical' }, 'echo hello'], {
|
||||
simulate: true,
|
||||
});
|
||||
expect(result.gateResults).toHaveLength(2);
|
||||
for (const gate of result.gateResults) {
|
||||
expect(gate.status).toBe('simulated');
|
||||
expect(gate.passed).toBe(false);
|
||||
}
|
||||
expect(result.state).toBe('simulated');
|
||||
});
|
||||
|
||||
it('a really-executed red command gate fails with typed status failed', () => {
|
||||
const result = run([{ command: 'exit 3', type: 'mechanical' }]);
|
||||
expect(result.gateResults[0]!.status).toBe('failed');
|
||||
expect(result.gateResults[0]!.passed).toBe(false);
|
||||
expect(result.allPassed).toBe(false);
|
||||
expect(result.state).toBe('failed');
|
||||
});
|
||||
|
||||
// ─── negative controls — each asserts typed status AND aggregate not passed ──
|
||||
|
||||
it('an empty-command gate is a capability_failure, not skipped and not passed', () => {
|
||||
const result = run([{ command: '', type: 'mechanical' }]);
|
||||
// runGates must not silently skip it — it produces a typed result
|
||||
expect(result.gateResults).toHaveLength(1);
|
||||
const gate = result.gateResults[0]!;
|
||||
expect(gate.status).toBe('capability_failure');
|
||||
expect(gate.capability_code).toBe('MACP_NO_COMMAND');
|
||||
expect(gate.passed).toBe(false);
|
||||
// aggregate is not passed
|
||||
expect(result.allPassed).toBe(false);
|
||||
expect(result.state).toBe('capability_failure');
|
||||
expect(result.state).not.toBe('passed');
|
||||
});
|
||||
|
||||
it('a commandless ai-review gate is a typed MACP_NO_REVIEWER capability_failure', () => {
|
||||
const result = run([{ command: '', type: 'ai-review' }]);
|
||||
expect(result.gateResults[0]!.status).toBe('capability_failure');
|
||||
expect(result.gateResults[0]!.capability_code).toBe('MACP_NO_REVIEWER');
|
||||
expect(result.allPassed).toBe(false);
|
||||
expect(result.state).not.toBe('passed');
|
||||
});
|
||||
|
||||
it('a ci-pipeline gate without a provider implementation is a capability_failure, never a placeholder pass', () => {
|
||||
const result = run([{ command: '', type: 'ci-pipeline' }]);
|
||||
const gate = result.gateResults[0]!;
|
||||
expect(gate.status).toBe('capability_failure');
|
||||
expect(gate.capability_code).toBe('MACP_NO_CI_PIPELINE');
|
||||
expect(gate.passed).toBe(false);
|
||||
// the old false-success placeholder must be gone
|
||||
expect(gate.output).not.toBe('CI pipeline gate placeholder');
|
||||
expect(result.allPassed).toBe(false);
|
||||
expect(result.state).not.toBe('passed');
|
||||
});
|
||||
|
||||
it('a ci-pipeline gate fails closed even alongside an otherwise green run', () => {
|
||||
const result = run(['exit 0', { type: 'ci-pipeline', command: 'fake-ci' }]);
|
||||
expect(result.gateResults[1]!.status).toBe('capability_failure');
|
||||
expect(result.gateResults[0]!.status).toBe('passed');
|
||||
expect(result.allPassed).toBe(false);
|
||||
expect(result.state).toBe('capability_failure');
|
||||
});
|
||||
|
||||
it('a manual gate with no automation enters typed waiting — neither pass nor fail', () => {
|
||||
const result = run([{ type: 'manual' }]);
|
||||
const gate = result.gateResults[0]!;
|
||||
expect(gate.status).toBe('waiting');
|
||||
expect(gate.passed).toBe(false);
|
||||
expect(gate.exit_code).toBe(0);
|
||||
// aggregate is not passed while any gate is waiting
|
||||
expect(result.allPassed).toBe(false);
|
||||
expect(result.state).toBe('waiting');
|
||||
expect(result.state).not.toBe('passed');
|
||||
});
|
||||
|
||||
it('a simulated result can never make the aggregate passed', () => {
|
||||
const result = run(['exit 0', 'exit 0'], { simulate: true });
|
||||
expect(result.gateResults.every((g) => g.status === 'simulated')).toBe(true);
|
||||
expect(result.allPassed).toBe(false);
|
||||
expect(result.state).toBe('simulated');
|
||||
expect(result.state).not.toBe('passed');
|
||||
});
|
||||
|
||||
it('waiting dominates an otherwise green aggregate', () => {
|
||||
const result = run(['exit 0', { type: 'manual' }]);
|
||||
expect(result.allPassed).toBe(false);
|
||||
expect(result.state).toBe('waiting');
|
||||
});
|
||||
});
|
||||
|
||||
describe('runGate fail-closed (RI-N2)', () => {
|
||||
let tmpDir: string;
|
||||
let logPath: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = makeTmpDir();
|
||||
logPath = path.join(tmpDir, 'gate.log');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('simulate: true returns a typed simulated result without executing', () => {
|
||||
const result = runGate('this-command-does-not-exist-xyz', tmpDir, logPath, 10, {
|
||||
simulate: true,
|
||||
});
|
||||
expect(result.status).toBe('simulated');
|
||||
expect(result.passed).toBe(false);
|
||||
expect(result.exit_code).toBe(0);
|
||||
});
|
||||
|
||||
it('normal mode executes for real and types a green gate passed', () => {
|
||||
const result = runGate('echo ok', tmpDir, logPath, 10);
|
||||
expect(result.status).toBe('passed');
|
||||
expect(result.passed).toBe(true);
|
||||
expect(result.output).toContain('ok');
|
||||
});
|
||||
|
||||
it('a bare string gate normalizes to mechanical and executes', () => {
|
||||
const result = runGate('exit 7', tmpDir, logPath, 10);
|
||||
expect(result.type).toBe('mechanical');
|
||||
expect(result.status).toBe('failed');
|
||||
expect(result.passed).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -4,20 +4,7 @@ import { dirname } from 'node:path';
|
||||
|
||||
import { emitEvent } from './event-emitter.js';
|
||||
import { nowISO } from './event-emitter.js';
|
||||
import type { GateResult, GateStatus, RunGatesResult } from './types.js';
|
||||
|
||||
/** Typed reason stamped on every simulated gate result. */
|
||||
export const SIMULATED_GATE_REASON =
|
||||
'simulated execution (explicit simulate opt-in): gate was not evaluated by a real implementation';
|
||||
|
||||
/** Options for gate execution (RI-N2 fail-closed / explicit simulation). */
|
||||
export interface RunGateOptions {
|
||||
/**
|
||||
* Explicit caller opt-in to simulation. Simulated gates are NOT executed;
|
||||
* every result is typed `simulated` and never satisfies anything.
|
||||
*/
|
||||
simulate?: boolean;
|
||||
}
|
||||
import type { GateResult } from './types.js';
|
||||
|
||||
export interface NormalizedGate {
|
||||
command: string;
|
||||
@@ -116,91 +103,36 @@ export function countAIFindings(parsedOutput: unknown): { blockers: number; tota
|
||||
return { blockers, total };
|
||||
}
|
||||
|
||||
function simulatedResult(gateEntry: NormalizedGate): GateResult {
|
||||
return {
|
||||
command: gateEntry.command,
|
||||
exit_code: 0,
|
||||
type: gateEntry.type,
|
||||
output: SIMULATED_GATE_REASON,
|
||||
timed_out: false,
|
||||
passed: false,
|
||||
status: 'simulated',
|
||||
reason: SIMULATED_GATE_REASON,
|
||||
};
|
||||
}
|
||||
|
||||
function capabilityFailureResult(
|
||||
gateEntry: NormalizedGate,
|
||||
code: GateResult['capability_code'],
|
||||
reason: string,
|
||||
): GateResult {
|
||||
return {
|
||||
command: gateEntry.command,
|
||||
exit_code: 1,
|
||||
type: gateEntry.type,
|
||||
output: '',
|
||||
timed_out: false,
|
||||
passed: false,
|
||||
status: 'capability_failure',
|
||||
capability_code: code,
|
||||
reason,
|
||||
};
|
||||
}
|
||||
|
||||
function waitingResult(gateEntry: NormalizedGate, reason: string): GateResult {
|
||||
return {
|
||||
command: gateEntry.command,
|
||||
exit_code: 0,
|
||||
type: gateEntry.type,
|
||||
output: '',
|
||||
timed_out: false,
|
||||
passed: false,
|
||||
status: 'waiting',
|
||||
capability_code: 'MACP_AUTHORITY_REQUIRED',
|
||||
reason,
|
||||
};
|
||||
}
|
||||
|
||||
export function runGate(
|
||||
gate: unknown,
|
||||
cwd: string,
|
||||
logPath: string,
|
||||
timeoutSec: number,
|
||||
options: RunGateOptions = {},
|
||||
): GateResult {
|
||||
const gateEntry = normalizeGate(gate);
|
||||
const gateType = gateEntry.type;
|
||||
const command = gateEntry.command;
|
||||
|
||||
// Explicit simulation only: never executes, typed simulated, never satisfying.
|
||||
if (options.simulate) {
|
||||
return simulatedResult(gateEntry);
|
||||
}
|
||||
|
||||
// Fail closed: no CI provider implementation exists in @mosaicstack/macp,
|
||||
// so a ci-pipeline gate is an absent capability — never a placeholder pass.
|
||||
if (gateType === 'ci-pipeline') {
|
||||
return capabilityFailureResult(
|
||||
gateEntry,
|
||||
'MACP_NO_CI_PIPELINE',
|
||||
`ci-pipeline gate '${gateEntry.command || gateType}' has no CI provider implementation wired — refusing placeholder pass`,
|
||||
);
|
||||
return {
|
||||
command,
|
||||
exit_code: 0,
|
||||
type: gateType,
|
||||
output: 'CI pipeline gate placeholder',
|
||||
timed_out: false,
|
||||
passed: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (!command) {
|
||||
// A manual gate with no automation waits for human sign-off: not pass, not fail.
|
||||
if (gateType === 'manual') {
|
||||
return waitingResult(
|
||||
gateEntry,
|
||||
`manual gate has no automation — waiting for human sign-off (type: ${gateType})`,
|
||||
);
|
||||
}
|
||||
// Any other commandless gate is an absent capability — never a vacuous pass.
|
||||
return capabilityFailureResult(
|
||||
gateEntry,
|
||||
gateType === 'ai-review' ? 'MACP_NO_REVIEWER' : 'MACP_NO_COMMAND',
|
||||
`gate of type '${gateType}' has no command to execute — refusing empty-command pass`,
|
||||
);
|
||||
return {
|
||||
command: '',
|
||||
exit_code: 0,
|
||||
type: gateType,
|
||||
output: '',
|
||||
timed_out: false,
|
||||
passed: true,
|
||||
};
|
||||
}
|
||||
|
||||
const { exitCode, output, timedOut } = runShell(command, cwd, logPath, timeoutSec);
|
||||
@@ -211,12 +143,10 @@ export function runGate(
|
||||
output,
|
||||
timed_out: timedOut,
|
||||
passed: false,
|
||||
status: 'failed',
|
||||
};
|
||||
|
||||
if (gateType !== 'ai-review') {
|
||||
result.passed = exitCode === 0;
|
||||
result.status = result.passed ? 'passed' : 'failed';
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -240,7 +170,6 @@ export function runGate(
|
||||
} else {
|
||||
result.passed = exitCode === 0 && blockers === 0 && !timedOut && parseError === undefined;
|
||||
}
|
||||
result.status = result.passed ? 'passed' : 'failed';
|
||||
|
||||
result.fail_on = failOn;
|
||||
result.blockers = blockers;
|
||||
@@ -262,19 +191,16 @@ export function runGates(
|
||||
timeoutSec: number,
|
||||
eventsPath: string,
|
||||
taskId: string,
|
||||
options: RunGateOptions = {},
|
||||
): RunGatesResult {
|
||||
): { allPassed: boolean; gateResults: GateResult[] } {
|
||||
let allPassed = true;
|
||||
const gateResults: GateResult[] = [];
|
||||
let hasCapabilityFailure = false;
|
||||
let hasSimulated = false;
|
||||
let hasFailed = false;
|
||||
let hasWaiting = false;
|
||||
|
||||
for (const gate of gates) {
|
||||
const gateEntry = normalizeGate(gate);
|
||||
const gateCmd = gateEntry.command;
|
||||
if (!gateCmd && gateEntry.type !== 'ci-pipeline') continue;
|
||||
|
||||
const label = gateCmd || gateEntry.type;
|
||||
// NOTE: no silent skip — every gate produces a typed result (RI-N2).
|
||||
emitEvent(
|
||||
eventsPath,
|
||||
'rail.check.started',
|
||||
@@ -283,10 +209,10 @@ export function runGates(
|
||||
'quality-gate',
|
||||
`Running gate: ${label}`,
|
||||
);
|
||||
const result = runGate(gate, cwd, logPath, timeoutSec, options);
|
||||
const result = runGate(gate, cwd, logPath, timeoutSec);
|
||||
gateResults.push(result);
|
||||
|
||||
if (result.status === 'passed') {
|
||||
if (result.passed) {
|
||||
emitEvent(
|
||||
eventsPath,
|
||||
'rail.check.passed',
|
||||
@@ -298,46 +224,7 @@ export function runGates(
|
||||
continue;
|
||||
}
|
||||
|
||||
if (result.status === 'waiting') {
|
||||
hasWaiting = true;
|
||||
emitEvent(
|
||||
eventsPath,
|
||||
'rail.check.waiting',
|
||||
taskId,
|
||||
'gated',
|
||||
'quality-gate',
|
||||
`Gate waiting: ${label} — ${result.reason ?? 'manual gate awaits sign-off'}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (result.status === 'simulated') {
|
||||
hasSimulated = true;
|
||||
emitEvent(
|
||||
eventsPath,
|
||||
'rail.check.simulated',
|
||||
taskId,
|
||||
'gated',
|
||||
'quality-gate',
|
||||
`Gate simulated (non-satisfying): ${label}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (result.status === 'capability_failure') {
|
||||
hasCapabilityFailure = true;
|
||||
emitEvent(
|
||||
eventsPath,
|
||||
'rail.check.failed',
|
||||
taskId,
|
||||
'gated',
|
||||
'quality-gate',
|
||||
`Gate capability failure (${result.capability_code ?? 'MACP_NO_PROVIDER'}): ${label} — ${result.reason ?? 'required capability is absent'}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
hasFailed = true;
|
||||
allPassed = false;
|
||||
let message: string;
|
||||
if (result.timed_out) {
|
||||
message = `Gate timed out after ${timeoutSec}s: ${label}`;
|
||||
@@ -349,15 +236,5 @@ export function runGates(
|
||||
emitEvent(eventsPath, 'rail.check.failed', taskId, 'gated', 'quality-gate', message);
|
||||
}
|
||||
|
||||
const state: GateStatus = hasCapabilityFailure
|
||||
? 'capability_failure'
|
||||
: hasSimulated
|
||||
? 'simulated'
|
||||
: hasFailed
|
||||
? 'failed'
|
||||
: hasWaiting
|
||||
? 'waiting'
|
||||
: 'passed';
|
||||
|
||||
return { allPassed: state === 'passed', gateResults, state };
|
||||
return { allPassed, gateResults };
|
||||
}
|
||||
|
||||
@@ -6,13 +6,11 @@ export type {
|
||||
DependsOnPolicy,
|
||||
GateType,
|
||||
GateFailOn,
|
||||
GateStatus,
|
||||
GateEntry,
|
||||
Task,
|
||||
EventType,
|
||||
MACPEvent,
|
||||
GateResult,
|
||||
RunGatesResult,
|
||||
TaskResult,
|
||||
ProviderMeta,
|
||||
ProviderRegistry,
|
||||
@@ -20,11 +18,6 @@ export type {
|
||||
|
||||
export { CredentialError } from './types.js';
|
||||
|
||||
// Typed fail-closed capability errors (RI-N2, SDLC-D-035)
|
||||
export { MACP_ERROR_CODES, MACPCapabilityError } from './errors.js';
|
||||
|
||||
export type { MacpErrorCode } from './errors.js';
|
||||
|
||||
// Credential resolver
|
||||
export {
|
||||
DEFAULT_CREDENTIALS_DIR,
|
||||
@@ -42,16 +35,9 @@ export {
|
||||
export type { ResolveCredentialsOptions } from './credential-resolver.js';
|
||||
|
||||
// Gate runner
|
||||
export {
|
||||
normalizeGate,
|
||||
runShell,
|
||||
countAIFindings,
|
||||
runGate,
|
||||
runGates,
|
||||
SIMULATED_GATE_REASON,
|
||||
} from './gate-runner.js';
|
||||
export { normalizeGate, runShell, countAIFindings, runGate, runGates } from './gate-runner.js';
|
||||
|
||||
export type { NormalizedGate, RunGateOptions } from './gate-runner.js';
|
||||
export type { NormalizedGate } from './gate-runner.js';
|
||||
|
||||
// Risk-floor (agent reflection loop — diff review classifier)
|
||||
export { evaluateRiskFloor, DEFAULT_RISK_THRESHOLD } from './risk-floor.js';
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import type { MacpErrorCode } from './errors.js';
|
||||
|
||||
/** Task status values. */
|
||||
export type TaskStatus = 'pending' | 'running' | 'gated' | 'completed' | 'failed' | 'escalated';
|
||||
|
||||
@@ -19,17 +17,7 @@ export type DispatchMode = 'yolo' | 'acp' | 'exec';
|
||||
export type DependsOnPolicy = 'all' | 'any' | 'all_terminal';
|
||||
|
||||
/** Quality gate type. */
|
||||
export type GateType = 'mechanical' | 'ai-review' | 'ci-pipeline' | 'manual';
|
||||
|
||||
/**
|
||||
* Typed execution state of a gate — closed set (RI-N2, SDLC-D-035).
|
||||
*
|
||||
* Only `passed` means "really executed and green". `simulated` is produced
|
||||
* exclusively under an explicit simulate opt-in and never satisfies anything.
|
||||
* `capability_failure` means a required executor/provider/command was absent.
|
||||
* `waiting` means a manual gate awaits human sign-off (neither pass nor fail).
|
||||
*/
|
||||
export type GateStatus = 'passed' | 'failed' | 'simulated' | 'waiting' | 'capability_failure';
|
||||
export type GateType = 'mechanical' | 'ai-review' | 'ci-pipeline';
|
||||
|
||||
/** Gate fail_on mode. */
|
||||
export type GateFailOn = 'blocker' | 'any';
|
||||
@@ -79,9 +67,7 @@ export type EventType =
|
||||
| 'task.retry.scheduled'
|
||||
| 'rail.check.started'
|
||||
| 'rail.check.passed'
|
||||
| 'rail.check.failed'
|
||||
| 'rail.check.waiting'
|
||||
| 'rail.check.simulated';
|
||||
| 'rail.check.failed';
|
||||
|
||||
/** Structured event record. */
|
||||
export interface MACPEvent {
|
||||
@@ -102,14 +88,7 @@ export interface GateResult {
|
||||
type: string;
|
||||
output: string;
|
||||
timed_out: boolean;
|
||||
/** Back-compat boolean view — true ONLY when `status === 'passed'`. */
|
||||
passed: boolean;
|
||||
/** Typed discriminator — the authoritative gate outcome (RI-N2). */
|
||||
status: GateStatus;
|
||||
/** Typed capability error code, set when `status === 'capability_failure'`. */
|
||||
capability_code?: MacpErrorCode;
|
||||
/** Why a non-executed state (simulated/waiting/capability_failure) was reached. */
|
||||
reason?: string;
|
||||
fail_on?: string;
|
||||
blockers?: number;
|
||||
findings?: number;
|
||||
@@ -117,22 +96,6 @@ export interface GateResult {
|
||||
parse_error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregate outcome of `runGates` (RI-N2).
|
||||
*
|
||||
* `state` is the typed aggregate: it is `passed` only when every gate really
|
||||
* executed green. A `simulated` result makes the aggregate `simulated` (never
|
||||
* `passed`); a `waiting` manual gate keeps the aggregate `waiting`; a missing
|
||||
* capability makes it `capability_failure`. `allPassed` is exactly
|
||||
* `state === 'passed'`, so a simulated or waiting result can never satisfy a
|
||||
* dependency, acceptance criterion, gate, merge, or release check.
|
||||
*/
|
||||
export interface RunGatesResult {
|
||||
allPassed: boolean;
|
||||
gateResults: GateResult[];
|
||||
state: GateStatus;
|
||||
}
|
||||
|
||||
/** Result from a completed task. */
|
||||
export interface TaskResult {
|
||||
task_id: string;
|
||||
|
||||
Reference in New Issue
Block a user