From 21c24d3218dfd7501479c5aa629cf6458c26b412 Mon Sep 17 00:00:00 2001 From: Dragan Spiridonov Date: Sun, 22 Nov 2026 20:46:02 +0100 Subject: [PATCH] fix(learning-loop): help/list runs are not verifiers; never store part of a secret (#5067) (#5068) * fix(learning-loop): help/list runs are not verifiers; never store part of a secret An edit followed by a test command that only printed help or listed tests (`npm test --help`, `npx vitest list`, `npx jest --listTests`, `pytest --collect-only`, `cargo test --no-run`, `go test -list .`) was recorded as verified-success: classify() matched the command head and ignored the rest, and those commands exit 0 without running a check. - classify(): a verifier segment whose bash words ask for help, version, a listing, a config dump, a dry run or a compile-only build is not a verifier; `vitest list` / `cargo nextest list` likewise. Words are split as bash does, so a quoted argument that contains `--help` (a test-name pattern) still verifies. A command with a shell comment is refused: `npm run build # && npm test` ran only the build. - Verifier evidence is screened for secret shapes; a command carrying one keeps its kind and outcome and is stored as `[redacted]`. Evidence reaches SONA feedback, the ledger and learned lessons. - taskText() screened only the first 300 characters, after the cut, so a key the cut split was stored in part (`ghp_ABCDEFGHIJKLMNO`). It now screens the kept text plus 1 KiB, cuts at a word boundary so a long key (JWT) is dropped whole, and reads at most 64 KiB of the prompt (32M-character prompt: ~6 ms, against ~1.4 s unbounded). Regenerated both learning-loop.cjs copies. helpers.manifest.json needs a maintainer re-sign for the new bytes. Co-Authored-By: Ruflo & AQE Claude-Session: https://claude.ai/code/session_01GLQCdgnsuwts6j51rwcqgB * fix(learning-loop): per-runner no-run flags, raw screening, SONA skips [redacted] (0.17.5) Third adversarial review of #5068: - More commands that exit 0 without a check are not verifiers: tsc -v, --listFilesOnly, -b --dry, --init; eslint -v, --env-info; vitest/jest -v; make -n/-q (and clusters); go test -c/-n; dotnet test -t; pytest --fixtures/--markers/--setup-plan; npm/pnpm/yarn/bun --if-present. Flags are read for the program actually run (past npx, pnpm exec, python -m, uv/poetry run), so `pytest -v` stays a run and `jest --testNamePattern vitest list` is not taken for `vitest list`. - Bash removes a backslash-newline outright; classify() now joins without a space (`--ver\sion` is --version). An escaped space no longer starts a word, so `a\ #b` is not a comment. - shellWords()/hasComment() move to hooks/loop/words.ts; narrows() uses them, so a partly quoted --passWithNoTests still taints (ADR-503). - Evidence and task text are screened as given as well as normalised: a line separator or control character inside a key hid it from the folded screen. A kept key-block header ("-----BEGIN") is refused. - Ingest counts a task stored as [redacted] and never trains SONA with it (it learned `coder:redacted`). - ruflo-mods 0.17.5 with a CHANGELOG entry (version-bump check). Every guard is covered: reverting any one of the 12 fails a test. Co-Authored-By: Ruflo & AQE Claude-Session: https://claude.ai/code/session_01GLQCdgnsuwts6j51rwcqgB * chore(helpers): re-sign helpers.manifest.json for the rebuilt learning-loop.cjs (#5067) Rebuilt learning-loop.cjs from source with build-learning-loop-helper.mjs; the bytes match the committed bundle (sha256 0a39ee1d50d3349d...). Co-Authored-By: RuFlo --------- Co-authored-by: r Co-authored-by: RuFlo --- .claude/helpers/learning-loop.cjs | 127 +++++++++++++++++- plugins/ruflo-mods/.claude-plugin/plugin.json | 2 +- plugins/ruflo-mods/CHANGELOG.md | 6 + plugins/ruflo-mods/hooks/loop/record.ts | 35 ++++- plugins/ruflo-mods/hooks/loop/taint.ts | 6 +- plugins/ruflo-mods/hooks/loop/verifier.ts | 74 +++++++++- plugins/ruflo-mods/hooks/loop/words.ts | 64 +++++++++ plugins/ruflo-mods/scripts/smoke.sh | 6 +- .../cli/.claude/helpers/helpers.manifest.json | 4 +- .../cli/.claude/helpers/learning-loop.cjs | 127 +++++++++++++++++- .../mods/mods-learning-loop-defences.test.ts | 15 +++ .../__tests__/mods/mods-learning-loop.test.ts | 93 ++++++++++++- .../cli/src/memory/verified-outcomes.ts | 10 ++ 13 files changed, 538 insertions(+), 31 deletions(-) create mode 100644 plugins/ruflo-mods/hooks/loop/words.ts diff --git a/.claude/helpers/learning-loop.cjs b/.claude/helpers/learning-loop.cjs index a05143d05f..df55d4bc7e 100644 --- a/.claude/helpers/learning-loop.cjs +++ b/.claude/helpers/learning-loop.cjs @@ -108,6 +108,57 @@ function utf8Bytes(text) { return n; } +// plugins/ruflo-mods/hooks/loop/words.ts +function shellWords(segment) { + const words2 = []; + let word = ""; + let quoted = false; + let quote = ""; + const flush = () => { + if (word !== "" || quoted) words2.push(word); + word = ""; + quoted = false; + }; + for (let i = 0; i < segment.length; i++) { + const c = segment[i]; + if (quote === "'") { + if (c === "'") quote = ""; + else word += c; + } else if (quote === '"') { + if (c === '"') quote = ""; + else if (c === "\\" && i + 1 < segment.length && '$`"\\'.includes(segment[i + 1])) word += segment[++i]; + else word += c; + } else if (c === "'" || c === '"') { + quote = c; + quoted = true; + } else if (c === "\\" && i + 1 < segment.length) word += segment[++i]; + else if (/\s/.test(c)) flush(); + else word += c; + } + flush(); + return words2; +} +function hasComment(command) { + let quote = ""; + let wordStart = true; + for (let i = 0; i < command.length; i++) { + const c = command[i]; + if (quote !== "") { + if (c === quote) quote = ""; + else if (c === "\\" && quote === '"') i++; + } else if (c === "'" || c === '"') { + quote = c; + wordStart = false; + } else if (c === "\\") { + i++; + wordStart = false; + } else if (/\s/.test(c)) wordStart = true; + else if (c === "#" && wordStart) return true; + else wordStart = false; + } + return false; +} + // plugins/ruflo-mods/hooks/loop/taint.ts var TEST_FILE = /(?:\.(?:test|spec)\.[A-Za-z0-9]+|^test_[^/]*\.py|_test\.(?:go|rs))$/; var TEST_DIRS = /* @__PURE__ */ new Set(["__tests__", "tests"]); @@ -132,7 +183,7 @@ var WEAKEN = /^(?:--passWithNoTests|--exclude|--testPathIgnorePatterns)(?:=|$)/; var SELECT = /^(?:-t|--testNamePattern|-k|--skip|-run)(?:=|$)/; var unquote = (token) => token.replace(/^['"]|['"]$/g, ""); function narrows(segment, kind) { - const tokens = segment.split(/\s+/).map(unquote).filter(Boolean); + const tokens = shellWords(segment).filter(Boolean); if (tokens.some((t) => WEAKEN.test(t))) return true; if (kind !== "test") return false; if (tokens.some((t) => SELECT.test(t))) return true; @@ -178,11 +229,27 @@ var ORIGIN_PATH = ".claude-flow/learning-loop-origin"; var MAX_LINES = 500; var MAX_STEPS = 64; var MAX_TASK = 300; +var SCREEN_LOOKAHEAD = 1024; +var MAX_PROMPT = 64 * 1024; +var REDACTED = "[redacted]"; var EDIT_TOOLS = /* @__PURE__ */ new Set(["Write", "Edit", "MultiEdit", "NotebookEdit"]); var TOOL = /^[A-Za-z0-9_.:-]{1,80}$/; function taskText(prompt) { - const flat = prompt.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,24}/g, "[email]").replace(/\s+/g, " ").trim().slice(0, MAX_TASK); - return scan(flat).secrets.length > 0 ? "[redacted]" : flat; + const raw = prompt.slice(0, MAX_PROMPT); + if (scan(raw).secrets.length > 0) return REDACTED; + const flat = raw.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,24}/g, "[email]").replace(/\s+/g, " ").trim(); + if (scan(flat.slice(0, MAX_TASK + SCREEN_LOOKAHEAD)).secrets.length > 0) return REDACTED; + let kept = flat; + if (flat.length > MAX_TASK) { + kept = flat.slice(0, MAX_TASK); + if (kept.at(-1) !== " " && flat[MAX_TASK] !== " ") { + const space = kept.lastIndexOf(" "); + if (space <= 0) return REDACTED; + kept = kept.slice(0, space); + } + kept = kept.trimEnd(); + } + return /-----BEGIN/.test(kept) ? REDACTED : kept; } var SESSION = /^[A-Za-z0-9_-]{1,40}$/; function start(id, prompt, agent, now, session = "") { @@ -295,9 +362,9 @@ function parseLessons(text) { if (typeof l.id !== "string" || !ID.test(l.id) || typeof l.agent !== "string" || !AGENT.test(l.agent) || keywords.length === 0 || confidence < 0) continue; if (l.kind !== "lesson" && l.kind !== "caution") continue; if (l.kind === "lesson" && confidence < gate) continue; - const evidence = typeof l.evidence === "string" && EVIDENCE.test(l.evidence) ? l.evidence : ""; + const evidence2 = typeof l.evidence === "string" && EVIDENCE.test(l.evidence) ? l.evidence : ""; const files = l.kind === "lesson" && Array.isArray(l.files) ? l.files.filter((f) => typeof f === "string" && lessonFile(f)).slice(0, MAX_FILES_SHOWN) : []; - lessons.push({ id: l.id, kind: l.kind, agent: l.agent, keywords, confidence, successes: count(l.successes), failures: count(l.failures), evidence, files }); + lessons.push({ id: l.id, kind: l.kind, agent: l.agent, keywords, confidence, successes: count(l.successes), failures: count(l.failures), evidence: evidence2, files }); } return { gate, lessons, belowGate: count(raw.belowGate), origin: typeof raw.origin === "string" && ORIGIN.test(raw.origin) ? raw.origin : null }; } @@ -372,10 +439,55 @@ var RULES = [ var SETUP = /^(?:cd\s+\S+|export\s+[A-Za-z_][A-Za-z0-9_]*=\S*)$/; var ENV_PREFIX = /^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/; var REDIRECTS = /\s*(?:\d?>&\d|&>>?\s*\S+|\d?>>?\s*\S+|<\s*\S+)/g; +var NO_RUN = /^(?:-h|--help|-V|--version|--listTests|--list-tests|--showConfig|--show-config|--collect-only|--co|--no-run|--list|-list|--dry-run|--print-config)(?:=.*)?$/; +var NO_RUN_FOR = { + tsc: /^(?:-v|--listFilesOnly|--dry|--init)$/, + eslint: /^(?:-v|--env-info|--init)$/, + vitest: /^-v$/, + jest: /^-v$/, + mvn: /^(?:-v|-h)$/, + mvnw: /^(?:-v|-h)$/, + gradle: /^(?:-m)$/, + gradlew: /^(?:-m)$/, + // make -n/-q (and clusters such as -nk) print or test targets without running their recipes. + make: /^(?:--just-print|--recon|--question|-[A-Za-z]*[nq][A-Za-z]*)$/, + pytest: /^(?:--fixtures|--fixtures-per-test|--markers|--setup-plan)$/, + dotnet: /^(?:-t)$/, + // A package script run with --if-present exits 0 when the project has no such script. + npm: /^--if-present$/, + pnpm: /^--if-present$/, + yarn: /^--if-present$/, + bun: /^--if-present$/ +}; +function programAt(words2) { + const name = (i2) => (words2[i2] ?? "").split("/").at(-1); + let i = 0; + if (["npx", "bunx"].includes(name(i))) i++; + else if (name(i) === "pnpm" && ["exec", "dlx"].includes(words2[1] ?? "")) i += 2; + else if (["python", "python3"].includes(name(i)) && words2[1] === "-m") i += 2; + else if (["uv", "poetry"].includes(name(i)) && words2[1] === "run") i += 2; + return i; +} +function runsNothing(segment) { + const words2 = shellWords(segment); + const at = programAt(words2); + const program = (words2[at] ?? "").split("/").at(-1); + const args = words2.slice(at + 1); + if (program === "vitest" && args[0] === "list") return true; + if (program === "cargo" && args.filter((a) => !a.startsWith("+"))[0] === "nextest" && args.filter((a) => !a.startsWith("+"))[1] === "list") return true; + if (program === "go" && args[0] === "test" && args.some((a) => a === "-c" || a === "-n")) return true; + const own = NO_RUN_FOR[program]; + return args.some((word) => NO_RUN.test(word) || own !== void 0 && own.test(word)); +} +function evidence(bare2) { + const flat = bare2.replace(/\s+/g, " "); + return scan(bare2).secrets.length > 0 || scan(flat).secrets.length > 0 ? "[redacted]" : flat.slice(0, MAX_EVIDENCE); +} function classify(command) { if (typeof command !== "string" || command.length === 0 || command.length > 2e3) return null; - const flat = command.replace(/\\\n/g, " ").trim(); + const flat = command.replace(/\\\n/g, "").trim(); if (/[\n\r`]|\$\(|\|\||;|\|/.test(flat)) return null; + if (hasComment(flat)) return null; const segments = flat.split("&&").map((s) => s.replace(REDIRECTS, "").trim()); if (segments.some((s) => s.length === 0 || s.includes("&"))) return null; let found = null; @@ -384,7 +496,8 @@ function classify(command) { const bare2 = segment.replace(ENV_PREFIX, ""); const kind = kindOf(bare2); if (kind === null) return null; - found = { kind: rank(found?.kind, kind), command: bare2.replace(/\s+/g, " ").slice(0, MAX_EVIDENCE), narrowed: found?.narrowed === true || narrows(bare2, kind) }; + if (runsNothing(bare2)) return null; + found = { kind: rank(found?.kind, kind), command: evidence(bare2), narrowed: found?.narrowed === true || narrows(bare2, kind) }; } return found; } diff --git a/plugins/ruflo-mods/.claude-plugin/plugin.json b/plugins/ruflo-mods/.claude-plugin/plugin.json index b70898222c..87a27c680c 100644 --- a/plugins/ruflo-mods/.claude-plugin/plugin.json +++ b/plugins/ruflo-mods/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-mods", "description": "ruflo as a Claude Code mod (function hooks, ADR-404): in-process prompt routing, edit learning signals, tighten-only tool checks from ruflo policy, the cost-tracker budget ladder, a mod trust gate for newly installed mods, and the $.ruflo noun other mods compose their status with. Opt-in and removable: the classic hook-handler hooks stay the default and take every event back whenever the mod is not loaded.", - "version": "0.17.4", + "version": "0.17.5", "repository": "https://github.com/ruvnet/ruflo", "author": { "name": "ruvnet", diff --git a/plugins/ruflo-mods/CHANGELOG.md b/plugins/ruflo-mods/CHANGELOG.md index 03d1d83127..fcb819d39e 100644 --- a/plugins/ruflo-mods/CHANGELOG.md +++ b/plugins/ruflo-mods/CHANGELOG.md @@ -2,6 +2,12 @@ Newest first. One `## — ` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-mods`. +## 0.17.5 — 2026-11-22 +- fix: a test, build or lint command that exits 0 without checking anything is no longer a learning-loop verifier, so the turn is not recorded as verified-success (#5067): help and version (`npm test --help`, `tsc -v`), listings (`npx vitest list`, `npx jest --listTests`, `pytest --collect-only`, `cargo nextest list`, `go test -list`, `dotnet test -t`), dry runs and config dumps (`make -n`, `tsc -b --dry`, `eslint --env-info`), compile-only runs (`cargo test --no-run`, `go test -c`) and `--if-present` scripts. Commands are read as bash splits them, so a real run whose quoted arguments contain those words still verifies, and a command with a shell comment is refused (`npm run build # && npm test` runs only the build). +- fix: the verifier command kept as evidence is screened for secret shapes, as given and as stored; one that carries a secret keeps its kind and outcome and is stored as `[redacted]`. +- fix: task text is screened as given before it is normalised and cut, the cut falls at a word boundary so a key it would split is dropped whole, a kept key-block header is refused, and at most 64 KiB of a prompt is read. A task stored as `[redacted]` is counted at ingest and never trains SONA. +- fix: ADR-503 taints read the same shell words, so a partly quoted `--passWithNoTests` still taints. + ## 0.17.4 — 2026-11-19 - fix: every file the mod writes under `.claude-flow` refuses a link on the way (#4746): edit records, the learning-loop ledger, guidance observations, context-delegation metrics, cost attribution and the console toast ring, as well as the session heartbeat and compaction snapshots. A symlinked `.claude-flow`, or a symlinked folder below it, can no longer steer a write outside the project; the refused write is dropped like any other failed one. - fix: the cost ledger no longer counts a symlinked `.claude-flow` as the project's state. diff --git a/plugins/ruflo-mods/hooks/loop/record.ts b/plugins/ruflo-mods/hooks/loop/record.ts index f4b0b21700..a632884622 100644 --- a/plugins/ruflo-mods/hooks/loop/record.ts +++ b/plugins/ruflo-mods/hooks/loop/record.ts @@ -20,6 +20,12 @@ export const ORIGIN_PATH = '.claude-flow/learning-loop-origin' export const MAX_LINES = 500 export const MAX_STEPS = 64 export const MAX_TASK = 300 +/** Text past the cut screened with it, for secret shapes that span words (`aws_secret_access_key = …`). */ +export const SCREEN_LOOKAHEAD = 1_024 +/** The most of a prompt read at all. */ +export const MAX_PROMPT = 64 * 1_024 +/** The task text stored for a prompt that carried a secret shape; it teaches nothing (ingest skips it). */ +export const REDACTED = '[redacted]' /** Records waiting for a write, at most (a file that cannot be written must not grow memory). */ export const MAX_PENDING = 50 @@ -54,17 +60,36 @@ const TOOL = /^[A-Za-z0-9_.:-]{1,80}$/ /** * A task as stored: control characters gone, e-mail addresses replaced, cut - * to 300 characters; a task carrying a secret shape is stored as - * `[redacted]` (it then teaches nothing). The CLI redacts PII again at ingest. + * to 300 characters at a word boundary; a task carrying a secret shape in the + * kept text or just past the cut is stored as `[redacted]` (it then teaches + * nothing). The cut never keeps part of a word, so a key it would split (a + * token, a JWT) is dropped whole rather than stored in part; the screen runs + * over the kept text plus SCREEN_LOOKAHEAD for shapes that span words. Only + * the first MAX_PROMPT characters are read and screened as given, so a huge + * prompt costs no more than a long one. A kept key-block header is refused. The CLI redacts PII again at ingest. */ export function taskText(prompt: string): string { - const flat = prompt + const raw = prompt.slice(0, MAX_PROMPT) + // The prompt as given: replacing control characters can split a shape the screen recognises in the original. + if (scan(raw).secrets.length > 0) return REDACTED + const flat = raw .replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ') .replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,24}/g, '[email]') .replace(/\s+/g, ' ') .trim() - .slice(0, MAX_TASK) - return scan(flat).secrets.length > 0 ? '[redacted]' : flat + if (scan(flat.slice(0, MAX_TASK + SCREEN_LOOKAHEAD)).secrets.length > 0) return REDACTED + let kept = flat + if (flat.length > MAX_TASK) { + kept = flat.slice(0, MAX_TASK) + if (kept.at(-1) !== ' ' && flat[MAX_TASK] !== ' ') { + const space = kept.lastIndexOf(' ') + if (space <= 0) return REDACTED // one word longer than the cut: nothing whole to keep + kept = kept.slice(0, space) + } + kept = kept.trimEnd() + } + // A key block's header with its body cut off no longer matches the screen; never keep one. + return /-----BEGIN/.test(kept) ? REDACTED : kept } const SESSION = /^[A-Za-z0-9_-]{1,40}$/ diff --git a/plugins/ruflo-mods/hooks/loop/taint.ts b/plugins/ruflo-mods/hooks/loop/taint.ts index bc60a68e39..ea7eed024b 100644 --- a/plugins/ruflo-mods/hooks/loop/taint.ts +++ b/plugins/ruflo-mods/hooks/loop/taint.ts @@ -9,6 +9,8 @@ * A taint never changes the outcome word. */ +import { shellWords } from './words' + export type Taint = 'edited-tests' | 'edited-verifier-config' | 'narrowed-verifier' export const TAINTS: readonly Taint[] = ['edited-tests', 'edited-verifier-config', 'narrowed-verifier'] @@ -48,6 +50,7 @@ const WEAKEN = /^(?:--passWithNoTests|--exclude|--testPathIgnorePatterns)(?:=|$) /** Flags that select a subset of tests. `-run` is `go test`'s name filter. */ const SELECT = /^(?:-t|--testNamePattern|-k|--skip|-run)(?:=|$)/ + const unquote = (token: string) => token.replace(/^['"]|['"]$/g, '') /** @@ -56,7 +59,8 @@ const unquote = (token: string) => token.replace(/^['"]|['"]$/g, '') * node id `file.py::name` counts). A directory argument (`pytest tests/`) does not. */ export function narrows(segment: string, kind: string): boolean { - const tokens = segment.split(/\s+/).map(unquote).filter(Boolean) + // The shell's words, so a partly quoted flag (`--pass"WithNoTests"`) is still that flag. + const tokens = shellWords(segment).filter(Boolean) if (tokens.some(t => WEAKEN.test(t))) return true if (kind !== 'test') return false if (tokens.some(t => SELECT.test(t))) return true diff --git a/plugins/ruflo-mods/hooks/loop/verifier.ts b/plugins/ruflo-mods/hooks/loop/verifier.ts index 037776de3d..2e4caa5b4d 100644 --- a/plugins/ruflo-mods/hooks/loop/verifier.ts +++ b/plugins/ruflo-mods/hooks/loop/verifier.ts @@ -8,11 +8,17 @@ * * A command whose exit status could be someone else's is refused: a pipe (the * last stage's status wins), `||`, `;`, a background `&`, command - * substitution, or a segment that is not `cd`/`export`/a verifier. So + * substitution, a comment, or a segment that is not `cd`/`export`/a verifier. So * `npm test || true` and `npm test | tail` never verify anything. + * + * A runner asked to print or list instead of run (`--help`, `--version`, + * `--listTests`, `--collect-only`, `--no-run`, ...) exits 0 without checking + * anything, so it is not a verifier either. */ +import { scan } from '../guidance/screen' import { narrows } from './taint' +import { hasComment, shellWords } from './words' export type VerifierKind = 'test' | 'build' | 'typecheck' | 'lint' @@ -62,6 +68,64 @@ const ENV_PREFIX = /^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/ /** Redirections that are not a background `&`. */ const REDIRECTS = /\s*(?:\d?>&\d|&>>?\s*\S+|\d?>>?\s*\S+|<\s*\S+)/g +/** + * Flags that make a runner print, list or compile instead of running its checks. Matched as whole shell words on the + * verifier segment, after the runner (`npm test --help`, `npm test -- --help`, `npx jest --listTests`). + */ +const NO_RUN = /^(?:-h|--help|-V|--version|--listTests|--list-tests|--showConfig|--show-config|--collect-only|--co|--no-run|--list|-list|--dry-run|--print-config)(?:=.*)?$/ +/** Per-program flags that also stop a run (`tsc -v` is a version, `pytest -v` is not: only the named program). */ +const NO_RUN_FOR: Record = { + tsc: /^(?:-v|--listFilesOnly|--dry|--init)$/, + eslint: /^(?:-v|--env-info|--init)$/, + vitest: /^-v$/, + jest: /^-v$/, + mvn: /^(?:-v|-h)$/, + mvnw: /^(?:-v|-h)$/, + gradle: /^(?:-m)$/, + gradlew: /^(?:-m)$/, + // make -n/-q (and clusters such as -nk) print or test targets without running their recipes. + make: /^(?:--just-print|--recon|--question|-[A-Za-z]*[nq][A-Za-z]*)$/, + pytest: /^(?:--fixtures|--fixtures-per-test|--markers|--setup-plan)$/, + dotnet: /^(?:-t)$/, + // A package script run with --if-present exits 0 when the project has no such script. + npm: /^--if-present$/, + pnpm: /^--if-present$/, + yarn: /^--if-present$/, + bun: /^--if-present$/, +} + +/** Index of the program a verifier segment runs, past launchers (`npx`, `pnpm exec`, `python -m`, `uv run`). */ +function programAt(words: readonly string[]): number { + const name = (i: number) => (words[i] ?? '').split('/').at(-1)! + let i = 0 + if (['npx', 'bunx'].includes(name(i))) i++ + else if (name(i) === 'pnpm' && ['exec', 'dlx'].includes(words[1] ?? '')) i += 2 + else if (['python', 'python3'].includes(name(i)) && words[1] === '-m') i += 2 + else if (['uv', 'poetry'].includes(name(i)) && words[1] === 'run') i += 2 + return i +} + +/** Whether a verifier segment asks its runner to do anything but run the checks. */ +export function runsNothing(segment: string): boolean { + const words = shellWords(segment) + const at = programAt(words) + const program = (words[at] ?? '').split('/').at(-1)! + const args = words.slice(at + 1) + if (program === 'vitest' && args[0] === 'list') return true + if (program === 'cargo' && args.filter(a => !a.startsWith('+'))[0] === 'nextest' && args.filter(a => !a.startsWith('+'))[1] === 'list') return true + // go test -c / -n build or print the test binary without running it. + if (program === 'go' && args[0] === 'test' && args.some(a => a === '-c' || a === '-n')) return true + const own = NO_RUN_FOR[program] + return args.some(word => NO_RUN.test(word) || (own !== undefined && own.test(word))) +} + +/** The command as kept for evidence: a command carrying a secret shape anywhere is kept as `[redacted]`. */ +function evidence(bare: string): string { + const flat = bare.replace(/\s+/g, ' ') + // Screen the command as given and as stored: folding can split a shape the screen recognises in the original. + return scan(bare).secrets.length > 0 || scan(flat).secrets.length > 0 ? '[redacted]' : flat.slice(0, MAX_EVIDENCE) +} + /** * The verifier a Bash command is, or null. Pure; bounded input. * @@ -69,8 +133,11 @@ const REDIRECTS = /\s*(?:\d?>&\d|&>>?\s*\S+|\d?>>?\s*\S+|<\s*\S+)/g */ export function classify(command: unknown): Verifier | null { if (typeof command !== 'string' || command.length === 0 || command.length > 2000) return null - const flat = command.replace(/\\\n/g, ' ').trim() + // Bash removes a backslash-newline outright (`--ver\\sion` is `--version`), so join without a space. + const flat = command.replace(/\\\n/g, '').trim() if (/[\n\r`]|\$\(|\|\||;|\|/.test(flat)) return null + // A comment hides what follows from the shell: `npm run build # && npm test` runs only the build. + if (hasComment(flat)) return null const segments = flat.split('&&').map(s => s.replace(REDIRECTS, '').trim()) if (segments.some(s => s.length === 0 || s.includes('&'))) return null @@ -80,7 +147,8 @@ export function classify(command: unknown): Verifier | null { const bare = segment.replace(ENV_PREFIX, '') const kind = kindOf(bare) if (kind === null) return null // something else ran: its status is not the verifier's - found = { kind: rank(found?.kind, kind), command: bare.replace(/\s+/g, ' ').slice(0, MAX_EVIDENCE), narrowed: found?.narrowed === true || narrows(bare, kind) } + if (runsNothing(bare)) return null // help, version or a listing: exit 0 says nothing about the code + found = { kind: rank(found?.kind, kind), command: evidence(bare), narrowed: found?.narrowed === true || narrows(bare, kind) } } return found } diff --git a/plugins/ruflo-mods/hooks/loop/words.ts b/plugins/ruflo-mods/hooks/loop/words.ts new file mode 100644 index 0000000000..ab09179d89 --- /dev/null +++ b/plugins/ruflo-mods/hooks/loop/words.ts @@ -0,0 +1,64 @@ +/** + * Bash word splitting for the learning loop's verifier and taint checks (#5067). One splitter, so the verifier + * decision and the ADR-503 taints read a command the way the shell will run it. + */ + +/** + * Shell words of one segment, as bash splits them: quotes group (`-t "a --help b"` is two words, the second never a + * flag), a quoted flag is still that flag (`'--listTests'`), an unquoted backslash escapes the next character, and + * inside double quotes a backslash escapes only `$`, `` ` ``, `"` and `\\`. Comments are refused before this runs. + */ +export function shellWords(segment: string): string[] { + const words: string[] = [] + let word = '' + let quoted = false + let quote: '' | "'" | '"' = '' + const flush = () => { + if (word !== '' || quoted) words.push(word) + word = '' + quoted = false + } + for (let i = 0; i < segment.length; i++) { + const c = segment[i]! + if (quote === "'") { + if (c === "'") quote = '' + else word += c + } else if (quote === '"') { + if (c === '"') quote = '' + else if (c === '\\' && i + 1 < segment.length && '$`"\\'.includes(segment[i + 1]!)) word += segment[++i] + else word += c + } else if (c === "'" || c === '"') { + quote = c + quoted = true + } else if (c === '\\' && i + 1 < segment.length) word += segment[++i] + else if (/\s/.test(c)) flush() + else word += c + } + flush() + return words +} + +/** + * Whether an unquoted, unescaped `#` starts a word, i.e. the shell would drop the rest of the command as a comment. + * An escaped space does not end a word, so `a\\ #b` has no comment. + */ +export function hasComment(command: string): boolean { + let quote = '' + let wordStart = true + for (let i = 0; i < command.length; i++) { + const c = command[i]! + if (quote !== '') { + if (c === quote) quote = '' + else if (c === '\\' && quote === '"') i++ + } else if (c === "'" || c === '"') { + quote = c + wordStart = false + } else if (c === '\\') { + i++ + wordStart = false + } else if (/\s/.test(c)) wordStart = true + else if (c === '#' && wordStart) return true + else wordStart = false + } + return false +} diff --git a/plugins/ruflo-mods/scripts/smoke.sh b/plugins/ruflo-mods/scripts/smoke.sh index c697c0e0b5..32a61b8b9c 100755 --- a/plugins/ruflo-mods/scripts/smoke.sh +++ b/plugins/ruflo-mods/scripts/smoke.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Structural + security smoke for ruflo-mods v0.17.4 (ADR-404, ADR-447). +# Structural + security smoke for ruflo-mods v0.17.5 (ADR-404, ADR-447). # Static only: CI has no Claude Code, so the hooks module's behaviour is held # by v3/@claude-flow/cli/__tests__/mods/*.test.ts and, where function hooks are # on, by `claude plugin test plugins/ruflo-mods`. @@ -12,9 +12,9 @@ ok() { printf "PASS\n"; PASS=$((PASS+1)); } bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); } HOOKS="$ROOT/hooks" -step "1. plugin.json declares ruflo-mods 0.17.4" +step "1. plugin.json declares ruflo-mods 0.17.5" grep -q '"name": "ruflo-mods"' "$ROOT/.claude-plugin/plugin.json" \ - && grep -q '"version": "0.17.4"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version" + && grep -q '"version": "0.17.5"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version" step "2. hooks.json names exactly one module and no classic hook commands" grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \ diff --git a/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json b/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json index c8b1016cde..1554046338 100644 --- a/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json +++ b/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json @@ -7,11 +7,11 @@ "intelligence.cjs": "ffdcfa6d2665a16e417dedd5bc67080c8192820f76265de5013fcb49f668ec71", "statusline.cjs": "284b95629ced4340667872b977de3f2beac90fc6bb7ab1a62dd7f7ae75c5e5d1", "router.cjs": "16648b3c0d73b6681ac2d8d13def6a68286c57f5a11004de5b19a0fa088c833d", - "learning-loop.cjs": "33caa41ce9edacbb0d403a337558f7a77c27b0864e4dfe8f6c2b541188602c1d", + "learning-loop.cjs": "0a39ee1d50d3349d9b77770e2c21b3247e8239b148755b10269b7d8b9cff56e3", "session.cjs": "b9972858615343120c7a65092c1c426fc859c6f9c308ce0ff6b4caace8ac6813", "memory.cjs": "2ef989f4640e357c1ac3eae09330242c1f6b037e6ef676a5999b8a7c11d53c33" } }, - "signature": "eSgtUFX3ZniFlNn6XZos4oGn/Qk+SQbQQtvhf4bFjt9o0lvM+5kt+xiFRaUgPQqEpFXPOwphMqD4JF6ju2IJBQ==", + "signature": "+oFdY590y0UpjBuHtGrqrcyPC2NZhlKKyV7dMv2EMvsgXvB1DhK6X8PzZTpNYT7kFIjNgnaCoKEbkkWDi/EEAA==", "algorithm": "ed25519" } diff --git a/v3/@claude-flow/cli/.claude/helpers/learning-loop.cjs b/v3/@claude-flow/cli/.claude/helpers/learning-loop.cjs index a05143d05f..df55d4bc7e 100755 --- a/v3/@claude-flow/cli/.claude/helpers/learning-loop.cjs +++ b/v3/@claude-flow/cli/.claude/helpers/learning-loop.cjs @@ -108,6 +108,57 @@ function utf8Bytes(text) { return n; } +// plugins/ruflo-mods/hooks/loop/words.ts +function shellWords(segment) { + const words2 = []; + let word = ""; + let quoted = false; + let quote = ""; + const flush = () => { + if (word !== "" || quoted) words2.push(word); + word = ""; + quoted = false; + }; + for (let i = 0; i < segment.length; i++) { + const c = segment[i]; + if (quote === "'") { + if (c === "'") quote = ""; + else word += c; + } else if (quote === '"') { + if (c === '"') quote = ""; + else if (c === "\\" && i + 1 < segment.length && '$`"\\'.includes(segment[i + 1])) word += segment[++i]; + else word += c; + } else if (c === "'" || c === '"') { + quote = c; + quoted = true; + } else if (c === "\\" && i + 1 < segment.length) word += segment[++i]; + else if (/\s/.test(c)) flush(); + else word += c; + } + flush(); + return words2; +} +function hasComment(command) { + let quote = ""; + let wordStart = true; + for (let i = 0; i < command.length; i++) { + const c = command[i]; + if (quote !== "") { + if (c === quote) quote = ""; + else if (c === "\\" && quote === '"') i++; + } else if (c === "'" || c === '"') { + quote = c; + wordStart = false; + } else if (c === "\\") { + i++; + wordStart = false; + } else if (/\s/.test(c)) wordStart = true; + else if (c === "#" && wordStart) return true; + else wordStart = false; + } + return false; +} + // plugins/ruflo-mods/hooks/loop/taint.ts var TEST_FILE = /(?:\.(?:test|spec)\.[A-Za-z0-9]+|^test_[^/]*\.py|_test\.(?:go|rs))$/; var TEST_DIRS = /* @__PURE__ */ new Set(["__tests__", "tests"]); @@ -132,7 +183,7 @@ var WEAKEN = /^(?:--passWithNoTests|--exclude|--testPathIgnorePatterns)(?:=|$)/; var SELECT = /^(?:-t|--testNamePattern|-k|--skip|-run)(?:=|$)/; var unquote = (token) => token.replace(/^['"]|['"]$/g, ""); function narrows(segment, kind) { - const tokens = segment.split(/\s+/).map(unquote).filter(Boolean); + const tokens = shellWords(segment).filter(Boolean); if (tokens.some((t) => WEAKEN.test(t))) return true; if (kind !== "test") return false; if (tokens.some((t) => SELECT.test(t))) return true; @@ -178,11 +229,27 @@ var ORIGIN_PATH = ".claude-flow/learning-loop-origin"; var MAX_LINES = 500; var MAX_STEPS = 64; var MAX_TASK = 300; +var SCREEN_LOOKAHEAD = 1024; +var MAX_PROMPT = 64 * 1024; +var REDACTED = "[redacted]"; var EDIT_TOOLS = /* @__PURE__ */ new Set(["Write", "Edit", "MultiEdit", "NotebookEdit"]); var TOOL = /^[A-Za-z0-9_.:-]{1,80}$/; function taskText(prompt) { - const flat = prompt.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,24}/g, "[email]").replace(/\s+/g, " ").trim().slice(0, MAX_TASK); - return scan(flat).secrets.length > 0 ? "[redacted]" : flat; + const raw = prompt.slice(0, MAX_PROMPT); + if (scan(raw).secrets.length > 0) return REDACTED; + const flat = raw.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,24}/g, "[email]").replace(/\s+/g, " ").trim(); + if (scan(flat.slice(0, MAX_TASK + SCREEN_LOOKAHEAD)).secrets.length > 0) return REDACTED; + let kept = flat; + if (flat.length > MAX_TASK) { + kept = flat.slice(0, MAX_TASK); + if (kept.at(-1) !== " " && flat[MAX_TASK] !== " ") { + const space = kept.lastIndexOf(" "); + if (space <= 0) return REDACTED; + kept = kept.slice(0, space); + } + kept = kept.trimEnd(); + } + return /-----BEGIN/.test(kept) ? REDACTED : kept; } var SESSION = /^[A-Za-z0-9_-]{1,40}$/; function start(id, prompt, agent, now, session = "") { @@ -295,9 +362,9 @@ function parseLessons(text) { if (typeof l.id !== "string" || !ID.test(l.id) || typeof l.agent !== "string" || !AGENT.test(l.agent) || keywords.length === 0 || confidence < 0) continue; if (l.kind !== "lesson" && l.kind !== "caution") continue; if (l.kind === "lesson" && confidence < gate) continue; - const evidence = typeof l.evidence === "string" && EVIDENCE.test(l.evidence) ? l.evidence : ""; + const evidence2 = typeof l.evidence === "string" && EVIDENCE.test(l.evidence) ? l.evidence : ""; const files = l.kind === "lesson" && Array.isArray(l.files) ? l.files.filter((f) => typeof f === "string" && lessonFile(f)).slice(0, MAX_FILES_SHOWN) : []; - lessons.push({ id: l.id, kind: l.kind, agent: l.agent, keywords, confidence, successes: count(l.successes), failures: count(l.failures), evidence, files }); + lessons.push({ id: l.id, kind: l.kind, agent: l.agent, keywords, confidence, successes: count(l.successes), failures: count(l.failures), evidence: evidence2, files }); } return { gate, lessons, belowGate: count(raw.belowGate), origin: typeof raw.origin === "string" && ORIGIN.test(raw.origin) ? raw.origin : null }; } @@ -372,10 +439,55 @@ var RULES = [ var SETUP = /^(?:cd\s+\S+|export\s+[A-Za-z_][A-Za-z0-9_]*=\S*)$/; var ENV_PREFIX = /^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/; var REDIRECTS = /\s*(?:\d?>&\d|&>>?\s*\S+|\d?>>?\s*\S+|<\s*\S+)/g; +var NO_RUN = /^(?:-h|--help|-V|--version|--listTests|--list-tests|--showConfig|--show-config|--collect-only|--co|--no-run|--list|-list|--dry-run|--print-config)(?:=.*)?$/; +var NO_RUN_FOR = { + tsc: /^(?:-v|--listFilesOnly|--dry|--init)$/, + eslint: /^(?:-v|--env-info|--init)$/, + vitest: /^-v$/, + jest: /^-v$/, + mvn: /^(?:-v|-h)$/, + mvnw: /^(?:-v|-h)$/, + gradle: /^(?:-m)$/, + gradlew: /^(?:-m)$/, + // make -n/-q (and clusters such as -nk) print or test targets without running their recipes. + make: /^(?:--just-print|--recon|--question|-[A-Za-z]*[nq][A-Za-z]*)$/, + pytest: /^(?:--fixtures|--fixtures-per-test|--markers|--setup-plan)$/, + dotnet: /^(?:-t)$/, + // A package script run with --if-present exits 0 when the project has no such script. + npm: /^--if-present$/, + pnpm: /^--if-present$/, + yarn: /^--if-present$/, + bun: /^--if-present$/ +}; +function programAt(words2) { + const name = (i2) => (words2[i2] ?? "").split("/").at(-1); + let i = 0; + if (["npx", "bunx"].includes(name(i))) i++; + else if (name(i) === "pnpm" && ["exec", "dlx"].includes(words2[1] ?? "")) i += 2; + else if (["python", "python3"].includes(name(i)) && words2[1] === "-m") i += 2; + else if (["uv", "poetry"].includes(name(i)) && words2[1] === "run") i += 2; + return i; +} +function runsNothing(segment) { + const words2 = shellWords(segment); + const at = programAt(words2); + const program = (words2[at] ?? "").split("/").at(-1); + const args = words2.slice(at + 1); + if (program === "vitest" && args[0] === "list") return true; + if (program === "cargo" && args.filter((a) => !a.startsWith("+"))[0] === "nextest" && args.filter((a) => !a.startsWith("+"))[1] === "list") return true; + if (program === "go" && args[0] === "test" && args.some((a) => a === "-c" || a === "-n")) return true; + const own = NO_RUN_FOR[program]; + return args.some((word) => NO_RUN.test(word) || own !== void 0 && own.test(word)); +} +function evidence(bare2) { + const flat = bare2.replace(/\s+/g, " "); + return scan(bare2).secrets.length > 0 || scan(flat).secrets.length > 0 ? "[redacted]" : flat.slice(0, MAX_EVIDENCE); +} function classify(command) { if (typeof command !== "string" || command.length === 0 || command.length > 2e3) return null; - const flat = command.replace(/\\\n/g, " ").trim(); + const flat = command.replace(/\\\n/g, "").trim(); if (/[\n\r`]|\$\(|\|\||;|\|/.test(flat)) return null; + if (hasComment(flat)) return null; const segments = flat.split("&&").map((s) => s.replace(REDIRECTS, "").trim()); if (segments.some((s) => s.length === 0 || s.includes("&"))) return null; let found = null; @@ -384,7 +496,8 @@ function classify(command) { const bare2 = segment.replace(ENV_PREFIX, ""); const kind = kindOf(bare2); if (kind === null) return null; - found = { kind: rank(found?.kind, kind), command: bare2.replace(/\s+/g, " ").slice(0, MAX_EVIDENCE), narrowed: found?.narrowed === true || narrows(bare2, kind) }; + if (runsNothing(bare2)) return null; + found = { kind: rank(found?.kind, kind), command: evidence(bare2), narrowed: found?.narrowed === true || narrows(bare2, kind) }; } return found; } diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-learning-loop-defences.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-learning-loop-defences.test.ts index 92bc02ac1a..69389d516b 100644 --- a/v3/@claude-flow/cli/__tests__/mods/mods-learning-loop-defences.test.ts +++ b/v3/@claude-flow/cli/__tests__/mods/mods-learning-loop-defences.test.ts @@ -184,6 +184,21 @@ describe('CLI ingest defences', () => { expect(again.ingested.tainted).toBe(0); }); + it('counts a verified success whose task was stored as [redacted] and never sends it to SONA (#5067)', async () => { + seed([rec('vt-1'), rec('vt-2', { task: '[redacted]' }), rec('vt-3', { task: '[redacted]', outcome: 'verified-failure', verifier: { kind: 'test', command: 'npm test', passed: false } })]); + const { sona, calls } = fakeSona(); + const r = await ingestVerifiedOutcomes({ root: dir, sona, force: true, config: cfg() }); + expect(calls.map((c) => c.id)).toEqual(['vt-1']); + expect(r.ingested).toMatchObject({ verifiedSuccess: 2, verifiedFailure: 1 }); + }); + + it('narrows() reads shell words: a partly quoted weakening flag is still that flag (#5067)', () => { + expect(narrows('npx jest --pass"WithNoTests"', 'test')).toBe(true); + expect(narrows("npx jest '--passWithNoTests'", 'test')).toBe(true); + expect(narrows('npx jest -t "not --passWithNoTests"', 'test')).toBe(true); // -t itself narrows + expect(narrows('npx jest src', 'test')).toBe(false); + }); + it('allowTaint lets exactly the listed class through (negative control: allowing every class trains them all)', async () => { seed([rec('vt-1', { taint: ['edited-verifier-config'] }), rec('vt-2', { taint: ['edited-tests'] }), rec('vt-3', { taint: ['edited-verifier-config', 'edited-tests'] })]); const { sona, calls } = fakeSona(); diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-learning-loop.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-learning-loop.test.ts index b69f511370..8e4aa748c3 100644 --- a/v3/@claude-flow/cli/__tests__/mods/mods-learning-loop.test.ts +++ b/v3/@claude-flow/cli/__tests__/mods/mods-learning-loop.test.ts @@ -13,7 +13,7 @@ import { afterEach, describe, expect, it } from 'vitest'; import { register } from '../../../../../plugins/ruflo-mods/hooks/register'; import { classify, verdict } from '../../../../../plugins/ruflo-mods/hooks/loop/verifier'; -import { decide, start as open, step } from '../../../../../plugins/ruflo-mods/hooks/loop/record'; +import { decide, start as open, step, taskText } from '../../../../../plugins/ruflo-mods/hooks/loop/record'; import { lessonBlock, parseLessons, pick } from '../../../../../plugins/ruflo-mods/hooks/loop/lessons'; import { buildLessons, ingestVerifiedOutcomes, learningLoopHealth, lessonId, lessonsOrigin, parseRecord, type SonaLike } from '../../src/memory/verified-outcomes.js'; import { SONAOptimizer } from '../../src/memory/sona-optimizer.js'; @@ -58,12 +58,51 @@ describe('verifier classification (pure)', () => { it('refuses anything whose exit status could belong to something else', () => { for (const cmd of ['npm test || true', 'npm test | tail -5', 'npm test; echo done', 'npm test & sleep 1', 'echo $(npm test)', 'npm test\nexit 0', - 'npm install', 'npm run deploy', 'git commit -m test', 'echo npm test', 'rm -rf x && npm test', 'npm test && rm -rf dist', '`npm test`', 'ls', '']) { + 'npm install', 'npm run deploy', 'git commit -m test', 'npm run build # && npm test', 'npm test # --help', 'echo npm test', 'rm -rf x && npm test', 'npm test && rm -rf dist', '`npm test`', 'ls', '']) { expect(classify(cmd), cmd).toBeNull(); } for (const bad of [undefined, null, 5, {}, 'x'.repeat(3000)]) expect(classify(bad)).toBeNull(); }); + it('a runner asked to print, list or compile is not a verifier: it exits 0 without checking anything', () => { + for (const cmd of ['npm test --help', 'npm test -- --help', 'npm run test -- -h', 'pnpm test --version', 'npx vitest --version', + 'npx jest --listTests', 'npx jest --showConfig', 'npx playwright test --list', 'pytest --collect-only', 'pytest --co -q', + 'python -m pytest --version', 'cargo test --no-run', 'cargo test -- --list', 'go test -list .', 'node --test --help', + 'npx tsc --help', 'npx eslint --print-config src/a.ts', 'cd v3 && npm test -- --help', 'npm run build && npm test --help', + 'npx vitest list', 'pnpm exec vitest list src/', 'cargo nextest list', "npx jest '--listTests'", 'CI=1 npx jest --listTests', 'npm test -- --help=true', + "npx vitest 'list'", "cargo +stable nextest 'list'", 'npx jest \\--listTests', + // Per-program forms: tsc/eslint/vitest/jest -v are a version, make -n/-q only print, go test -c only compiles. + 'npx tsc -v', 'npx tsc --listFilesOnly', 'npx tsc -b --dry', 'npx tsc --init', 'npx eslint --env-info', 'npx eslint -v', + 'npx vitest -v', 'npx jest -v', 'make test -n', 'make -nk test', 'make -q check', 'npm test --if-present', 'pnpm run test --if-present', + 'pytest --fixtures', 'python -m pytest --markers', 'go test -c ./...', 'go test -n ./...', 'dotnet test -t', + 'npx tsc --ver\\\nsion' /* bash joins a backslash-newline with no space: this is --version */]) { + expect(classify(cmd), cmd).toBeNull(); + } + // Flags that only shape a real run stay verifiers (negative control). + for (const cmd of ['npm test -- --reporter=list', 'pytest -v', 'cargo test -- --nocapture', 'npx vitest run --coverage', 'go test -v ./...', + 'npx vitest run -t "prints --help text"', "pytest -k 'help or --version'", 'npx vitest run tests/list.test.ts', + 'npx jest "\\--listTests"' /* bash keeps the backslash inside double quotes: jest gets a pattern, not the flag */, + 'npx jest --testNamePattern vitest list' /* "vitest list" is a pattern here, not the program */, 'pytest -v tests/', 'make test', + 'npx tsc --noEmit -p tsconfig.json', 'go test -v -count=1 ./...', 'dotnet test --logger trx', 'npx eslint --max-warnings 0 src', + 'npx vitest run a\\ #b.test.ts' /* an escaped space keeps # inside the word: no comment */]) { + expect(classify(cmd), cmd).not.toBeNull(); + } + }); + + it('a verifier command carrying a secret keeps its kind but is stored as [redacted]', () => { + const v = classify('npm test -- --token=ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ab'); + expect(v?.kind).toBe('test'); + expect(v?.command).toBe('[redacted]'); + // A secret past the 80-character evidence cut is found too. + const far = classify(`npx vitest run ${'a/'.repeat(40)}x.test.ts --token=ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ab`); + expect(far?.command).toBe('[redacted]'); + expect(classify('npm test -- --runInBand')?.command).toBe('npm test -- --runInBand'); + // A control character inside the token: the screen reads through it, folding would not. + expect(classify(`npm test -- --token=ghp_ABCDEFGHIJ\u0007KLMNOPQRSTUVWXYZ0123456789ab`)?.command).toBe('[redacted]'); + // A line separator inside the token: the screen reads through it, but folding whitespace would split it. + expect(classify(`npm test -- --token=ghp_ABCDEFGHIJ\u2028KLMNOPQRSTUVWXYZ0123456789ab`)?.command).toBe('[redacted]'); + }); + it('only a finished, foreground, uninterrupted run has a verdict', () => { expect(verdict({ result: { interrupted: false } })).toBe(true); expect(verdict({ result: { interrupted: false }, isError: true })).toBe(false); @@ -122,6 +161,20 @@ describe('learningLoop in the mod', () => { expect(mem(bare).has(TRAJ)).toBe(false); }); + it('an edit followed by a help or listing run that exits 0 is not recorded as verified-success', async () => { + const world = memoryWorld(); + const mod = await boot(world); + for (const cmd of ['npm test --help', 'npx vitest list', 'npx jest --listTests']) { + await ask(mod, `fix the parser (${cmd})`); + await edit(mod); + await bash(mod, cmd, true); + await end(mod); + } + expect(records(world)).toHaveLength(3); // each turn is recorded, so the checks below are not vacuous + expect(records(world).map((x) => x.outcome)).not.toContain('verified-success'); + expect(records(world).every((x) => x.verifier === null)).toBe(true); + }); + it('records verified success, verified failure and unknown from exit status only', async () => { const world = memoryWorld(); const mod = await boot(world); @@ -393,3 +446,39 @@ describe('end to end: mod record → CLI ingest with real SONA → lesson in the expect((await sona.getRoutingSuggestion('implement the tokenizer parser module')).agent).toBe('coder'); }); }); + +describe('task text (pure)', () => { + const key = 'ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ab'; + const jwt = `eyJhbGciOiJIUzI1NiJ9.eyJ${'a'.repeat(2000)}.${'s'.repeat(43)}`; + it('never stores part of a key the cut splits', () => { + expect(taskText(`fix it ${key}`)).toBe('[redacted]'); + expect(taskText(`${'x'.repeat(280)} ${key}`)).toBe('[redacted]'); // was stored with "ghp_ABCDEFGHIJKLMNO" + // A JWT that runs past the cut is found whole in the prompt as given. + expect(taskText(`fix ${'x'.repeat(285)} ${jwt}`)).toBe('[redacted]'); + // The cut drops a word it would split instead of keeping part of it. + expect(taskText(`fix ${'x'.repeat(285)} ${'q'.repeat(2000)}`)).toBe(`fix ${'x'.repeat(285)}`); + }); + it('screens the prompt as given (a control character inside a key) and refuses a kept key-block header', () => { + expect(taskText(`fix ${key.slice(0, 10)}\u0007${key.slice(10)}`)).toBe('[redacted]'); + expect(taskText(`${'x'.repeat(50)} -----BEGIN OPENSSH PRIVATE KEY----- ${'b3BlbnNzaC1rZXktdjEAAAAA '.repeat(80)}`)).toBe('[redacted]'); + // A header whose closing words lie past the read bound matches no rule; the kept "-----BEGIN" is still refused. + expect(taskText(`${'x'.repeat(50)} -----BEGIN${' '.repeat(70_000)}OPENSSH PRIVATE KEY-----`)).toBe('[redacted]'); + }); + it('a key past the read bound is never stored, so the kept text is clean and is kept', () => { + expect(taskText(`${'word '.repeat(14_000)}${key}`)).toBe('word '.repeat(60).trimEnd()); + }); + it('cuts a clean prompt to at most 300 characters at a word boundary', () => { + expect(taskText('implement the parser')).toBe('implement the parser'); + const cut = taskText('alpha '.repeat(100)); + expect(cut.length).toBeLessThanOrEqual(300); + expect(cut.endsWith('alpha')).toBe(true); + expect(taskText('y'.repeat(1000))).toBe('[redacted]'); // one word longer than the cut: nothing whole to keep + }); + it('reads a bounded prefix of a huge prompt', () => { + // 32M characters: ~6 ms with the read bound, ~1.4 s without it (measured on an M-series Mac). Built before the clock starts. + const huge = `do it ${'z '.repeat(16_000_000)}`; + const started = Date.now(); + expect(taskText(huge).startsWith('do it z')).toBe(true); + expect(Date.now() - started).toBeLessThan(250); + }); +}); diff --git a/v3/@claude-flow/cli/src/memory/verified-outcomes.ts b/v3/@claude-flow/cli/src/memory/verified-outcomes.ts index fdae0e3c85..b686b5779e 100644 --- a/v3/@claude-flow/cli/src/memory/verified-outcomes.ts +++ b/v3/@claude-flow/cli/src/memory/verified-outcomes.ts @@ -39,6 +39,9 @@ import { addOutcome, blockedTaints, emptyStats, parseStats, parseTaint, readLoop import { gitWorktreeRunner, ReverifySession, type ReverifyRunner } from './verified-reverify.js'; import { addFiles, buildLessons, parseFileCounts, recordFiles, type LessonsFile, type PatternExport } from './verified-lessons.js'; + +/** The recorder's task text for a prompt that carried a secret shape (ruflo-mods hooks/loop/record.ts). */ +const REDACTED_TASK = '[redacted]'; export { buildLessons, CAUTION_MIN_FAILURES, LESSON_GATE, lessonFile, lessonId, MAX_LESSONS, type Lesson, type LessonsFile } from './verified-lessons.js'; export const VERIFIED_PATH = join('.claude-flow', 'data', 'verified-trajectories.jsonl'); @@ -370,6 +373,13 @@ export async function ingestVerifiedOutcomes(options: IngestOptions = {}): Promi ingested.tainted++; continue; } + // A task the recorder stored as [redacted] carries no words; training it would teach SONA the marker itself + // (`coder:redacted`) and group unrelated tasks under it. Counted, never trained (#5067). + if (record.task === REDACTED_TASK) { + if (success) ingested.verifiedSuccess++; + else ingested.verifiedFailure++; + continue; + } if (options.dryRun) { if (success) ingested.verifiedSuccess++; else ingested.verifiedFailure++;