@mushi-mushi/cli 0.40.5 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ // src/version.ts
2
+ var MUSHI_CLI_VERSION = true ? "0.41.0" : "0.0.0-dev";
3
+ var MUSHI_MCP_PIN_SPEC = "@mushi-mushi/mcp@0.31.8";
4
+
5
+ export {
6
+ MUSHI_CLI_VERSION,
7
+ MUSHI_MCP_PIN_SPEC
8
+ };
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  MUSHI_CLI_VERSION
4
- } from "./chunk-UWPIVVCG.js";
4
+ } from "./chunk-SW53IBFM.js";
5
5
  import {
6
6
  CLOUD_API_ENDPOINT,
7
7
  normalizeEndpoint
@@ -9,10 +9,10 @@ import {
9
9
  requireUuid,
10
10
  saveConfig,
11
11
  savedSdkKeyFor
12
- } from "./chunk-4Z5MWQS5.js";
12
+ } from "./chunk-G3RJDBYO.js";
13
13
  import {
14
14
  MUSHI_MCP_PIN_SPEC
15
- } from "./chunk-UWPIVVCG.js";
15
+ } from "./chunk-SW53IBFM.js";
16
16
  import {
17
17
  assertEndpoint,
18
18
  normalizeEndpoint
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/version.ts
4
+ var MUSHI_CLI_VERSION = true ? "0.41.0" : "0.0.0-dev";
5
+ var MUSHI_MCP_PIN_SPEC = "@mushi-mushi/mcp@0.31.8";
6
+
7
+ export {
8
+ MUSHI_CLI_VERSION,
9
+ MUSHI_MCP_PIN_SPEC
10
+ };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  MUSHI_CLI_VERSION
3
- } from "./chunk-5DI4Q5BD.js";
3
+ } from "./chunk-3K53JXJ4.js";
4
4
  import {
5
5
  assertEndpoint,
6
6
  normalizeEndpoint
@@ -8,10 +8,10 @@ import {
8
8
  requireConfig,
9
9
  requireUuid,
10
10
  tryLoadWorkerKey
11
- } from "./chunk-4Z5MWQS5.js";
11
+ } from "./chunk-G3RJDBYO.js";
12
12
  import {
13
13
  MUSHI_CLI_VERSION
14
- } from "./chunk-UWPIVVCG.js";
14
+ } from "./chunk-SW53IBFM.js";
15
15
 
16
16
  // src/worker/daemon.ts
17
17
  import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
@@ -457,9 +457,142 @@ import { join as join3 } from "path";
457
457
  import { closeSync, constants as fsConstants, existsSync, fstatSync, mkdirSync, openSync, readFileSync as readFileSync2, readSync, writeFileSync } from "fs";
458
458
  import { homedir, tmpdir } from "os";
459
459
  import { basename, join as join2 } from "path";
460
+
461
+ // src/worker/audit-patterns.ts
462
+ import { posix } from "path";
463
+ var AUDIT_TAXONOMY = [
464
+ { category: "a11y-loading-silent", re: /(loading|loads|skeleton|busy|streaming|placeholder|wait)[\s\S]{0,80}(screen reader|silent|announc|unlabel|accessible name|no status|status|no text|hears)|(screen reader|silent|announc|unlabel|no status|hears)[\s\S]{0,80}(loading|loads|skeleton|busy|streaming)/i },
465
+ { category: "offline-state", re: /offline|reconnect/i },
466
+ { category: "error-state", re: /(fail|error|rejected|timed? ?out|retry|try again)[\s\S]{0,80}(empty|blank|zero|no |nothing|hidden|vanish|disappear|silent|ready|looks|shown as|says|as if|ignored|swallow|generic|never|recover)|error-(shown|as)|silent-(error|failure|download)|no-retry|error-no|retry-/i },
467
+ { category: "loading-state", re: /(loading|loads|skeleton|spinner|suspense|redirect|placeholder)[\s\S]{0,80}(blank|empty|never|stuck|no |shows|looks|mismatch|vanish|disappear|columns|tiles)|blank-(redirect|loading|page)|false-empty|stuck-loading|lazy-without-suspense|blank page/i },
468
+ { category: "untranslated", re: /untranslated|(stays?|always|stuck|shows?|uses?|is|in)( an| the)? (in )?english|english[- ](error|text|copy|labels?|status|abbreviation|notice|data|in|member)|hardcoded-english|wrong language|in the wrong lang|i18n|translation key|raw key|hardcoded|locale|stays japanese|always adds thai|mixed-language|missing-lang|aria-lang/i },
469
+ { category: "contrast", re: /contrast|faint|washed out|blends? into|fades? (out|into)|hard to read|disappears on|on (a )?(cream|pale|white)|white-on|-on-(wash|fill|accent|error)/i },
470
+ { category: "overflow", re: /overflow|clip|cut off|cut-off|runs? (off|out|past)|spills|truncat|ellipsiz|too narrow|offscreen|off-screen/i },
471
+ { category: "control-hard-to-use", re: /tap[- ]target|hit[- ]target|too (small|thin|short) to tap|tiny[- ](tap|hit|target|dont|close|button|link|checkbox)|\d+px[- ](tall|target)|not focusable|keyboard|focus|hover[- ]only|until hover|steal clicks|zooms? the page/i },
472
+ { category: "control-does-nothing", re: /does nothing|do nothing|noop|no-op|dead-|ignored|never keeps|swallowed|no (tap )?feedback|gives no|no result|nothing happens/i },
473
+ { category: "a11y-name", re: /screen reader|accessible name|unlabel|unnamed|aria|alt text|heading level|announced (twice|as)|not announced|live region|silent to/i },
474
+ { category: "hydration-shift", re: /hydration|pops in|pop in|flicker|shifts?|jumps|flash/i },
475
+ { category: "reduced-motion", re: /reduced[- ]motion|keeps? (bobbing|floating|moving)|never stops moving/i },
476
+ { category: "wrong-number", re: /count|plural|\b0\b|zero|percent|%|total|mismatch|disagree|number|\$0|infinity|over-?count|under-?count|1 words/i },
477
+ { category: "date-time", re: /utc|date|time ?zone|day|week|month|year|hours|minute/i },
478
+ { category: "stale-state", re: /stale|previous|old |keeps the|stays|comes back|left over/i }
479
+ ];
480
+ var AUDIT_CATEGORIES = [...AUDIT_TAXONOMY.map((t) => t.category), "other"];
481
+ function auditCategory(f) {
482
+ const text = `${(f.rule ?? "").replace(/-/g, " ")} ${f.rule ?? ""}
483
+ ${f.title ?? ""}
484
+ ${f.userImpact ?? ""}`;
485
+ for (const t of AUDIT_TAXONOMY) if (t.re.test(text)) return t.category;
486
+ return "other";
487
+ }
488
+ function auditPatternKey(category, root, rule) {
489
+ const cat = AUDIT_CATEGORIES.includes(category) ? category : "other";
490
+ return (cat === "other" ? `other:${rule}:${root}` : `${cat}:${root}`).slice(0, 400);
491
+ }
492
+ function parseImports(source) {
493
+ const out = /* @__PURE__ */ new Map();
494
+ const re = /import\s+(type\s+)?([\s\S]*?)\s+from\s+["']([^"']+)["']/g;
495
+ for (const m of source.matchAll(re)) {
496
+ if (m[1]) continue;
497
+ const clause = m[2].trim();
498
+ const spec = m[3];
499
+ const named = /\{([\s\S]*)\}/.exec(clause);
500
+ const def = clause.replace(/\{[\s\S]*\}/, "").replace(/\*\s+as\s+\w+/, "").replace(/,/g, " ").trim();
501
+ if (def && /^[A-Za-z_$][\w$]*$/.test(def)) out.set(def, spec);
502
+ if (named) {
503
+ for (const part of named[1].split(",")) {
504
+ const p = part.trim();
505
+ if (!p || /^type\s/.test(p)) continue;
506
+ const [orig, alias] = p.split(/\s+as\s+/).map((x) => x.trim());
507
+ const name = alias || orig;
508
+ if (name && /^[A-Za-z_$][\w$]*$/.test(name)) out.set(name, spec);
509
+ }
510
+ }
511
+ }
512
+ return out;
513
+ }
514
+ var EXTS = [".tsx", ".ts", ".jsx", ".js", ".vue", ".svelte"];
515
+ function resolveImport(fromFile, spec, exists) {
516
+ let base;
517
+ if (spec.startsWith("./") || spec.startsWith("../")) base = [posix.normalize(posix.join(posix.dirname(fromFile), spec))];
518
+ else if (spec.startsWith("@/") || spec.startsWith("~/")) base = [spec.slice(2), `src/${spec.slice(2)}`];
519
+ else return null;
520
+ for (const b of base) {
521
+ if (b.startsWith("..")) continue;
522
+ if (EXTS.some((e) => b.endsWith(e)) && exists(b)) return b;
523
+ for (const e of EXTS) if (exists(`${b}${e}`)) return `${b}${e}`;
524
+ for (const e of EXTS) if (exists(`${b}/index${e}`)) return `${b}/index${e}`;
525
+ }
526
+ return null;
527
+ }
528
+ function resolveComponent(fromFile, name, imports, read, exists) {
529
+ const spec = imports.get(name);
530
+ if (!spec) return null;
531
+ const target = resolveImport(fromFile, spec, exists);
532
+ if (!target) return null;
533
+ if (!/\/index\.[jt]sx?$/.test(target)) return target;
534
+ const barrel = read(target);
535
+ if (barrel === null) return target;
536
+ const named = new RegExp(`export\\s*\\{[^}]*\\b${name}\\b[^}]*\\}\\s*from\\s*["']([^"']+)["']`).exec(barrel);
537
+ if (named) return resolveImport(target, named[1], exists) ?? target;
538
+ for (const m of barrel.matchAll(/export\s*\*\s*from\s*["']([^"']+)["']/g)) {
539
+ const file = resolveImport(target, m[1], exists);
540
+ const text = file ? read(file) : null;
541
+ if (file && text && new RegExp(`export\\s+(?:default\\s+)?(?:function|const|class)\\s+${name}\\b`).test(text)) return file;
542
+ }
543
+ return target;
544
+ }
545
+ function evidenceTag(evidence) {
546
+ const m = /<([A-Z][\w]*)(?:\.[A-Z]\w*)?[\s/>]/.exec(`${evidence} `);
547
+ return m ? m[1] : null;
548
+ }
549
+ var CONVENTION_RE = /^(.*?\b(?:app|pages|routes))\/(?:.+\/)?(loading|error|not-found|global-error|\+not-found|_layout|layout)\.(tsx|jsx|ts|js)$/;
550
+ function patternRoot(file, evidence, source, read, exists) {
551
+ const tag = evidenceTag(evidence);
552
+ if (tag && source) {
553
+ const imports = parseImports(source);
554
+ const comp = resolveComponent(file, tag, imports, read, exists);
555
+ if (comp && comp !== file) return comp;
556
+ }
557
+ const conv = CONVENTION_RE.exec(file);
558
+ if (conv) return `${conv[1]}/**/${conv[2]}.${conv[3]}`;
559
+ return file;
560
+ }
561
+ function enclosingComponents(source, line) {
562
+ const lines = source.split("\n");
563
+ const names = [...parseImports(source).keys()].filter((n) => /^[A-Z]/.test(n));
564
+ const out = [];
565
+ for (const name of names) {
566
+ const open = new RegExp(`<${name}(?=[\\s>])`);
567
+ const close = new RegExp(`</${name}\\s*>`);
568
+ let opened = false;
569
+ for (let n = 1; n < line && n <= lines.length; n++) if (open.test(lines[n - 1])) opened = true;
570
+ if (!opened) continue;
571
+ for (let n = line; n <= lines.length; n++) {
572
+ if (close.test(lines[n - 1])) {
573
+ out.push(name);
574
+ break;
575
+ }
576
+ }
577
+ }
578
+ return out;
579
+ }
580
+ function absentHeldByWrapper(file, source, line, re, read, exists) {
581
+ if (!line) return null;
582
+ const imports = parseImports(source);
583
+ for (const name of enclosingComponents(source, line)) {
584
+ const path = resolveComponent(file, name, imports, read, exists);
585
+ const text = path ? read(path) : null;
586
+ if (path && text && text.split("\n").some((l) => re.test(l.slice(0, 1e3)))) return path;
587
+ }
588
+ return null;
589
+ }
590
+
591
+ // src/worker/audit.ts
460
592
  var ASK_TIMEOUT_MS = 15 * 6e4;
