diff --git a/CHANGELOG.md b/CHANGELOG.md index 534d48bb8..3a4650677 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## 1.0.18-beta.0 — 2026-11-30 +### Fixes + +- Add a global `--no-color` flag, the same as `NO_COLOR=1`, accepted before or after any command; `failproofai policies` already honors `NO_COLOR` (#1067, from #695, #700, #848, fixes #688) + ### Docs - The keys and settings docs explain personal and organization keys, the rule that an organization key can no longer be created or edited with permission to manage people, keys or settings (an older key that has one keeps working and is marked **too broad**), the **keys may live for** limit with its 15-day expiry reminder, extending a working key without changing its secret and renewing an expired one, and that the allowed sign-ins list also governs AI tool connections, the Slack app and personal keys (FailproofAI/agenteye#1882, #1065, from #1064) diff --git a/__tests__/e2e/cli/cli-args.e2e.test.ts b/__tests__/e2e/cli/cli-args.e2e.test.ts index bfc76f631..26d9bcf5b 100644 --- a/__tests__/e2e/cli/cli-args.e2e.test.ts +++ b/__tests__/e2e/cli/cli-args.e2e.test.ts @@ -12,7 +12,7 @@ import { createHash } from "node:crypto"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { runCli, assertCleanError, assertSuccess } from "../helpers/cli-runner"; +import { runCli, runCliWithTTY, assertCleanError, assertSuccess } from "../helpers/cli-runner"; // ── Top-level flags ─────────────────────────────────────────────────────────── @@ -58,6 +58,7 @@ describe("top-level: --help", () => { expect(result.stdout).toContain("policies"); // The half that replaced every inlined flag. expect(result.stdout).toContain("failproofai help "); + expect(result.stdout).toContain("--no-color"); }); it("-h shorthand prints help and exits 0", () => { @@ -263,6 +264,24 @@ describe("policies: list (default)", () => { expect(result.stdout).toMatch(HEADER); }); + it("accepts --no-color after the subcommand", () => { + const baseline = runCliWithTTY("policies"); + assertSuccess(baseline); + expect(baseline.stdout).toMatch(/\x1B\[/); + + const result = runCliWithTTY("policies", "--no-color"); + assertSuccess(result); + expect(result.stdout).toMatch(HEADER); + expect(result.stdout).not.toMatch(/\x1B\[/); + }); + + it("accepts --no-color before the subcommand", () => { + const result = runCliWithTTY("--no-color", "policies"); + assertSuccess(result); + expect(result.stdout).toMatch(HEADER); + expect(result.stdout).not.toMatch(/\x1B\[/); + }); + it("rejects unexpected positional argument", () => { const result = runCli("policies", "hi"); assertCleanError(result, "Unexpected argument: hi"); @@ -285,6 +304,7 @@ describe("policies: --help", () => { assertSuccess(result); expect(result.stdout).toContain("--install"); expect(result.stdout).toContain("--uninstall"); + expect(result.stdout).toContain("--no-color"); }); it("-h shorthand prints policies help", () => { diff --git a/__tests__/e2e/helpers/cli-runner.ts b/__tests__/e2e/helpers/cli-runner.ts index fcb74595e..490c0062d 100644 --- a/__tests__/e2e/helpers/cli-runner.ts +++ b/__tests__/e2e/helpers/cli-runner.ts @@ -6,7 +6,7 @@ */ import { spawnSync } from "node:child_process"; import { resolve, dirname } from "node:path"; -import { fileURLToPath } from "node:url"; +import { fileURLToPath, pathToFileURL } from "node:url"; import { existsSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { afterAll, expect } from "vitest"; @@ -44,22 +44,38 @@ export interface CliRunResult { /** * Invoke `failproofai <...args>` and return stdout, stderr, exitCode. * + * @param stdoutIsTTY - Whether captured stdout should present as a terminal * @param args - CLI arguments to pass to the binary */ -export function runCli(...args: string[]): CliRunResult { +function invokeCli(stdoutIsTTY: boolean, args: string[]): CliRunResult { const binaryPath = getBinaryPath(); if (!existsSync(binaryPath)) { throw new Error(`Binary not found: ${binaryPath}`); } - const result = spawnSync("bun", [binaryPath, ...args], { - env: { - ...process.env, - HOME: ISOLATED_HOME, - USERPROFILE: ISOLATED_HOME, - FAILPROOFAI_TELEMETRY_DISABLED: "1", - }, + const env: NodeJS.ProcessEnv = { + ...process.env, + HOME: ISOLATED_HOME, + USERPROFILE: ISOLATED_HOME, + FAILPROOFAI_TELEMETRY_DISABLED: "1", + }; + if (stdoutIsTTY) delete env.NO_COLOR; + + const commandArgs = stdoutIsTTY + ? [ + "--eval", + `Object.defineProperty(process.stdout, "isTTY", { value: true });\n` + + `Object.defineProperty(process.stdout, "columns", { value: 80 });\n` + + `await import(${JSON.stringify(pathToFileURL(binaryPath).href)});`, + "--", + binaryPath, + ...args, + ] + : [binaryPath, ...args]; + + const result = spawnSync("bun", commandArgs, { + env, encoding: "utf8", timeout: 15_000, }); @@ -71,6 +87,16 @@ export function runCli(...args: string[]): CliRunResult { }; } +/** Invoke the CLI with its normal captured, non-TTY stdout. */ +export function runCli(...args: string[]): CliRunResult { + return invokeCli(false, args); +} + +/** Invoke the CLI while presenting captured stdout as an 80-column TTY. */ +export function runCliWithTTY(...args: string[]): CliRunResult { + return invokeCli(true, args); +} + // ── Assertion helpers ───────────────────────────────────────────────────────── export function assertCleanError(result: CliRunResult, expectedMessage: string): void { diff --git a/__tests__/hooks/manager-no-color.test.ts b/__tests__/hooks/manager-no-color.test.ts new file mode 100644 index 000000000..51f8fa59e --- /dev/null +++ b/__tests__/hooks/manager-no-color.test.ts @@ -0,0 +1,94 @@ +// @vitest-environment node +// +// `failproofai policies` (listHooks) once hardcoded ANSI escapes in +// src/hooks/manager.ts, so it printed color even when NO_COLOR=1 / --no-color +// was set under a TTY (issue #688). The listing now renders through tui.ts, +// whose `printBlock` strips every escape when `colorsEnabled` says no. +// +// These assert the gate both ways: colored when a TTY has color on, and zero +// ESC bytes the moment NO_COLOR is set — with stdout.isTTY forced true so the +// off-TTY short-circuit is not what is being measured. +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { listHooks } from "@/src/hooks/manager"; + +const ESC = "\x1B["; + +function policySource(hookName: string): string { + return ` + import { customPolicies, allow } from "failproofai"; + customPolicies.add({ + name: ${JSON.stringify(hookName)}, + description: "test policy", + match: { events: ["PreToolUse"] }, + fn: async () => allow(), + }); + `; +} + +describe("listHooks — NO_COLOR / --no-color gating", () => { + let tmp: string; + let emptyHome: string; + let packRoot: string; + let out: string[]; + let origIsTTY: boolean | undefined; + + beforeEach(() => { + tmp = mkdtempSync(join(tmpdir(), "fp-nocolor-")); + emptyHome = mkdtempSync(join(tmpdir(), "fp-nocolor-home-")); + packRoot = mkdtempSync(join(tmpdir(), "fp-nocolor-packs-")); + vi.stubEnv("HOME", emptyHome); + vi.stubEnv("USERPROFILE", emptyHome); + // The listing mirrors convention policies into the user config and reads + // installed packs; keep both off the real machine. + vi.stubEnv("FAILPROOFAI_HOME", join(emptyHome, ".failproofai")); + vi.stubEnv("FAILPROOFAI_PACK_DIR", packRoot); + // Seed a convention policy so the listing has a row of its own to color. + const dir = join(tmp, ".failproofai", "policies"); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "team-policies.mjs"), policySource("team-rule"), "utf8"); + + out = []; + vi.spyOn(process.stdout, "write").mockImplementation((chunk: unknown) => { + out.push(String(chunk)); + return true; + }); + // Color is off for anything but a TTY; force one so we measure the + // NO_COLOR gate, not the isTTY gate. + origIsTTY = process.stdout.isTTY; + Object.defineProperty(process.stdout, "isTTY", { value: true, configurable: true }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + Object.defineProperty(process.stdout, "isTTY", { value: origIsTTY, configurable: true }); + for (const dir of [tmp, emptyHome, packRoot]) rmSync(dir, { recursive: true, force: true }); + }); + + it("emits ANSI escapes on a color TTY", async () => { + // Register NO_COLOR with vi.stubEnv (empty = unset) so afterEach's + // vi.unstubAllEnvs() restores the worker's original value instead of + // leaving it deleted for later tests. + vi.stubEnv("NO_COLOR", ""); + await listHooks(tmp); + const text = out.join(""); + expect(text).toContain("Policies"); + expect(text).toContain("team-policies.mjs"); + expect(text).toContain(ESC); + }); + + it("emits zero ESC bytes when NO_COLOR is set", async () => { + vi.stubEnv("NO_COLOR", "1"); + await listHooks(tmp); + const text = out.join(""); + expect(text).not.toContain(ESC); + // The same rows still render as plain text — the header and the convention + // policy's file — proving only the color was dropped. + expect(text).toContain("Policies"); + expect(text).toContain("team-policies.mjs"); + }); +}); diff --git a/__tests__/hooks/no-color.test.ts b/__tests__/hooks/no-color.test.ts new file mode 100644 index 000000000..6c5306434 --- /dev/null +++ b/__tests__/hooks/no-color.test.ts @@ -0,0 +1,60 @@ +// @vitest-environment node +// +// NO_COLOR=1 `failproofai policies` once emitted ANSI (issue #688): manager.ts +// hardcoded escapes, and there was no --no-color flag at all. Everything now +// routes through tui.ts, and the bin spells the env var as a flag. These lock +// the gate, the absence of hardcoded escapes, and where the flag is consumed; +// __tests__/e2e/cli/cli-args.e2e.test.ts runs the flag end to end. +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { colorsEnabled, paint } from "../../src/hooks/tui"; + +describe("NO_COLOR support", () => { + const saved = process.env.NO_COLOR; + + beforeEach(() => { + delete process.env.NO_COLOR; + }); + + afterEach(() => { + if (saved === undefined) delete process.env.NO_COLOR; + else process.env.NO_COLOR = saved; + }); + + it("colorsEnabled reports false for a TTY when NO_COLOR is set", () => { + const tty = { isTTY: true } as typeof process.stdout; + expect(colorsEnabled(tty)).toBe(true); + process.env.NO_COLOR = "1"; + expect(colorsEnabled(tty)).toBe(false); + }); + + it("the painter the warning now uses emits no ESC bytes under NO_COLOR", () => { + const text = "Warning: Failproof AI hooks are also installed at user (user)."; + expect(paint(true).warn(text)).toContain("\x1B["); + process.env.NO_COLOR = "1"; + expect(paint(!process.env.NO_COLOR).warn(text)).toBe(text); + }); + + it("the bin consumes --no-color before every dispatch, without loading tui.ts", () => { + // Inline on purpose. Importing tui.ts at the top of the bin reorders the + // bundle, which renames the builtin policies' `ctx` parameters and changes + // the audit cache key, and it would load the kit on every --hook call. + const bin = readFileSync(resolve(__dirname, "..", "..", "bin", "failproofai.mjs"), "utf-8"); + const flag = bin.indexOf('args.includes("--no-color")'); + const aliases = bin.indexOf("// ── one noun for policies"); + const hook = bin.indexOf('const hookIdx = args.indexOf("--hook")'); + expect(flag).toBeGreaterThan(-1); + expect(aliases).toBeGreaterThan(flag); + expect(hook).toBeGreaterThan(flag); + expect(bin.slice(0, hook)).not.toMatch(/import\([^)]*src\/hooks\/tui/); + }); + + it("manager.ts holds no hardcoded ANSI escapes - the 16-site bug stays dead", () => { + const src = readFileSync( + resolve(__dirname, "..", "..", "src", "hooks", "manager.ts"), + "utf-8", + ); + expect(src.match(/\\x1[Bb]\[|\\u001[bB]\[|\\033\[/)).toBeNull(); + }); +}); diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index e79a804d7..af3c4d1a3 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -6,6 +6,7 @@ * --hook Hook event from Claude Code (minimal startup latency) * --version / -v Print version and exit * --help / -h Show usage and exit + * --no-color Suppress ANSI color output * policies Manage policies (list / install / uninstall) * (default) Launch production dashboard */ @@ -34,6 +35,15 @@ if (!process.env.FAILPROOFAI_DIST_PATH) { const args = process.argv.slice(2); +// Global presentation flag: consume it before aliases, help routing, and +// subcommand validation so it works in any position without loading the TUI. +if (args.includes("--no-color")) { + process.env.NO_COLOR = "1"; + for (let i = args.length - 1; i >= 0; i--) { + if (args[i] === "--no-color") args.splice(i, 1); + } +} + // ── one noun for policies ────────────────────────────────────────────────── // `policies`, `policy` and `pack` were three commands for one idea, two of them // a single letter apart and doing unrelated things. They are now three @@ -420,6 +430,7 @@ async function runCli() { ["", "hermes, openclaw, factory, devin, antigravity, goose"], ["--scope ", "user, project, local (default user); all when removing"], ["--beta", "Include beta policies"], + ["--no-color", "Plain output, same as NO_COLOR=1, for any command"], ["-c, --custom ", "With --install, add a custom policy file (repeatable)"], ["", "--uninstall -c removes every custom policy file"], ["--releases", "With show: list its releases, and which one is here"], @@ -584,7 +595,7 @@ async function runCli() { ]), "", `Run ${kit.cmd("failproofai help ")} for its options, ${kit.cmd("failproofai -v")} for the version.`, - "docs.befailproof.ai · discord.befailproof.ai", + "docs.befailproof.ai · discord.befailproof.ai · --no-color: plain output", ]); } process.exit(0); diff --git a/docs/reference/failproof-cli.mdx b/docs/reference/failproof-cli.mdx index cc97aa58b..81d079e66 100644 --- a/docs/reference/failproof-cli.mdx +++ b/docs/reference/failproof-cli.mdx @@ -79,6 +79,7 @@ Run `failproofai` without arguments to open the local policy dashboard. | `failproofai --version` | Print the installed package version | | `failproofai --help` | Show commands and global usage | | `failproofai help ` | Show one command's options and examples, same as `failproofai --help` | +| `failproofai --no-color` | Print without color, the same as `NO_COLOR=1`; goes before or after any command | ## Configuration flags @@ -174,7 +175,7 @@ Use configuration files for persistent machine behavior. Environment variables a | `FAILPROOFAI_NO_DOWNLOAD=1` | Refuse to fetch packs and daemon binaries; what is installed keeps enforcing | | `FAILPROOFAI_PACK_BASE_URL` | Fetch packs from a mirror instead of `github.com` | | `FAILPROOFAI__EXTRA_PATHS` | Replace configured extra capture paths for one harness | -| `NO_COLOR` | Disable colored terminal output | +| `NO_COLOR` | Disable colored terminal output; `--no-color` does the same for one command | Agent-specific home variables such as `CLAUDE_PROJECTS_PATH`, `CURSOR_HOME`, `HERMES_HOME`, and `OPENCLAW_HOME` override where Failproof AI discovers local sessions for that harness.