461
593
  var SCRIPT_TIMEOUT_MS = 10 * 6e4;
462
594
  var MAX_FINDINGS_PER_SCREEN = 3;
595
+ var MIN_CONFIDENCE = 0.6;
463
596
  var MAX_PENDING = 20;
464
597
  var MAX_FILE_BYTES = 1e6;
465
598
  function readWorktreeFile(path, maxBytes = MAX_FILE_BYTES) {
@@ -502,17 +635,19 @@ function nextScreen(state, screens) {
502
635
  const next = { ...state, pass: state.pass + 1, done: [] };
503
636
  return { screen: screens[0], state: next };
504
637
  }
505
- function proposePrompt(screen, pass) {
506
- const focus = pass === 1 ? "bugs a real user would notice" : "small rough edges a careful user would notice (polish pass)";
638
+ function proposePrompt(screen) {
507
639
  return `You are auditing one screen of this app as its most careful user. Screen file: ${screen}. Read it and only the files it imports directly (at most 8 files); do not explore the rest of the repo and do not run commands. Answer within a few minutes.
508
- Find up to ${MAX_FINDINGS_PER_SCREEN} ${focus}, each CONCRETE and visible to a user: wrong or missing data, text in the wrong language, numbers that contradict each other, a broken empty, loading or error state, a control that does nothing, text that overflows, missing feedback after an action, an accessibility gap (unlabelled control, tiny target, contrast).
640
+ Return 0 to ${MAX_FINDINGS_PER_SCREEN} findings. Return none when nothing on this screen would matter to a real user: an empty list is the usual, correct answer, and there is no quota. A finding must be a CONCRETE bug a real user of this screen hits: wrong or missing data, text in the wrong language, numbers that contradict each other, a broken empty, loading or error state, a control that does nothing, text that overflows, missing feedback after an action, an accessibility gap (unlabelled control, tiny target, contrast).
641
+ When the problem lives in a shared component this screen renders (a wrapper, a layout, a primitive), say so in user_impact: one fix there covers every screen.
642
+ Severity: high = a user loses data, money or access, or cannot finish the screen's main task; medium = a user sees wrong information or is blocked from a secondary task; low = a user is confused or slowed, with a way around it.
643
+ Confidence: how sure you are, from 0 to 1, that a real user hits this as you describe it. Below 0.6, leave it out.
509
644
  A program checks every finding before anyone sees it, with no model, and drops what it cannot reproduce:
510
645
  - "quote" must be the exact code on "line" of "file" (it is compared with the file);
511
646
  - "check" must reproduce the problem, as ONE of:
512
647
  {"kind":"pattern","file":"path","regex":"JavaScript regex","ignoreCase":false,"expect":"present"|"absent","line":123} (the regex is matched against each line of that file, within 3 lines of "line" when given; "absent" means the problem is that something is missing there)
513
648
  {"kind":"script","script":"lint"|"typecheck"|"test"|"check","expect":"text the failing output prints"} (the repo's own package script must fail and print this text and the file's path)
514
- Rules: no style opinions, no refactors, no "consider"; nothing that needs CI, secrets or another service. If nothing concrete, return an empty list.
515
- Answer with ONLY this JSON: {"findings":[{"title":"short, the user's view","severity":"high|medium|low","file":"path","line":123,"rule":"short-slug","quote":"exact code on that line","user_impact":"what the user sees","fix":"smallest change","done_when":"observable check","check":{...}}]}`;
649
+ Rules: no style opinions, no refactors, no "consider", no polish; nothing that needs CI, secrets or another service. If nothing concrete, return {"findings":[]}.
650
+ Answer with ONLY this JSON: {"findings":[{"title":"short, the user's view","severity":"high|medium|low","confidence":0.8,"file":"path","line":123,"rule":"short-slug","quote":"exact code on that line","user_impact":"what the user sees and when","fix":"smallest change","done_when":"observable check","check":{...}}]}`;
516
651
  }
517
652
  function vetoPrompt(f) {
518
653
  return `A program reproduced this claimed user-visible problem in the repository with a deterministic check. Your only job is to veto it if it is wrong: the check proves the wrong thing, the behaviour is intended, it is not visible to users, or it is a style opinion. Read the code before you answer.
@@ -572,9 +707,13 @@ function parseProposals(text) {
572
707
  check = { kind: "script", script: c.script, expect: str(c.expect, 200) };
573
708
  }
574
709
  if (!check) continue;
575
- const severity = raw.severity === "high" || raw.severity === "low" ? raw.severity : "medium";
710
+ if (raw.severity !== "high" && raw.severity !== "medium" && raw.severity !== "low") continue;
711
+ const userImpact = str(raw.user_impact, 1e3);
712
+ if (userImpact.length < 10) continue;
713
+ const confidence = typeof raw.confidence === "number" && Number.isFinite(raw.confidence) ? Math.min(1, Math.max(0, raw.confidence)) : null;
714
+ if (confidence === null || confidence < MIN_CONFIDENCE) continue;
576
715
  const rule = (str(raw.rule, 60).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "other").slice(0, 60);
577
- out.push({ title, severity, file, line, rule, quote, userImpact: str(raw.user_impact, 1e3), fix: str(raw.fix, 1e3), doneWhen: str(raw.done_when, 500), check });
716
+ out.push({ title, severity: raw.severity, file, line, rule, quote, userImpact, fix: str(raw.fix, 1e3), doneWhen: str(raw.done_when, 500), confidence, check });
578
717
  }
579
718
  return out;
580
719
  }
@@ -632,6 +771,25 @@ function saveAuditState(lane, s) {
632
771
  mkdirSync(join2(homedir(), ".cache", "mushi", "audit"), { recursive: true });
633
772
  writeFileSync(statePath(lane), JSON.stringify({ ...s, pending: s.pending.slice(0, MAX_PENDING) }, null, 1), { mode: 384 });
634
773
  }
774
+ function recheckSweep(list, wt, readFile = readWorktreeFile) {
775
+ const results = list.reports.map((r) => {
776
+ const res = recheckReport({ source: "code_audit", description: r.description }, wt, readFile);
777
+ return { reportId: r.id, gone: res.gone, reason: res.reason ?? "" };
778
+ });
779
+ const refile = [];
780
+ const deferredGone = [];
781
+ for (const d of list.deferred) {
782
+ const f = d.finding;
783
+ if (!f || typeof f.check?.summary !== "string" || f.check.kind !== "pattern") {
784
+ deferredGone.push(d.id);
785
+ continue;
786
+ }
787
+ const res = recheckReport({ source: "code_audit", description: `Reproduced by the worker with no model: pattern check, ${f.check.summary}` }, wt, readFile);
788
+ if (res.gone || !parseAuditCheck(`Reproduced by the worker with no model: pattern check, ${f.check.summary}`)) deferredGone.push(d.id);
789
+ else refile.push(f);
790
+ }
791
+ return { results, refile, deferredGone };
792
+ }
635
793
  async function auditPass(api, claimId, o) {
636
794
  const root = join2(homedir(), ".cache", "mushi", "audit", basename(o.repoDir));
637
795
  const wt = join2(root, o.laneName);
@@ -639,7 +797,9 @@ async function auditPass(api, claimId, o) {
639
797
  let state = loadAuditState(o.laneName);
640
798
  const fileOne = async (body) => {
641
799
  try {
642
- await api(`/v1/worker/claims/${claimId}/findings`, { method: "POST", body: JSON.stringify(body) });
800
+ const res = await api(`/v1/worker/claims/${claimId}/findings`, { method: "POST", body: JSON.stringify(body) });
801
+ if (res?.outcome === "merged" || res?.outcome === "regressed") return "merged";
802
+ if (res?.outcome === "deferred") return "deferred";
643
803
  return "filed";
644
804
  } catch (err) {
645
805
  const m = err instanceof Error ? err.message : String(err);
@@ -679,17 +839,36 @@ async function auditPass(api, claimId, o) {
679
839
  mkdirSync(empty, { recursive: true });
680
840
  await clearWorktree(o.repoDir, wt);
681
841
  await git(o.repoDir, ["worktree", "add", "--detach", wt, `refs/remotes/origin/${base}`]);
842
+ let swept = "";
843
+ const wrapperRoot = /* @__PURE__ */ new Map();
844
+ if (o.recheck) {
845
+ const list = await api(`/v1/worker/claims/${claimId}/recheck`);
846
+ const sweep = recheckSweep(list, wt);
847
+ const sha = (await git(wt, ["rev-parse", "HEAD"])).trim();
848
+ const out = await api(`/v1/worker/claims/${claimId}/recheck`, {
849
+ method: "POST",
850
+ body: JSON.stringify({ sha, base, results: sweep.results, deferredGone: sweep.deferredGone })
851
+ });
852
+ let refiled = 0;
853
+ for (const body of sweep.refile) if (await fileOne(body) === "filed") refiled++;
854
+ filed += refiled;
855
+ swept = `recheck on ${base} at ${sha.slice(0, 9)}: ${out.closed} of ${list.reports.length} open finding(s) closed as no longer there, ${out.requeued} queued again, ${refiled} waiting finding(s) filed, ${out.deferredDropped} dropped`;
856
+ o.log(` audit: ${swept}`);
857
+ }
858
+ if (o.propose === false) return { result: filed ? "filed" : "no_change", detail: swept || "the app is at its open cap; nothing proposed" };
682
859
  const files = (await git(wt, ["ls-tree", "-r", "--name-only", "HEAD"])).split("\n").filter(Boolean);
683
860
  const pick = nextScreen(state, listScreens(files));
684
861
  state = pick.state;
685
862
  if (!pick.screen) return { result: "no_change", detail: "no screen or UI file found in the default branch" };
686
863
  const screen = pick.screen;
687
- const proposed = await ask(o.model, proposePrompt(screen, state.pass));
864
+ const proposed = await ask(o.model, proposePrompt(screen));
688
865
  if (o.signal?.aborted) return { result: "stopped", detail: `stopped (lost the lease) while reading ${screen}` };
689
866
  if (proposed.timedOut) return { result: "timeout", failureKind: "code", detail: `the model did not answer about ${screen} within ${ASK_TIMEOUT_MS / 6e4} min` };
690
867
  if (proposed.code !== 0) return { result: "failed", failureKind: "infra", detail: `${agentSpec(agent).bin} exited ${proposed.code}: ${failureTail(proposed, 200)}` };
691
868
  const proposals = parseProposals(proposed.stdout);
692
869
  let reproduced = 0;
870
+ let merged = 0;
871
+ let deferred = 0;
693
872
  let vetoes = 0;
694
873
  let duplicates = 0;
695
874
  let depsReady = false;
@@ -703,6 +882,15 @@ async function auditPass(api, claimId, o) {
703
882
  if (p.check.kind === "pattern") {
704
883
  const checked = readWorktreeFile(join2(wt, p.check.file));
705
884
  ok = checked !== null && patternReproduces(checked, p.check);
885
+ if (ok && checked !== null && p.check.expect === "absent") {
886
+ const re = safeRegex(p.check.regex, p.check.ignoreCase);
887
+ const readRel = (f) => readWorktreeFile(join2(wt, f));
888
+ const held2 = re ? absentHeldByWrapper(p.check.file, checked, p.check.line, re, readRel, (f) => readRel(f) !== null) : null;
889
+ if (held2) {
890
+ o.log(` audit: ${p.file}:${evidence.line} is rooted at ${held2}, which wraps it and has /${p.check.regex}/ without doing the job`);
891
+ wrapperRoot.set(p, held2);
892
+ }
893
+ }
706
894
  } else if (scriptRuns < 1) {
707
895
  const pkg = existsSync(join2(wt, "package.json")) ? JSON.parse(readFileSync2(join2(wt, "package.json"), "utf8")) : {};
708
896
  const pm = installCommand((f) => existsSync(join2(wt, f)))?.[0] ?? "npm";
@@ -731,7 +919,9 @@ async function auditPass(api, claimId, o) {
731
919
  check: { kind: p.check.kind, summary: checkSummary(p.check) },
732
920
  screen,
733
921
  proposedBy: o.model ?? null,
734
- vetoBy: o.reviewModel
922
+ vetoBy: o.reviewModel,
923
+ confidence: p.confidence,
924
+ rootFile: wrapperRoot.get(p) ?? patternRoot(p.file, evidence.text, source, (f) => readWorktreeFile(join2(wt, f)), (f) => readWorktreeFile(join2(wt, f)) !== null)
735
925
  };
736
926
  if (o.reviewModel) {
737
927
  const v = await ask(o.reviewModel, vetoPrompt(body));
@@ -744,6 +934,8 @@ async function auditPass(api, claimId, o) {
744
934
  }
745
935
  const r = await fileOne(body);
746
936
  if (r === "filed") filed++;
937
+ else if (r === "merged") merged++;
938
+ else if (r === "deferred") deferred++;
747
939
  else if (r === "duplicate") duplicates++;
748
940
  else if (r === "capped" || r === "error") {
749
941
  held++;
@@ -752,7 +944,7 @@ async function auditPass(api, claimId, o) {
752
944
  }
753
945
  state.done = [...state.done, screen];
754
946
  saveAuditState(o.laneName, state);
755
- const detail = `${screen} (pass ${state.pass}): ${proposals.length} proposed, ${reproduced} reproduced, ${vetoes} vetoed, ${duplicates} already filed, ${filed} filed${held ? `, ${held} wait for the hourly cap` : ""}`;
947
+ const detail = `${swept ? `${swept}; ` : ""}${screen} (pass ${state.pass}): ${proposals.length} proposed, ${reproduced} reproduced, ${vetoes} vetoed, ${duplicates} already filed, ${merged} joined an open report, ${deferred} set aside past the open cap, ${filed} filed${held ? `, ${held} wait for the hourly cap` : ""}`;
756
948
  return { result: filed ? "filed" : "no_change", detail };
757
949
  } catch (err) {
758
950
  const message = err instanceof Error ? err.message : String(err);
@@ -780,9 +972,17 @@ function recheckReport(detail, worktree, readFile = readWorktreeFile) {
780
972
  if (detail.source !== "code_audit") return { gone: false, reason: null };
781
973
  const check = parseAuditCheck(detail.description);
782
974
  if (!check) return { gone: false, reason: "its check could not be read back, so the agent looks" };
783
- const text = readFile(join3(worktree, check.file));
975
+ const readRel = (p) => readFile(join3(worktree, p));
976
+ const text = readRel(check.file);
784
977
  if (text === null) return { gone: false, reason: `${check.file} is not in the base branch any more, so the agent looks` };
785
- if (patternReproduces(text, check)) return { gone: false, reason: null };
978
+ if (patternReproduces(text, check)) {
979
+ if (check.expect === "absent") {
980
+ const re = safeRegex(check.regex, check.ignoreCase);
981
+ const wrapper = re ? absentHeldByWrapper(check.file, text, check.line, re, readRel, (p) => readRel(p) !== null) : null;
982
+ if (wrapper) return { gone: false, reason: null, root: wrapper };
983
+ }
984
+ return { gone: false, reason: null };
985
+ }
786
986
  if (check.expect === "present" && patternReproduces(text, { ...check, line: null })) {
787
987
  return { gone: false, reason: `the code moved away from line ${check.line ?? "?"} but is still in ${check.file}, so the agent looks` };
788
988
  }
@@ -791,6 +991,47 @@ function recheckReport(detail, worktree, readFile = readWorktreeFile) {
791
991
  reason: `its own check no longer reproduces: /${check.regex}/${check.ignoreCase ? "i" : ""} is not ${check.expect} in ${check.file}${check.line ? ` near line ${check.line}` : ""}`
792
992
  };
793
993
  }
994
+ function descField(description, label) {
995
+ const m = new RegExp(`^${label}: (.*)$`, "m").exec(description ?? "");
996
+ return m ? m[1].trim() : "";
997
+ }
998
+ var SEVERITY_RANK = { critical: 4, high: 3, medium: 2, low: 1 };
999
+ function planBacklog(rows, worktree, readFile = readWorktreeFile) {
1000
+ const plan = { checked: 0, gone: [], stillThere: 0, unclear: 0, patterns: [], collapsed: 0, remaining: 0 };
1001
+ const readRel = (p) => readFile(join3(worktree, p));
1002
+ const byKey = /* @__PURE__ */ new Map();
1003
+ for (const r of rows) {
1004
+ if (r.source !== "code_audit") continue;
1005
+ plan.checked++;
1006
+ const res = recheckReport(r, worktree, readFile);
1007
+ if (res.gone) {
1008
+ plan.gone.push({ reportId: r.id, severity: r.severity ?? null, reason: res.reason });
1009
+ continue;
1010
+ }
1011
+ if (res.reason) plan.unclear++;
1012
+ else plan.stillThere++;
1013
+ const where = /^(.+):(\d+)$/.exec(descField(r.description, "Where"));
1014
+ const file = r.custom_metadata?.file ?? where?.[1] ?? parseAuditCheck(r.description)?.file ?? "";
1015
+ const rule = r.custom_metadata?.rule ?? "";
1016
+ const evidence = descField(r.description, "The code there");
1017
+ const category = auditCategory({ rule, title: r.title ?? r.summary ?? "", userImpact: descField(r.description, "What the user sees") });
1018
+ const root = res.root ?? (file ? patternRoot(file, evidence, readRel(file), readRel, (p) => readRel(p) !== null) : `report:${r.id}`);
1019
+ const key = r.custom_metadata?.pattern_key ?? auditPatternKey(category, root, rule || r.id);
1020
+ const g = byKey.get(`${r.project_id ?? ""}|${key}`) ?? { category, root, rows: [], screens: /* @__PURE__ */ new Set() };
1021
+ g.rows.push(r);
1022
+ const screen = /code-read audit of (\S+?) on the local/.exec(r.description ?? "")?.[1] ?? file;
1023
+ if (screen) g.screens.add(screen);
1024
+ byKey.set(`${r.project_id ?? ""}|${key}`, g);
1025
+ }
1026
+ for (const [k, g] of byKey) {
1027
+ const sorted = [...g.rows].sort((a, b) => (SEVERITY_RANK[b.severity ?? ""] ?? 0) - (SEVERITY_RANK[a.severity ?? ""] ?? 0) || String(a.created_at ?? "").localeCompare(String(b.created_at ?? "")));
1028
+ plan.patterns.push({ key: k.slice(k.indexOf("|") + 1), category: g.category, root: g.root, parentId: sorted[0].id, reportIds: sorted.map((r) => r.id), screens: [...g.screens].sort() });
1029
+ }
1030
+ plan.patterns.sort((a, b) => b.reportIds.length - a.reportIds.length || a.key.localeCompare(b.key));
1031
+ plan.remaining = plan.patterns.length;
1032
+ plan.collapsed = plan.patterns.reduce((n, p) => n + p.reportIds.length - 1, 0);
1033
+ return plan;
1034
+ }
794
1035
  var SHA_RE = /\b([0-9a-f]{7,40})\b/g;
795
1036
  function verdictCommits(reason) {
796
1037
  return [...new Set([...reason.matchAll(SHA_RE)].map((m) => m[1]).filter((s) => /[a-f]/.test(s) && /\d/.test(s)))].slice(0, 3);
@@ -798,6 +1039,115 @@ function verdictCommits(reason) {
798
1039
  function goneNote(reason, baseRef, sha) {
799
1040
  return `Closed by mushi work without an agent run: ${reason} (checked on ${baseRef}${sha ? ` at ${sha.slice(0, 9)}` : ""}). Reopen it if the problem is still there.`.slice(0, 4e3);
800
1041
  }
1042
+ var CATEGORY_TITLES = {
1043
+ "a11y-loading-silent": "Screen readers hear nothing while it loads",
1044
+ "offline-state": "Offline state is wrong",
1045
+ "error-state": "A failed load is hidden or shown as something else",
1046
+ "loading-state": "Loading shows a blank or wrong screen",
1047
+ untranslated: "Text is not translated",
1048
+ contrast: "Text or icons are too faint to read",
1049
+ overflow: "Text is cut off or overflows",
1050
+ "control-hard-to-use": "A control is too small or hard to reach",
1051
+ "control-does-nothing": "A control does nothing",
1052
+ "a11y-name": "Screen readers get no name or the wrong one",
1053
+ "hydration-shift": "Content pops in and shifts after load",
1054
+ "reduced-motion": "Motion ignores reduced motion",
1055
+ "wrong-number": "A number or count is wrong",
1056
+ "date-time": "A date or time is wrong",
1057
+ "stale-state": "The screen keeps stale data"
1058
+ };
1059
+ function collapseGroups(plan, rows) {
1060
+ const byId = new Map(rows.map((r) => [r.id, r]));
1061
+ const out = [];
1062
+ for (const p of plan.patterns) {
1063
+ if (p.reportIds.length < 2) continue;
1064
+ const members = p.reportIds.map((id) => byId.get(id)).filter((r) => !!r);
1065
+ const parent = members.find((r) => r.status === "fixing") ?? byId.get(p.parentId);
1066
+ if (!parent) continue;
1067
+ const childIds = members.filter((r) => r.id !== parent.id && r.status !== "fixing").map((r) => r.id);
1068
+ if (childIds.length === 0) continue;
1069
+ const screens = members.flatMap((r) => {
1070
+ const where = /^(.+):(\d+)$/.exec(descField(r.description, "Where"));
1071
+ const file = r.custom_metadata?.file ?? where?.[1];
1072
+ const line = r.custom_metadata?.line ?? (where ? Number(where[2]) : null);
1073
+ const screen = /code-read audit of (\S+?) on the local/.exec(r.description ?? "")?.[1] ?? file;
1074
+ return file && screen && line ? [{ screen, file, line, title: (r.title ?? "").slice(0, 200), at: r.created_at ?? "" }] : [];
1075
+ });
1076
+ const parentFile = parent.custom_metadata?.file ?? null;
1077
+ const label = CATEGORY_TITLES[p.category];
1078
+ const title = label && p.root !== parentFile && !p.root.startsWith("report:") ? `${label} in ${p.root} (${members.length} screens)`.slice(0, 200) : null;
1079
+ out.push({ parentId: parent.id, patternKey: p.key, title, screens, childIds });
1080
+ }
1081
+ return out;
1082
+ }
1083
+ function collapseRevertSql(tag) {
1084
+ const t = tag.replace(/[^a-z0-9_]/g, "");
1085
+ const c = "custom_metadata->'collapse'";
1086
+ const k = "custom_metadata->'cap'";
1087
+ const parent = `${c}->>'role' = 'parent'`;
1088
+ const child = `${c}->>'role' = 'child'`;
1089
+ return [
1090
+ "begin;",
1091
+ "update public.reports set",
1092
+ ` status = coalesce(${k}->>'from_status', ${c}->>'from_status', status),`,
1093
+ ` closed_reason = case when ${k} is not null then ${k}->>'from_closed_reason' when ${child} then ${c}->>'from_closed_reason' else closed_reason end,`,
1094
+ ` parent_report_id = case when ${child} then null else parent_report_id end,`,
1095
+ ` title = case when ${parent} then coalesce(${c}->>'prev_title', title) else title end,`,
1096
+ ` pattern_key = case when ${parent} then ${c}->>'prev_pattern_key' when ${k} is not null then ${k}->>'prev_pattern_key' else pattern_key end,`,
1097
+ ` affected_screens = case when ${parent} then nullif(${c}->'prev_affected_screens', 'null'::jsonb) else affected_screens end,`,
1098
+ " custom_metadata = custom_metadata - 'collapse' - 'cap'",
1099
+ `where source = 'code_audit' and (${c}->>'tag' = '${t}' or ${k}->>'tag' = '${t}');`,
1100
+ `delete from public.code_audit_deferred where finding->>'collapse_tag' = '${t}';`,
1101
+ "commit;"
1102
+ ].join("\n");
1103
+ }
1104
+ var FINDING_SEVERITIES = /* @__PURE__ */ new Set(["high", "medium", "low"]);
1105
+ function findingFromRow(r, root) {
1106
+ const where = /^(.+):(\d+)$/.exec(descField(r.description, "Where"));
1107
+ const file = r.custom_metadata?.file ?? where?.[1];
1108
+ const line = r.custom_metadata?.line ?? (where ? Number(where[2]) : null);
1109
+ const check = /^Reproduced by the worker with no model: (pattern|script) check, (.+)$/m.exec(r.description ?? "");
1110
+ const evidence = descField(r.description, "The code there");
1111
+ const screen = /code-read audit of (\S+?) on the local/.exec(r.description ?? "")?.[1] ?? file;
1112
+ const severity = r.severity === "critical" ? "high" : r.severity;
1113
+ if (!file || !line || !check || !evidence || !screen || !severity || !FINDING_SEVERITIES.has(severity) || root.startsWith("report:")) return null;
1114
+ const title = (r.title ?? r.summary ?? "").trim();
1115
+ return {
1116
+ title,
1117
+ severity,
1118
+ file,
1119
+ line,
1120
+ rule: r.custom_metadata?.rule || "other",
1121
+ evidenceLine: evidence,
1122
+ userImpact: descField(r.description, "What the user sees") || title,
1123
+ fix: descField(r.description, "Fix") || "See the report.",
1124
+ doneWhen: descField(r.description, "Done when") || "The check above no longer reproduces.",
1125
+ check: { kind: check[1], summary: check[2].trim() },
1126
+ screen,
1127
+ proposedBy: null,
1128
+ vetoBy: null,
1129
+ confidence: typeof r.custom_metadata?.confidence === "number" ? r.custom_metadata.confidence : null,
1130
+ rootFile: root
1131
+ };
1132
+ }
1133
+ function capCandidates(plan, rows, groups, worktree, readFile = readWorktreeFile) {
1134
+ const children = new Set(groups.flatMap((g) => g.childIds));
1135
+ const rootOf = /* @__PURE__ */ new Map();
1136
+ for (const p of plan.patterns) for (const id of p.reportIds) rootOf.set(id, p.root);
1137
+ const readRel = (p) => readFile(join3(worktree, p));
1138
+ const out = [];
1139
+ for (const r of rows) {
1140
+ if (r.source !== "code_audit" || children.has(r.id)) continue;
1141
+ let root = rootOf.get(r.id);
1142
+ if (!root) {
1143
+ const file = r.custom_metadata?.file ?? /^(.+):(\d+)$/.exec(descField(r.description, "Where"))?.[1];
1144
+ root = file ? patternRoot(file, descField(r.description, "The code there"), readRel(file), readRel, (p) => readRel(p) !== null) : `report:${r.id}`;
1145
+ }
1146
+ const finding = findingFromRow(r, root);
1147
+ if (finding) out.push({ reportId: r.id, finding });
1148
+ }
1149
+ return out;
1150
+ }
801
1151
 
802
1152
  // src/commands/work.ts
803
1153
  var WORK_AGENT_KIND = "mcp";
@@ -1222,6 +1572,10 @@ async function recheckBacklog(api, repoDir, o) {
1222
1572
  if (got.length < RECHECK_PAGE) break;
1223
1573
  }
1224
1574
  }
1575
+ if (o.dryRun) {
1576
+ const plan = planBacklog(rows, wt, o.readFile);
1577
+ out.plan = { patterns: plan.patterns, collapsed: plan.collapsed, remaining: plan.remaining };
1578
+ }
1225
1579
  for (const r of rows) {
1226
1580
  if (interruptedBy()) break;
1227
1581
  out.checked++;
@@ -1246,8 +1600,40 @@ async function recheckBacklog(api, repoDir, o) {
1246
1600
  const verb = o.dryRun ? "would close" : "closed";
1247
1601
  o.log(`Rechecked ${out.checked} open code-audit report(s) on origin/${base}${sha ? ` (${sha.slice(0, 9)})` : ""}: ${verb} ${out.gone.length} that no longer reproduce, ${out.stillThere} still reproduce, ${out.unclear} left to the agent (check unreadable or file moved).`);
1248
1602
  if (out.closeFailed) o.log(`${out.closeFailed} could not be closed; see the lines above.`);
1603
+ if (out.plan) o.log(`The ${out.stillThere + out.unclear} left would be ${out.plan.remaining} report(s), one per pattern: ${out.plan.collapsed} would join a pattern's report as a duplicate.`);
1249
1604
  return out;
1250
1605
  }
1606
+ async function collapseBacklog(api, repoDir, o) {
1607
+ const base = await defaultBranch(repoDir);
1608
+ await git(repoDir, ["fetch", "--quiet", "origin", base]);
1609
+ const root = join4(homedir2(), ".cache", "mushi", "work", basename2(repoDir));
1610
+ mkdirSync2(root, { recursive: true });
1611
+ const wt = join4(root, "collapse");
1612
+ await clearWorktree(repoDir, wt);
1613
+ await git(repoDir, ["worktree", "add", "--detach", wt, `origin/${base}`]);
1614
+ try {
1615
+ const { reports } = await api(`/v1/admin/work/code-audit/backlog?projectId=${encodeURIComponent(o.projectId)}`);
1616
+ const plan = planBacklog(reports, wt);
1617
+ const groups = collapseGroups(plan, reports);
1618
+ const cap2 = o.applyCap ? { candidates: capCandidates(plan, reports, groups, wt) } : null;
1619
+ const res = await api("/v1/admin/work/code-audit/collapse", {
1620
+ method: "POST",
1621
+ body: JSON.stringify({ projectId: o.projectId, tag: o.tag, apply: o.apply, groups, ...cap2 ? { cap: cap2 } : {} })
1622
+ });
1623
+ const revertSql = collapseRevertSql(o.tag);
1624
+ o.log(`${o.apply ? "Collapsed" : "Would collapse (dry run, nothing changed)"}: open code-audit reports ${res.before} \u2192 ${res.after}; ${res.children} closed as duplicates into ${res.groups} pattern report(s); ${res.skipped} left open (a live PR, or changed meanwhile)${res.keyTaken ? `; ${res.keyTaken} group(s) skipped, their pattern is already open` : ""}.`);
1625
+ for (const g of groups.slice(0, 10)) o.log(` ${g.patternKey}: ${g.childIds.length + 1} reports \u2192 ${g.parentId}${g.title ? ` "${g.title}"` : ""}`);
1626
+ if (res.cap) {
1627
+ const c = res.cap;
1628
+ o.log(`${o.apply ? "Open cap applied" : "Open cap (dry run)"}: ${c.openBefore} \u2192 ${c.openAfter} open (cap ${c.cap}); ${c.deferred} set aside in code_audit_deferred as deferred_over_cap; kept open whatever the cap: ${c.keptLivePr} with a live PR${c.keptNoFinding ? `, ${c.keptNoFinding} with no finding to re-file` : ""}.`);
1629
+ } else if (res.capFailed) o.log("The open cap could not be applied (a read failed); the collapse above stands. Run it again.");
1630
+ o.log(`Tag ${o.tag}. To undo it, run this once in the SQL editor:
1631
+ ${revertSql}`);
1632
+ return { ...res, plan: groups, revertSql };
1633
+ } finally {
1634
+ await clearWorktree(repoDir, wt);
1635
+ }
1636
+ }
1251
1637
  async function workOne(api, detail, o) {
1252
1638
  const base = await defaultBranch(o.repoDir);
1253
1639
  await git(o.repoDir, ["fetch", "--quiet", "origin", base]);
@@ -1544,6 +1930,20 @@ async function pushWithHooks(wt, args, log) {
1544
1930
  }
1545
1931
  var CURSOR_STATUS_TIMEOUT_MS = 9e4;
1546
1932
  var CURSOR_STATUS_RETRY_DELAY_MS = 5e3;
1933
+ function signInDetail(text) {
1934
+ const start = text.indexOf("{");
1935
+ if (start >= 0) {
1936
+ try {
1937
+ const j = JSON.parse(text.slice(start));
1938
+ if (typeof j.loggedIn === "boolean") {
1939
+ const how = typeof j.authMethod === "string" && /^[\w.-]{1,30}$/.test(j.authMethod) ? ` (${j.authMethod})` : "";
1940
+ return j.loggedIn ? `logged in${how}` : "logged out";
1941
+ }
1942
+ } catch {
1943
+ }
1944
+ }
1945
+ return text.split("\n")[0]?.slice(0, 200) ?? "";
1946
+ }
1547
1947
  async function checkAgentSignIn(agent, run = runProc, wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
1548
1948
  const spec = agentSpec(agent);
1549
1949
  let last = { state: "unknown", detail: "not checked", output: "" };
@@ -1551,8 +1951,8 @@ async function checkAgentSignIn(agent, run = runProc, wait = (ms) => new Promise
1551
1951
  if (attempt > 0) await wait(CURSOR_STATUS_RETRY_DELAY_MS);
1552
1952
  const p = await run(spec.bin, spec.status, { timeoutMs: CURSOR_STATUS_TIMEOUT_MS });
1553
1953
  const state = spec.signInState(p);
1554
- const detail = p.timedOut ? `timed out after ${CURSOR_STATUS_TIMEOUT_MS / 1e3} s` : stripVTControlCharacters2(`${p.stdout}
1555
- ${p.stderr}`).trim().split("\n")[0]?.slice(0, 200) || `exit ${p.code}`;
1954
+ const detail = p.timedOut ? `timed out after ${CURSOR_STATUS_TIMEOUT_MS / 1e3} s` : signInDetail(stripVTControlCharacters2(`${p.stdout}
1955
+ ${p.stderr}`).trim()) || `exit ${p.code}`;
1556
1956
  last = { state, detail, output: stripVTControlCharacters2(`${p.stdout}
1557
1957
  ${p.stderr}`).slice(0, 2e3) };
1558
1958
  if (state === "signed_in" || state === "missing") break;
@@ -1613,13 +2013,13 @@ function stopLine(agent, left, what) {
1613
2013
  return `Stopped: the ${spec.label} agent could not run (out of usage or signed out). ${left} ${what}${left === 1 ? "" : "s"} left untouched and can be picked up again; the run was closed without a retry cooldown. Check: ${spec.bin} ${spec.status.join(" ")}`;
1614
2014
  }
1615
2015
  function registerWorkCommands(program) {
1616
- program.command("work").description("Fix reports with a coding agent on this machine (the Cursor CLI or Claude Code); pushes and opens the draft PR with your git and gh").option("--repo-dir <path>", "A clone of the app repo (only worktrees are created in it); not with --daemon").option("--project <id>", "Project id (overrides MUSHI_PROJECT_ID)").option("--agent <name>", "Local agent: cursor (cursor-agent, default) or claude (Claude Code, claude -p); with --daemon, overrides the worker config's agent").option("--model <id>", "Model for the agent (cursor: cursor-agent --list-models; claude: opus, sonnet, haiku or a claude-\u2026 id)").option("--max <n>", "Reports per run", "3").option("--report <id>", "Work on this report only").option("--followups", 'Instead of new reports: fix the Opus "fix first" findings on PRs mushi work opened, and push to them').option("--recheck", "Instead of fixing: run the check each open code-audit report was filed with again on the base branch (no agent, no tokens) and close those that no longer reproduce; with --dry-run, only count them").option("--keep", "Keep the worktree after the run").option("--dry-run", "Show what would run; change nothing").option("--any-repo", "Skip the check that the clone is a repo the key's project is linked to (a monorepo or a fork)").option("--json", "Machine-readable JSON output").option("--daemon", "Run as a local worker: register this machine, send a heartbeat every 60 s, take the console's lane settings and claim reports (set up with `mushi worker install`)").option("--worker-config <path>", "With --daemon: the lanes file (default ~/.config/mushi/worker.json)").action(async (opts) => {
2016
+ program.command("work").description("Fix reports with a coding agent on this machine (the Cursor CLI or Claude Code); pushes and opens the draft PR with your git and gh").option("--repo-dir <path>", "A clone of the app repo (only worktrees are created in it); not with --daemon").option("--project <id>", "Project id (overrides MUSHI_PROJECT_ID)").option("--agent <name>", "Local agent: cursor (cursor-agent, default) or claude (Claude Code, claude -p); with --daemon, overrides the worker config's agent").option("--model <id>", "Model for the agent (cursor: cursor-agent --list-models; claude: opus, sonnet, haiku or a claude-\u2026 id)").option("--max <n>", "Reports per run", "3").option("--report <id>", "Work on this report only").option("--followups", 'Instead of new reports: fix the Opus "fix first" findings on PRs mushi work opened, and push to them').option("--recheck", "Instead of fixing: run the check each open code-audit report was filed with again on the base branch (no agent, no tokens; shared wrappers followed) and close those that no longer reproduce; with --dry-run, only count them and show how the rest collapse into one report per pattern").option("--collapse-backlog", "Instead of fixing: group the open code-audit reports filed before pattern keys by root cause, on the base branch, and close each group's children as duplicates of its parent (ADR 0065); a dry run unless --apply").option("--apply", "With --collapse-backlog: make the change (every row is tagged, and the revert SQL is printed)").option("--collapse-tag <tag>", "With --collapse-backlog: the tag on every changed row (default collapse_<today, UTC>)").option("--apply-cap", "With --collapse-backlog: then keep only the best open reports up to the app's open cap (severity \xD7 confidence); the rest wait in code_audit_deferred and come back as slots free. Never a report with a live PR").option("--keep", "Keep the worktree after the run").option("--dry-run", "Show what would run; change nothing").option("--any-repo", "Skip the check that the clone is a repo the key's project is linked to (a monorepo or a fork)").option("--json", "Machine-readable JSON output").option("--daemon", "Run as a local worker: register this machine, send a heartbeat every 60 s, take the console's lane settings and claim reports (set up with `mushi worker install`)").option("--worker-config <path>", "With --daemon: the lanes file (default ~/.config/mushi/worker.json)").action(async (opts) => {
1617
2017
  const agent = parseLocalAgent(opts.agent);
1618
2018
  if (opts.daemon) {
1619
- if (opts.repoDir || opts.report || opts.followups || opts.recheck) {
2019
+ if (opts.repoDir || opts.report || opts.followups || opts.recheck || opts.collapseBacklog) {
1620
2020
  throw new MushiCliError("E_INVALID_INPUT", "--daemon takes its lanes and clones from the worker config, not from --repo-dir, --report or --followups.", "mushi worker install");
1621
2021
  }
1622
- const { runDaemon: runDaemon2 } = await import("./daemon-FM6M7TKK.js");
2022
+ const { runDaemon: runDaemon2 } = await import("./daemon-JPRYTZ2H.js");
1623
2023
  await runDaemon2({ configPath: opts.workerConfig, ...opts.agent !== void 0 ? { agent } : {}, ...opts.anyRepo ? { anyRepo: true } : {} });
1624
2024
  return;
1625
2025
  }
@@ -1638,6 +2038,16 @@ function registerWorkCommands(program) {
1638
2038
  `);
1639
2039
  const whoami = await readWhoami(cfg);
1640
2040
  if (!opts.anyRepo) await requireRightRepo(whoami, repoDir);
2041
+ if (opts.collapseBacklog) {
2042
+ if (opts.apply) requireWriteScope(cfg, whoami);
2043
+ const tag = opts.collapseTag ?? `collapse_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10).replace(/-/g, "_")}`;
2044
+ if (!/^collapse_\d{4}_\d{2}_\d{2}$/.test(tag)) throw new MushiCliError("E_INVALID_INPUT", "--collapse-tag must look like collapse_2026_11_21.", "mushi work --collapse-backlog --collapse-tag collapse_2026_11_21");
2045
+ if (!cfg.projectId) throw new MushiCliError("E_INVALID_INPUT", "mushi work --collapse-backlog needs a project.", "mushi work --collapse-backlog --project <id> --repo-dir <clone>");
2046
+ const out = await collapseBacklog(api, repoDir, { projectId: cfg.projectId, apply: !!opts.apply && !opts.dryRun, applyCap: !!opts.applyCap, tag, log });
2047
+ if (opts.json) process.stdout.write(`${JSON.stringify(out, null, 2)}
2048
+ `);
2049
+ return;
2050
+ }
1641
2051
  if (opts.recheck) {
1642
2052
  if (!opts.dryRun) requireWriteScope(cfg, whoami);
1643
2053
  const sweep = await recheckBacklog(api, repoDir, { dryRun: !!opts.dryRun, log });
@@ -2407,7 +2817,9 @@ function parseClaim(raw) {
2407
2817
  const reviewModel = a.reviewModel == null ? null : typeof a.reviewModel === "string" && MODEL_RE.test(a.reviewModel) ? a.reviewModel : void 0;
2408
2818
  if (reviewModel === void 0) return { ok: false, message: "the audit claim's review model is not a model id" };
2409
2819
  const left = typeof a.findingsLeft === "number" && Number.isInteger(a.findingsLeft) && a.findingsLeft >= 0 ? a.findingsLeft : 0;
2410
- return { ok: true, value: { kind: "audit", id: c.id, model, audit: { reviewModel, findingsLeft: left } } };
2820
+ const recheck = a.recheck === true;
2821
+ const propose = a.propose !== false;
2822
+ return { ok: true, value: { kind: "audit", id: c.id, model, audit: { reviewModel, findingsLeft: left, recheck, propose } } };
2411
2823
  }
2412
2824
  if (kind === "fresh_eyes") {
2413
2825
  const t = parseFreshEyesTarget(c.freshEyes);
@@ -2861,7 +3273,7 @@ function createDaemon(cfg, deps) {
2861
3273
  k.id,
2862
3274
  "audit",
2863
3275
  `audit pass (${k.audit.findingsLeft} finding(s) left this hour)`,
2864
- (signal, log) => (deps.auditPass ?? auditPass)(api, k.id, { repoDir: lane.local.repoDir, laneName: lane.local.name, agent, model: jobModel, reviewModel: model(k.audit.reviewModel) ?? null, log, signal })
3276
+ (signal, log) => (deps.auditPass ?? auditPass)(api, k.id, { repoDir: lane.local.repoDir, laneName: lane.local.name, agent, model: jobModel, reviewModel: model(k.audit.reviewModel) ?? null, recheck: k.audit.recheck, propose: k.audit.propose, log, signal })
2865
3277
  );
2866
3278
  } else if (k.kind === "fresh_eyes" && deps.freshEyes) {
2867
3279
  const run = deps.freshEyes;
@@ -32,10 +32,10 @@ import {
32
32
  saveConfig,
33
33
  savedSdkKeyFor,
34
34
  trySaveKeyToKeychain
35
- } from "./chunk-3LHOI34N.js";
35
+ } from "./chunk-XB3IJVAR.js";
36
36
  import {
37
37
  MUSHI_CLI_VERSION
38
- } from "./chunk-5DI4Q5BD.js";
38
+ } from "./chunk-3K53JXJ4.js";
39
39
  import {
40
40
  FRAMEWORKS,
41
41
  detectFramework,
@@ -2185,7 +2185,7 @@ async function maybeOfferConnect(credentials, options, _consoleBase) {
2185
2185
  if (p.isCancel(answer) || !answer) return;
2186
2186
  const endpoint = resolveCloudEndpoint(options.endpoint);
2187
2187
  try {
2188
- const { runConnect } = await import("./connect-ZVMQIYBI.js");
2188
+ const { runConnect } = await import("./connect-T62VV3TC.js");
2189
2189
  const saved = loadConfig();
2190
2190
  const result = await runConnect(
2191
2191
  {
@@ -2,10 +2,10 @@
2
2
  import {
3
3
  resolveSdkEnvKey,
4
4
  runConnect
5
- } from "./chunk-KEMUVMO7.js";
5
+ } from "./chunk-JW3JHZXS.js";
6
6
  import "./chunk-CG5KPP4S.js";
7
- import "./chunk-4Z5MWQS5.js";
8
- import "./chunk-UWPIVVCG.js";
7
+ import "./chunk-G3RJDBYO.js";
8
+ import "./chunk-SW53IBFM.js";
9
9
  import "./chunk-LGGE3LH7.js";
10
10
  export {
11
11
  resolveSdkEnvKey,
@@ -6,10 +6,10 @@ import {
6
6
  saveConfig,
7
7
  savedSdkKeyFor,
8
8
  waitForIngestReady
9
- } from "./chunk-3LHOI34N.js";
9
+ } from "./chunk-XB3IJVAR.js";
10
10
  import {
11
11
  MUSHI_MCP_PIN_SPEC
12
- } from "./chunk-5DI4Q5BD.js";
12
+ } from "./chunk-3K53JXJ4.js";
13
13
  import {
14
14
  detectFramework,
15
15
  envVarsToWrite,
@@ -12,9 +12,9 @@ import {
12
12
  runDaemon,
13
13
  stopHint,
14
14
  workerHostId
15
- } from "./chunk-ZOBSRRD3.js";
16
- import "./chunk-4Z5MWQS5.js";
17
- import "./chunk-UWPIVVCG.js";
15
+ } from "./chunk-ZNAK5DLR.js";
16
+ import "./chunk-G3RJDBYO.js";
17
+ import "./chunk-SW53IBFM.js";
18
18
  import "./chunk-LGGE3LH7.js";
19
19
  export {
20
20
  assertWorkerKey,
package/dist/index.js CHANGED
@@ -28,7 +28,7 @@ import {
28
28
  sanitizeEndpoint,
29
29
  sanitizeProjectId,
30
30
  writeMcpServerEntry
31
- } from "./chunk-KEMUVMO7.js";
31
+ } from "./chunk-JW3JHZXS.js";
32
32
  import {
33
33
  FRAMEWORKS,
34
34
  FRAMEWORK_IDS,
@@ -59,7 +59,7 @@ import {
59
59
  registerUxCommands,
60
60
  registerWorkCommands,
61
61
  validateWorkerConfig
62
- } from "./chunk-ZOBSRRD3.js";
62
+ } from "./chunk-ZNAK5DLR.js";
63
63
  import {
64
64
  CONFIG_PATH,
65
65
  MushiCliError,
@@ -99,11 +99,11 @@ import {
99
99
  tryLoadKeyFromKeychain,
100
100
  trySaveKeyToKeychain,
101
101
  trySaveWorkerKey
102
- } from "./chunk-4Z5MWQS5.js";
102
+ } from "./chunk-G3RJDBYO.js";
103
103
  import {
104
104
  MUSHI_CLI_VERSION,
105
105
  MUSHI_MCP_PIN_SPEC
106
- } from "./chunk-UWPIVVCG.js";
106
+ } from "./chunk-SW53IBFM.js";
107
107
  import {
108
108
  CLOUD_API_ENDPOINT,
109
109
  CLOUD_MCP_OAUTH_URL,
@@ -1639,7 +1639,7 @@ async function checkOnboardingStatus(config, _consoleBase, cwd, doFetch = global
1639
1639
  }
1640
1640
  async function checkVersionDrift(cwd, doFetch) {
1641
1641
  const checks = [];
1642
- const { MUSHI_CLI_VERSION: MUSHI_CLI_VERSION2 } = await import("./version-XXSOPUQR.js");
1642
+ const { MUSHI_CLI_VERSION: MUSHI_CLI_VERSION2 } = await import("./version-4FOYAOOB.js");
1643
1643
  if (MUSHI_CLI_VERSION2 === "0.0.0-dev") return checks;
1644
1644
  const parse2 = (v) => {
1645
1645
  const m = v.replace(/^[~^]/, "").match(/^(\d+)\.(\d+)\.(\d+)/);
@@ -2656,7 +2656,7 @@ async function maybeOfferConnect(credentials, options, _consoleBase) {
2656
2656
  if (p.isCancel(answer) || !answer) return;
2657
2657
  const endpoint = resolveCloudEndpoint(options.endpoint);
2658
2658
  try {
2659
- const { runConnect: runConnect2 } = await import("./connect-B2ZZPVWI.js");
2659
+ const { runConnect: runConnect2 } = await import("./connect-T4XXJHAQ.js");
2660
2660
  const saved = loadConfig();
2661
2661
  const result = await runConnect2(
2662
2662
  {
package/dist/init.js CHANGED
@@ -13,10 +13,10 @@ import {
13
13
  sampleBugSnippet,
14
14
  sanitizeSecret,
15
15
  snippetTarget
16
- } from "./chunk-MNIFWCTR.js";
16
+ } from "./chunk-ZTCOD6BX.js";
17
17
  import "./chunk-LFP3NPZT.js";
18
- import "./chunk-3LHOI34N.js";
19
- import "./chunk-5DI4Q5BD.js";
18
+ import "./chunk-XB3IJVAR.js";
19
+ import "./chunk-3K53JXJ4.js";
20
20
  import "./chunk-AWASJDQI.js";
21
21
  import "./chunk-2DMHQVRU.js";
22
22
  export {
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  MUSHI_CLI_VERSION,
4
4
  MUSHI_MCP_PIN_SPEC
5
- } from "./chunk-UWPIVVCG.js";
5
+ } from "./chunk-SW53IBFM.js";
6
6
  export {
7
7
  MUSHI_CLI_VERSION,
8
8
  MUSHI_MCP_PIN_SPEC
package/dist/version.d.ts CHANGED
@@ -14,6 +14,6 @@ declare const MUSHI_CLI_VERSION: string;
14
14
  * setup refreshes the pin. Synced to packages/mcp/package.json by
15
15
  * `scripts/sync-mcp-pin.mjs` — never hand-edit the version.
16
16
  */
17
- declare const MUSHI_MCP_PIN_SPEC = "@mushi-mushi/mcp@0.31.7";
17
+ declare const MUSHI_MCP_PIN_SPEC = "@mushi-mushi/mcp@0.31.8";
18
18
 
19
19
  export { MUSHI_CLI_VERSION, MUSHI_MCP_PIN_SPEC };
package/dist/version.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  MUSHI_CLI_VERSION,
3
3
  MUSHI_MCP_PIN_SPEC
4
- } from "./chunk-5DI4Q5BD.js";
4
+ } from "./chunk-3K53JXJ4.js";
5
5
  export {
6
6
  MUSHI_CLI_VERSION,
7
7
  MUSHI_MCP_PIN_SPEC
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  runInit
3
- } from "./chunk-MNIFWCTR.js";
3
+ } from "./chunk-ZTCOD6BX.js";
4
4
  import {
5
5
  FLAGS_HELP,
6
6
  UNKNOWN_COMMAND_EXIT,
@@ -11,8 +11,8 @@ import {
11
11
  scaffoldTemplate
12
12
  } from "./chunk-4JF7C3MY.js";
13
13
  import "./chunk-LFP3NPZT.js";
14
- import "./chunk-3LHOI34N.js";
15
- import "./chunk-5DI4Q5BD.js";
14
+ import "./chunk-XB3IJVAR.js";
15
+ import "./chunk-3K53JXJ4.js";
16
16
  import "./chunk-AWASJDQI.js";
17
17
  import "./chunk-2DMHQVRU.js";
18
18
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mushi-mushi/cli",
3
- "version": "0.40.5",
3
+ "version": "0.41.0",
4
4
  "license": "MIT",
5
5
  "description": "Mushi Mushi CLI: SDK setup, MCP wiring, triage. One place to improve AI-built apps: fix bugs, smooth user journeys and clean up the code.",
6
6
  "bin": {
@@ -1,8 +0,0 @@
1
- // src/version.ts
2
- var MUSHI_CLI_VERSION = true ? "0.40.5" : "0.0.0-dev";
3
- var MUSHI_MCP_PIN_SPEC = "@mushi-mushi/mcp@0.31.7";
4
-
5
- export {
6
- MUSHI_CLI_VERSION,
7
- MUSHI_MCP_PIN_SPEC
8
- };
@@ -1,10 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/version.ts
4
- var MUSHI_CLI_VERSION = true ? "0.40.5" : "0.0.0-dev";
5
- var MUSHI_MCP_PIN_SPEC = "@mushi-mushi/mcp@0.31.7";
6
-
7
- export {
8
- MUSHI_CLI_VERSION,
9
- MUSHI_MCP_PIN_SPEC
10
- };