neurastream 0.3.7 → 0.3.11

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.3.7",
3
+ "version": "0.3.11",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -36,6 +36,7 @@ import { activePlans, allowedAgents, enforceReadOnlyIndex, gitTop, indexPath, re
36
36
  import { defaultRunner } from "../core/mr-sweep.ts";
37
37
  import { allowAgents, denyAgents, invalidSlugs } from "../core/subagents.ts";
38
38
  import { runLabels } from "./labels.ts";
39
+ import { runRules } from "./rules.ts";
39
40
  import { runDiffCheck } from "./diff-check.ts";
40
41
 
41
42
  const BINS = [
@@ -119,6 +120,7 @@ export function helpText(): string {
119
120
  " trace step indexes",
120
121
  " neurastream labels assign <episode> --party plan|implementer|both --why <text>",
121
122
  " append a party override; the last ledger line wins",
123
+ " neurastream rules one line per rule: level, previous level, date, held_until when set; then the tuner bar",
122
124
  " neurastream diff-check [--staged | <rev>]",
123
125
  " the removal check (labels.removal_*): prints flagged",
124
126
  " file:line: text, exit 1 on hits",
@@ -180,6 +182,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
180
182
  if (cmd === "incident") return runIncident(args);
181
183
  if (cmd === "traces") return runTraces(args);
182
184
  if (cmd === "labels") return runLabels(args);
185
+ if (cmd === "rules") return runRules(args);
183
186
  if (cmd === "diff-check") return runDiffCheck(args);
184
187
  if (cmd === "workspace") return runWorkspace(args);
185
188
  if (cmd === "team") return runTeam(args);
@@ -0,0 +1,45 @@
1
+ // `neurastream rules` (plan 20261110_1746 P4b): one line per rule, read-only. The level is what
2
+ // levelFor reads, so a pinned, absent, or corrupt rule prints block. The one write is the corrupt
3
+ // file's guard line, through the same helper the daily tuner step uses (once per run).
4
+ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
5
+ import { PINNED, TUNABLE, levelFor, readLevels, type RuleLevels } from "../core/rule-levels.ts";
6
+ import { noteCorruptLevels } from "../core/watch.ts";
7
+
8
+ const USAGE = "usage: neurastream rules";
9
+
10
+ /** Every rule to print: the pinned and tunable kinds, then any other id the levels file names. */
11
+ function ruleIds(levels: RuleLevels): string[] {
12
+ const ids = new Set<string>([...PINNED, ...TUNABLE]);
13
+ for (const id of Object.keys(levels.rules)) ids.add(id);
14
+ return [...ids];
15
+ }
16
+
17
+ /** One line per rule, then the tuner bar (the file's `tuner.bar`, else the config's min_fires it starts at). */
18
+ export function rulesLines(cfg: Config): string[] {
19
+ const levels = readLevels(cfg);
20
+ const lines = ruleIds(levels).map(id => {
21
+ // The entry is read by own key for its display fields only; the level comes from levelFor.
22
+ const entry = Object.hasOwn(levels.rules, id) ? levels.rules[id] : undefined;
23
+ const hold = entry?.held_until === undefined ? "" : ` held_until=${entry.held_until}`;
24
+ return `${id} ${levelFor(levels, id)} prev=${entry?.prev ?? "-"} date=${entry?.date ?? "-"}${hold}`;
25
+ });
26
+ lines.push(`tuner bar ${levels.tuner?.bar ?? cfg.tuning.min_fires}`);
27
+ return lines;
28
+ }
29
+
30
+ export function runRules(args: string[], opts: { home?: string } = {}): number {
31
+ if (args.length > 0) {
32
+ console.error(USAGE);
33
+ return 2;
34
+ }
35
+ let cfg: Config;
36
+ try {
37
+ cfg = loadConfig(opts.home === undefined ? undefined : { home: opts.home });
38
+ } catch (err) {
39
+ console.error(err instanceof ConfigError ? err.message : String(err));
40
+ return 1;
41
+ }
42
+ if (noteCorruptLevels(cfg, readLevels(cfg))) console.error("rules: the levels file is corrupt; every rule reads as block");
43
+ for (const line of rulesLines(cfg)) console.log(line);
44
+ return 0;
45
+ }
@@ -245,6 +245,23 @@ export interface Config {
245
245
  /** Release verdict: fewer Main tool calls than this on either side reads "not enough data yet" — no verdict. */
246
246
  release_min_calls: number;
247
247
  };
248
+ /** Self-pruning (plan 20261110_1746): the tuner steps existing rules down and back up. */
249
+ tuning: {
250
+ /** The daily step runs when this is true. */
251
+ enabled: boolean;
252
+ /** A rule with at least this many fires in the window can step down. */
253
+ min_fires: number;
254
+ /** Useful share below this, with enough fires, steps the rule down one level. */
255
+ max_useful: number;
256
+ /** Days a level change is judged over, and how long an undo holds a rule. */
257
+ window_days: number;
258
+ /** Days an off rule stays off before a probation raise to tell. */
259
+ probation_days: number;
260
+ /** Guard ids are scored and stepped only when this is true. Default false. */
261
+ guards: boolean;
262
+ /** Rule ids probation never raises. */
263
+ keep_off: string[];
264
+ };
248
265
  machine: {
249
266
  load_over_cores: number;
250
267
  load_max: number;
@@ -685,6 +702,23 @@ function check(cfg: Config): void {
685
702
  if (!Number.isInteger(cfg.watch.release_min_calls) || cfg.watch.release_min_calls < 1) {
686
703
  throw new ConfigError("watch.release_min_calls must be an integer >= 1");
687
704
  }
705
+ if (typeof cfg.tuning.enabled !== "boolean") throw new ConfigError("tuning.enabled must be a boolean");
706
+ if (!Number.isInteger(cfg.tuning.min_fires) || cfg.tuning.min_fires < 1) {
707
+ throw new ConfigError("tuning.min_fires must be an integer >= 1");
708
+ }
709
+ if (typeof cfg.tuning.max_useful !== "number" || !(cfg.tuning.max_useful > 0 && cfg.tuning.max_useful <= 1)) {
710
+ throw new ConfigError("tuning.max_useful must be a number in (0, 1]");
711
+ }
712
+ if (!Number.isInteger(cfg.tuning.window_days) || cfg.tuning.window_days < 1) {
713
+ throw new ConfigError("tuning.window_days must be an integer >= 1");
714
+ }
715
+ if (!Number.isInteger(cfg.tuning.probation_days) || cfg.tuning.probation_days < 1) {
716
+ throw new ConfigError("tuning.probation_days must be an integer >= 1");
717
+ }
718
+ if (typeof cfg.tuning.guards !== "boolean") throw new ConfigError("tuning.guards must be a boolean");
719
+ if (!Array.isArray(cfg.tuning.keep_off) || cfg.tuning.keep_off.some((id) => typeof id !== "string")) {
720
+ throw new ConfigError("tuning.keep_off must be a list of strings");
721
+ }
688
722
  for (const p of cfg.metrics.correction_patterns) {
689
723
  try {
690
724
  new RegExp(p, "i");
@@ -33,6 +33,7 @@ import type { Config } from "./config.ts";
33
33
  import { openIncidents, ownerMessagesFile, ownerSaid, readOwnerAnswers, readOwnerMessages, type IncidentView, type OwnerMessage, writeOwnerStore } from "./incidents.ts";
34
34
  import { ownerText, UNANSWERED_PREFIX } from "./rollover.ts";
35
35
  import { ownerLogFile, recordOwnerLog } from "./owner-log.ts";
36
+ import { levelFor, readLevels } from "./rule-levels.ts";
36
37
  import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
37
38
  import { defaultRunner, listOpenMrs, mentioned, type CommandRunner, type OpenMr } from "./mr-sweep.ts";
38
39
  import { unlandedRows } from "./wip-check.ts";
@@ -59,8 +60,9 @@ export interface PlanEditDecision extends Decision {
59
60
  note?: string;
60
61
  }
61
62
 
62
- function deny(reason: string): Decision {
63
- return { allow: false, reason };
63
+ /** Every refusal names its guard rule id (plan 20261110_1746 P8a); the id ends the text as ` [rule <id>]`. */
64
+ function deny(reason: string, rule: string): Decision {
65
+ return { allow: false, reason: `${reason} [rule ${rule}]` };
64
66
  }
65
67
 
66
68
  /** A raw target that names a plan: under a docs/plans/ directory, or a plan file name (YYYYMMDD_HHMM_*.md). */
@@ -1429,11 +1431,12 @@ function editWindow(e: ToolEvent, input: Record<string, unknown>, cfg: Config):
1429
1431
  if (w.used.length && now - w.windowStart >= cfg.guards.main_window_min * 60_000) w.used = [];
1430
1432
  if (w.used.length >= limit) {
1431
1433
  const mins = Math.ceil((w.windowStart + cfg.guards.main_window_min * 60_000 - now) / 60_000);
1432
- log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${w.used.length} edits (tier ${tier}): ${files.join(",")}`);
1434
+ log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${w.used.length} edits (tier ${tier}): ${files.join(",")} rule=main.edit-window`);
1433
1435
  return deny(
1434
1436
  `main-guard: tier ${tier} — Main already changed project files ${w.used.length} times in this ${cfg.guards.main_window_min}-minute window ` +
1435
1437
  `(${limitName} ${limit}; resets in ${mins} min). Main writes plans, not code: put the work in a plan ` +
1436
1438
  `(listed in ${q.INDEX}, phase-0 blockers first) and spawn an implementer. Changes so far: ${w.used.join(", ")}`,
1439
+ "main.edit-window",
1437
1440
  );
1438
1441
  }
1439
1442
  if (!w.used.length) w.windowStart = now;
@@ -1571,7 +1574,7 @@ function bypassLaunch(command: string, cfg: Config, spawner: Spawner, runs?: Run
1571
1574
  function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config, runs?: RunSource): Decision {
1572
1575
  if (e.tool === "task") {
1573
1576
  const why = taskLaunch(input, cfg, e.runningJobs, "main", runs);
1574
- return why ? deny(`main-guard: ${why}`) : ALLOW;
1577
+ return why ? deny(`main-guard: ${why}`, "main.task-launch") : ALLOW;
1575
1578
  }
1576
1579
  if (cfg.guards.shell_tools.includes(e.tool)) {
1577
1580
  // Strict landing gate (20261025_1940 P2, P5): in tier strict every push/merge waits for the
@@ -1579,12 +1582,12 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config, run
1579
1582
  // it goes through. Opinionated and full keep today's allowance. Owner-only rules above are
1580
1583
  // untouched.
1581
1584
  if (landingCommand(input) && currentTier(cfg) === "strict" && !takeGo(cfg)) {
1582
- log(cfg.paths.guard_log, "BLOCK landing: tier strict, no approve phrase");
1583
- return deny(`main-guard: tier strict — type "${cfg.autonomy.go_phrase}" to approve one push/merge`);
1585
+ log(cfg.paths.guard_log, "BLOCK landing: tier strict, no approve phrase rule=main.push-merge");
1586
+ return deny(`main-guard: tier strict — type "${cfg.autonomy.go_phrase}" to approve one push/merge`, "main.push-merge");
1584
1587
  }
1585
1588
  const command = String(input?.command ?? input?.code ?? "");
1586
1589
  const why = bypassLaunch(command, cfg, "main", runs);
1587
- if (why) return deny(`main-guard: ${why}`);
1590
+ if (why) return deny(`main-guard: ${why}`, "main.bypass-launch");
1588
1591
  }
1589
1592
  return editWindow(e, input, cfg);
1590
1593
  }
@@ -1653,26 +1656,41 @@ export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)(?:[^/]+\/)*[^/]+\.md
1653
1656
  * plus, for Main, the spawn gates and the project-file edit window.
1654
1657
  */
1655
1658
  export function checkTool(e: ToolEvent, cfg: Config, runs?: RunSource): Decision {
1659
+ return tuned(checkToolRules(e, cfg, runs), cfg);
1660
+ }
1661
+
1662
+ /** Applies the owner's rule level to a refusal. Only with `tuning.guards` on; a refusal with no `[rule <id>]` suffix, or a pinned, unset or corrupt id, stays `block`. */
1663
+ function tuned(d: Decision, cfg: Config): Decision {
1664
+ if (d.allow || !cfg.tuning.guards) return d;
1665
+ const id = /\[rule ([\w.-]+)\]$/.exec(d.reason)?.[1];
1666
+ if (!id) return d;
1667
+ const level = levelFor(readLevels(cfg), id);
1668
+ if (level === "block") return d;
1669
+ return { allow: true, reason: level === "tell" ? d.reason : "" };
1670
+ }
1671
+
1672
+ function checkToolRules(e: ToolEvent, cfg: Config, runs?: RunSource): Decision {
1656
1673
  const lock = e.agent === "sub" ? reviewLockProblem(e, cfg) : null;
1657
1674
  if (lock) {
1658
- log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} review lock: ${lock}`);
1659
- return deny(`plan-guard: ${lock}`);
1675
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} review lock: ${lock} rule=tool.review-lock`);
1676
+ return deny(`plan-guard: ${lock}`, "tool.review-lock");
1660
1677
  }
1661
1678
  if (cfg.guards.skip_tools.includes(e.tool)) return ALLOW;
1662
1679
  const input = e.input ?? {};
1663
1680
  // Starting the owner page (plan 20261024_2230 P3c) is the owner's systemd move, never an
1664
1681
  // agent's, unlocked or not: refused plan-guard style like a protected-file write.
1665
1682
  if (cfg.guards.shell_tools.includes(e.tool) && startsOwnerUi(input)) {
1666
- log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} ui-start: ${String(input.command ?? "")}`);
1683
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} ui-start: ${String(input.command ?? "")} rule=tool.ui-start`);
1667
1684
  return deny(
1668
1685
  "plan-guard: starting the owner page (neurastream workspace, or systemctl --user start/restart/enable of neurastream-workspace) is the owner's move, not an agent's.",
1686
+ "tool.ui-start",
1669
1687
  );
1670
1688
  }
1671
1689
  // claim release --force frees another Main's claim (plan 20261027_1300 P4): the owner's
1672
1690
  // terminal move, refused for every agent like the ui-start, plan-guard style.
1673
1691
  if (cfg.guards.shell_tools.includes(e.tool) && forceClaimRelease(input)) {
1674
- log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} claim-force: ${String(input.command ?? "")}`);
1675
- return deny("plan-guard: claim release --force frees another Main's claim; that is the owner's move, in a terminal.");
1692
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} claim-force: ${String(input.command ?? "")} rule=tool.claim-force`);
1693
+ return deny("plan-guard: claim release --force frees another Main's claim; that is the owner's move, in a terminal.", "tool.claim-force");
1676
1694
  }
1677
1695
  // The caller may know paths the text search cannot see (structured edits); union, never shrink.
1678
1696
  const paths: string[] = [];
@@ -1684,8 +1702,8 @@ export function checkTool(e: ToolEvent, cfg: Config, runs?: RunSource): Decision
1684
1702
  // sees the edit (plan 20261028_1600 P4j). A plan is named by its absolute path, for every agent.
1685
1703
  const relPlan = PLAN_WRITE_TOOLS[e.tool] ? relative.find(isPlanName) : undefined;
1686
1704
  if (relPlan) {
1687
- log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} relative plan path: ${relPlan}`);
1688
- return deny(`plan-guard: use the absolute plan path, not ${relPlan}. The plan gate cannot see a relative one.`);
1705
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} relative plan path: ${relPlan} rule=tool.relative-plan`);
1706
+ return deny(`plan-guard: use the absolute plan path, not ${relPlan}. The plan gate cannot see a relative one.`, "tool.relative-plan");
1689
1707
  }
1690
1708
  // Notify secrets: no agent, main or sub, reads a webhook URL — with or without the unlock.
1691
1709
  // A call that changes a secret is not a read: its target goes through the protected-write
@@ -1698,8 +1716,8 @@ export function checkTool(e: ToolEvent, cfg: Config, runs?: RunSource): Decision
1698
1716
  if (!secretPaths.includes(p)) secretPaths.push(p);
1699
1717
  const secretHit = notifySecretReadHit(secretPaths.filter(p => !writes.includes(p)), cfg);
1700
1718
  if (secretHit) {
1701
- log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} notify secret: ${secretHit}`);
1702
- return deny(`plan-guard: ${secretHit} is a notify secret path. Only the owner touches the webhook files, in a terminal.`);
1719
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} notify secret: ${secretHit} rule=tool.notify-secret`);
1720
+ return deny(`plan-guard: ${secretHit} is a notify secret path. Only the owner touches the webhook files, in a terminal.`, "tool.notify-secret");
1703
1721
  }
1704
1722
  // Main writes its own rollover note unattended (the note turn has nobody to ask). Only a Write
1705
1723
  // of a .md directly in <state>/rollover/ is exempt; shell writes, subagents and relaunch.json stay refused.
@@ -1710,7 +1728,7 @@ export function checkTool(e: ToolEvent, cfg: Config, runs?: RunSource): Decision
1710
1728
  : writes;
1711
1729
  const hit = protectedHit(openWrites, cfg);
1712
1730
  if (hit && !unlocked(cfg)) {
1713
- log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} protected: ${hit}`);
1731
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} protected: ${hit} rule=tool.protected`);
1714
1732
  // The plan index (plan 20261031_0911 P2) is guard surface like the rest, but unlike the
1715
1733
  // others an agent has a sanctioned way to change it: the queue add/move CLI through
1716
1734
  // writeIndex. Name it, so the refusal says what to do instead of naming the unlock.
@@ -1719,6 +1737,7 @@ export function checkTool(e: ToolEvent, cfg: Config, runs?: RunSource): Decision
1719
1737
  `plan-guard: ${hit} is a protected guard file. Only the owner changes it (unlock: \`touch ${q.UNLOCK}\` in a terminal${
1720
1738
  cfg.guards.chat_unlock ? `, or type \`unlock ${cfg.guards.unlock_minutes}\` in chat` : ""
1721
1739
  }, valid ${cfg.guards.unlock_minutes} min).${viaQueue}`,
1740
+ "tool.protected",
1722
1741
  );
1723
1742
  }
1724
1743
  if (e.agent === "main") {
@@ -1726,13 +1745,13 @@ export function checkTool(e: ToolEvent, cfg: Config, runs?: RunSource): Decision
1726
1745
  // sed -i or heredoc into a plan would skip them, so plans change through edit/write only.
1727
1746
  const shellPlan = e.tool !== "write" && e.tool !== "edit" ? writes.find(p => MAIN_PLAN_FILE.test(p)) : undefined;
1728
1747
  if (shellPlan) {
1729
- log(cfg.paths.plan_guard_log, `BLOCK main tool=${e.tool} shell write to plan ${shellPlan}`);
1730
- return deny(`plan-guard: ${shellPlan} is a plan file: change it with the edit or write tool (close or cancel it with queue-close / queue-cancel).`);
1748
+ log(cfg.paths.plan_guard_log, `BLOCK main tool=${e.tool} shell write to plan ${shellPlan} rule=tool.shell-plan`);
1749
+ return deny(`plan-guard: ${shellPlan} is a plan file: change it with the edit or write tool (close or cancel it with queue-close / queue-cancel).`, "tool.shell-plan");
1731
1750
  }
1732
1751
  const stop = mainCallStop(e, cfg);
1733
1752
  if (stop) {
1734
- log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${readWindow().mainCalls} calls this turn`);
1735
- return deny(stop);
1753
+ log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${readWindow().mainCalls} calls this turn rule=main.call-budget`);
1754
+ return deny(stop, "main.call-budget");
1736
1755
  }
1737
1756
  const d = mainTool(e, input, cfg, runs);
1738
1757
  if (!d.allow) return d;
@@ -1744,16 +1763,16 @@ export function checkTool(e: ToolEvent, cfg: Config, runs?: RunSource): Decision
1744
1763
  const cap = subCallCap(e.agentId, cfg);
1745
1764
  const why = subRules(e, input, paths, writes, cfg, cap);
1746
1765
  if (why) {
1747
- log(cfg.paths.plan_guard_log, `BLOCK sub:${e.agentId} tool=${e.tool} ${why}`);
1748
- return deny(`plan-guard: ${why}`);
1766
+ log(cfg.paths.plan_guard_log, `BLOCK sub:${e.agentId} tool=${e.tool} ${why} rule=sub.rule`);
1767
+ return deny(`plan-guard: ${why}`, "sub.rule");
1749
1768
  }
1750
1769
  // A sub's own launch passes the same spawn gates as Main's (plan 20261028_1600 P4i).
1751
1770
  let launch: string | null = null;
1752
1771
  if (e.tool === "task") launch = taskLaunch(input, cfg, e.runningJobs, "sub", runs);
1753
1772
  else if (cfg.guards.shell_tools.includes(e.tool)) launch = bypassLaunch(String(input?.command ?? input?.code ?? ""), cfg, "sub", runs);
1754
1773
  if (launch) {
1755
- log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} ${launch}`);
1756
- return deny(`plan-guard: ${launch}`);
1774
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} ${launch} rule=sub.launch`);
1775
+ return deny(`plan-guard: ${launch}`, "sub.launch");
1757
1776
  }
1758
1777
  const n = e.calls + 1;
1759
1778
  // The warn band has the global width (sub_max_calls - sub_warn_calls) ending at the cap;
@@ -1998,16 +2017,20 @@ function recordTeamSpawns(teams: RoutedTeam[], agentIds: string[], cfg: Config):
1998
2017
  * original paths (the extension spawn event and a `task` tool call); the brief names the plan.
1999
2018
  */
2000
2019
  export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner, runs?: RunSource): Decision {
2020
+ return tuned(checkSpawnRules(e, cfg, runner, runs), cfg);
2021
+ }
2022
+
2023
+ function checkSpawnRules(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner, runs?: RunSource): Decision {
2001
2024
  const pending = q.cancelPending();
2002
2025
  if (pending) {
2003
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: cancel pending (${pending.words})`);
2004
- return deny(`main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`);
2026
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: cancel pending (${pending.words}) rule=spawn.cancel-pending`);
2027
+ return deny(`main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`, "spawn.cancel-pending");
2005
2028
  }
2006
2029
  const allowed = q.allowedAgents();
2007
2030
  if (!allowed.has(e.agent))
2008
- return deny(`main-guard: ${e.agent}: agent "${e.agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`);
2031
+ return deny(`main-guard: ${e.agent}: agent "${e.agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`, "spawn.agent-allowed");
2009
2032
  if (e.invocationKind !== "task")
2010
- return deny("main-guard: spawn implementers with the task tool (the plan gate checks its brief).");
2033
+ return deny("main-guard: spawn implementers with the task tool (the plan gate checks its brief).", "spawn.task-tool");
2011
2034
  // P4 (plan 20261031_1207): every gate's refusal lands in one numbered verdict; nothing
2012
2035
  // short-circuits, so Main sees all the problems in one round trip.
2013
2036
  const problems: string[] = [];
@@ -2040,15 +2063,15 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
2040
2063
  const verdict = spawnVerdict(e.agent, problems, named.length ? named : briefPlans(e.brief, cfg).map(p => p.file), e.runningJobs, cfg);
2041
2064
  if (verdict) {
2042
2065
  for (const p of problems) {
2043
- if (p === role.problem) log(cfg.paths.plan_guard_log, `BLOCK ${e.agent} ${e.name ?? "(unnamed)"} review spawn: ${p}`);
2044
- else log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${p}`);
2066
+ if (p === role.problem) log(cfg.paths.plan_guard_log, `BLOCK ${e.agent} ${e.name ?? "(unnamed)"} review spawn: ${p} rule=spawn.verdict`);
2067
+ else log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${p} rule=spawn.verdict`);
2045
2068
  }
2046
- return deny(`main-guard: ${verdict}`);
2069
+ return deny(`main-guard: ${verdict}`, "spawn.verdict");
2047
2070
  }
2048
2071
  const held = claimGate(named, cfg, { agentIds: e.name ? [e.name] : [], unnamed: !e.name, runs });
2049
2072
  if (held) {
2050
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${held}`);
2051
- return deny(`main-guard: ${held}`);
2073
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${held} rule=spawn.claim-held`);
2074
+ return deny(`main-guard: ${held}`, "spawn.claim-held");
2052
2075
  }
2053
2076
  // The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
2054
2077
  const staffing: Record<string, string[]> = {};
@@ -27,6 +27,7 @@ import type { Run, TraceEvent } from "./adapter.ts";
27
27
  import type { Config } from "./config.ts";
28
28
  import { nowSec, strftime } from "./clock.ts";
29
29
  import { log } from "./guards.ts";
30
+ import { levelFor, readLevels, TUNABLE } from "./rule-levels.ts";
30
31
  import { addIncident, type IncidentView } from "./incidents.ts";
31
32
  import type { GuardBlock } from "./metrics.ts";
32
33
  import { maskEvidence, verifyClaims, type Claim, type RelatedRun } from "./trace-claims.ts";
@@ -41,6 +42,8 @@ export interface Finding {
41
42
  evidence?: string;
42
43
  /** Stable identity of the problem; an open incident with it dedupes (count + last seen). */
43
44
  fingerprint?: string;
45
+ /** The guard rule id the refused call's text names (` [rule <id>]`); the tuner keys its level on it. */
46
+ rule?: string;
44
47
  }
45
48
 
46
49
  function iso(t: number): string {
@@ -172,6 +175,7 @@ export function blockThenBypass(events: TraceEvent[], windowSec: number, similar
172
175
  });
173
176
  if (!bypass) continue;
174
177
  const head = (refused.text ?? "").replace(/\s+/g, " ").trim();
178
+ const rule = /\[rule ([\w.-]+)\]/.exec(refused.text ?? "")?.[1];
175
179
  const sha = createHash("sha256").update(head).digest("hex").slice(0, 16);
176
180
  const blockedArgs = maskEvidence(JSON.stringify(block.args).slice(0, 200));
177
181
  const allowedArgs = maskEvidence(JSON.stringify(bypass.args).slice(0, 200));
@@ -180,6 +184,7 @@ export function blockThenBypass(events: TraceEvent[], windowSec: number, similar
180
184
  summary: `possible guard false positive: ${head.slice(0, 120)}`,
181
185
  evidence: `blocked ${block.tool} at ${iso(block.ts)}: ${blockedArgs}; same tool allowed at ${iso(bypass.ts)}: ${allowedArgs}`,
182
186
  fingerprint: `block-then-bypass:${block.tool}:${sha}`,
187
+ rule,
183
188
  });
184
189
  }
185
190
  return out;
@@ -272,6 +277,18 @@ export interface DetectorInput {
272
277
  mainSince?: number;
273
278
  }
274
279
 
280
+ /**
281
+ * Tell and off for a tunable kind: one guard-log tally line, no incident. Block, a corrupt
282
+ * file, and every non-tunable kind fall through so the fold opens the incident as today.
283
+ */
284
+ export function suppressedByLevel(cfg: Config, kind: string, summary: string): boolean {
285
+ if (!(TUNABLE as readonly string[]).includes(kind)) return false;
286
+ const level = levelFor(readLevels(cfg), kind);
287
+ if (level === "block") return false;
288
+ log(cfg.paths.guard_log, `rule ${kind} ${level}: ${summary}`);
289
+ return true;
290
+ }
291
+
275
292
  /**
276
293
  * Runs every detector that has its inputs, folds findings into the incident store and logs each
277
294
  * one. Detector failures are logged, never thrown. Returns the incidents (new or deduped).
@@ -281,9 +298,10 @@ export function runDetectors(cfg: Config, input: DetectorInput, now = nowSec()):
281
298
  const attempt = (name: string, findings: () => Finding[]): void => {
282
299
  try {
283
300
  for (const f of findings()) {
301
+ if (suppressedByLevel(cfg, f.kind, f.summary)) continue;
284
302
  const { incident, deduped } = addIncident(
285
303
  cfg,
286
- { source: "realtime", kind: f.kind, summary: f.summary, evidence: f.evidence, fingerprint: f.fingerprint },
304
+ { source: "realtime", kind: f.kind, summary: f.summary, evidence: f.evidence, fingerprint: f.fingerprint, rule: f.rule },
287
305
  now,
288
306
  );
289
307
  log(
@@ -326,6 +344,7 @@ export function runDetectors(cfg: Config, input: DetectorInput, now = nowSec()):
326
344
  if (input.unreported) {
327
345
  for (const f of input.unreported!) {
328
346
  try {
347
+ if (suppressedByLevel(cfg, "unreported-finding", f.summary)) continue;
329
348
  const { incident, deduped } = addIncident(
330
349
  cfg,
331
350
  { source: "traces", kind: "unreported-finding", summary: f.summary, evidence: f.evidence, fingerprint: `unreported-finding:${f.agent}:${f.target}` },
@@ -27,6 +27,8 @@ export interface IncidentRec {
27
27
  ts: number;
28
28
  count: number;
29
29
  lastSeen: number;
30
+ /** The guard rule id a block-then-bypass finding refused; guard scoring reads it (P9a). */
31
+ rule?: string;
30
32
  }
31
33
 
32
34
  export type ResolutionRec =
@@ -57,6 +59,8 @@ export interface IncidentInput {
57
59
  evidence?: string;
58
60
  /** Stable identity of the problem; detectors pass one, `incident add` derives it from the text. */
59
61
  fingerprint?: string;
62
+ /** The guard rule id a block-then-bypass finding refused (P9a). */
63
+ rule?: string;
60
64
  }
61
65
 
62
66
  export function incidentsFile(cfg: Config): string {
@@ -106,6 +110,7 @@ function parseLine(line: string): IncidentRec | ResolutionRec | ProposalRec | nu
106
110
  ts: rec.ts,
107
111
  count: typeof rec.count === "number" && rec.count >= 1 ? rec.count : 1,
108
112
  lastSeen: typeof rec.lastSeen === "number" ? rec.lastSeen : rec.ts,
113
+ rule: typeof rec.rule === "string" ? rec.rule : undefined,
109
114
  };
110
115
  }
111
116
 
@@ -185,6 +190,7 @@ export function addIncident(cfg: Config, input: IncidentInput, now = nowSec()):
185
190
  ts: now,
186
191
  count: 1,
187
192
  lastSeen: now,
193
+ rule: input.rule,
188
194
  };
189
195
  mkdirSync(dirname(file), { recursive: true });
190
196
  appendFileSync(file, `${JSON.stringify(rec)}\n`);
@@ -219,6 +219,8 @@ export function m4(runs: Run[], w: Window, patterns: RegExp[]): M4 {
219
219
  export interface GuardBlock {
220
220
  ts: number;
221
221
  reason: string;
222
+ /** The guard rule id from the line's ` rule=<id>` tail; undefined for lines written before P8a. */
223
+ rule?: string;
222
224
  }
223
225
 
224
226
  /** Groups reasons by shape: paths cut to 40 chars, digit runs collapsed to N, and every
@@ -238,7 +240,8 @@ export function parseBlocks(text: string): GuardBlock[] {
238
240
  if (!m) continue;
239
241
  const ts = Date.parse(m[1] ?? "") / 1000;
240
242
  if (Number.isNaN(ts)) continue;
241
- out.push({ ts, reason: reasonKey(m[2] ?? "") });
243
+ const rule = /\srule=(\S+)$/.exec(m[2] ?? "")?.[1];
244
+ out.push({ ts, reason: reasonKey(m[2] ?? ""), rule });
242
245
  }
243
246
  return out;
244
247
  }
@@ -41,6 +41,12 @@ export function newEntryId(atMs: number, rand: (n: number) => Uint8Array = rando
41
41
  return atMs.toString(36).padStart(9, "0") + Buffer.from(rand(4)).toString("hex");
42
42
  }
43
43
 
44
+ // The second an entry id was minted at; undefined for an id that is not in newEntryId's form.
45
+ export function entryIdSec(id: string): number | undefined {
46
+ if (!/^[0-9a-z]{9}[0-9a-f]{8}$/.test(id)) return undefined;
47
+ return Math.floor(Number.parseInt(id.slice(0, 9), 36) / 1000);
48
+ }
49
+
44
50
  // The one writer: the recall dir is 0700 and the file 0600, also when they pre-exist looser.
45
51
  export function appendJsonLines(file: string, rows: readonly object[]): void {
46
52
  const dir = dirname(file);
@@ -7,7 +7,7 @@ import { join } from "node:path";
7
7
  import { nowSec } from "./clock.ts";
8
8
  import type { Config } from "./config.ts";
9
9
  import { tryLock } from "./file-lock.ts";
10
- import { appendJsonLines, type LogEntry, ownerLogDir, ownerLogFile, readEntries, readLines } from "./owner-log.ts";
10
+ import { appendJsonLines, entryIdSec, type LogEntry, ownerLogDir, ownerLogFile, readEntries, readLines } from "./owner-log.ts";
11
11
  import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
12
12
 
13
13
  export interface CompleteRequest {
@@ -143,7 +143,7 @@ function parseRow(line: string): TopicRow | undefined {
143
143
  if (v === null || typeof v !== "object" || typeof v.from !== "string" || typeof v.to !== "string") return undefined;
144
144
  if (typeof v.at !== "number") return undefined;
145
145
  if (v.skipped === true) {
146
- return { from: v.from, to: v.to, at: v.at, skipped: true, why: typeof v.why === "string" ? v.why : "" };
146
+ return { from: v.from, to: v.to, at: entryIdSec(v.from) ?? v.at, skipped: true, why: typeof v.why === "string" ? v.why : "" };
147
147
  }
148
148
  if (
149
149
  typeof v.title !== "string" ||
@@ -159,7 +159,7 @@ function parseRow(line: string): TopicRow | undefined {
159
159
  return {
160
160
  from: v.from,
161
161
  to: v.to,
162
- at: v.at,
162
+ at: entryIdSec(v.from) ?? v.at,
163
163
  open: v.open,
164
164
  title: v.title,
165
165
  keywords: v.keywords,
@@ -40,6 +40,7 @@ interface Snap {
40
40
  m4: M4;
41
41
  m5: M5;
42
42
  m6: M6;
43
+ m9: number | null;
43
44
  }
44
45
 
45
46
  function day(t: number): string {
@@ -50,16 +51,25 @@ function day(t: number): string {
50
51
  export function snap(cfg: Config, source: RunSource, events: Ev[], blocks: GuardBlock[], incidents: IncidentView[], w: Window): Snap {
51
52
  const runs = source.listRuns(w.from);
52
53
  const patterns = cfg.metrics.correction_patterns.map((p) => new RegExp(p, "i"));
54
+ const m1v = m1({ runs, events }, w);
55
+ const flips = flipRecords(cfg.paths.score_state).filter((f) => inWindow(f.ts, w)).length;
53
56
  return {
54
- m1: m1({ runs, events }, w),
57
+ m1: m1v,
55
58
  m2: m2({ runs, events }, w),
56
59
  m3: m3(events, w),
57
60
  m4: m4(runs, w, patterns),
58
61
  m5: m5(blocks, events, w),
59
62
  m6: m6(incidents, w),
63
+ m9: adjustedPerDollar(m1v.accepts, flips, m1v.worker + m1v.main),
60
64
  };
61
65
  }
62
66
 
67
+ /** M9 (plan P7): adjusted merges per dollar. Each flip cancels one accepted merge, so a net-bad
68
+ * window reads negative. Null when nothing was spent in the window. */
69
+ export function adjustedPerDollar(accepts: number, flips: number, dollars: number): number | null {
70
+ return dollars > 0 ? (accepts - flips) / dollars : null;
71
+ }
72
+
63
73
  export interface M6 {
64
74
  /** Incidents opened in the window. */
65
75
  opened: number;
@@ -108,6 +118,7 @@ export interface KindStat {
108
118
  kind: string;
109
119
  opened: number;
110
120
  planned: number;
121
+ fixed: number;
111
122
  dismissed: number;
112
123
  dismissRate: number;
113
124
  }
@@ -126,6 +137,7 @@ export function kindStats(incidents: IncidentView[], w: Window): KindStat[] {
126
137
  kind,
127
138
  opened: list.length,
128
139
  planned: list.filter((i) => i.resolution?.type === "plan").length,
140
+ fixed: list.filter((i) => i.resolution?.type === "fixed").length,
129
141
  dismissed,
130
142
  dismissRate: dismissed / list.length,
131
143
  };
@@ -255,6 +267,8 @@ export function rowsOf(c: Snap, p: Snap): Row[] {
255
267
  { key: "m4_questions", name: "M4 Main questions", cur: c.m4.questions, prev: p.m4.questions, fmt: num, rank: true },
256
268
  { key: "m4_users", name: "M4 owner messages", cur: c.m4.users, prev: p.m4.users, fmt: num, rank: false },
257
269
  { key: "m5", name: "M5 guard blocks", cur: c.m5.blocks, prev: p.m5.blocks, fmt: num, rank: true },
270
+ // M9 is higher-better, so it is shown in the table but never ranked as the worst change.
271
+ { key: "m9", name: "M9 adjusted merges per $", cur: c.m9, prev: p.m9, fmt: (v: number | null) => (v === null ? "n/a" : v.toFixed(3)), rank: false },
258
272
  ];
259
273
  }
260
274
 
@@ -280,6 +294,7 @@ function detail(c: Snap): string[] {
280
294
  `M4 owner messages ${c.m4.users}, corrections ${c.m4.corrections}, Main questions ${c.m4.questions}`,
281
295
  `M5 guard blocks ${c.m5.blocks}, false alarms ${c.m5.falseAlarms}; top reasons: ${reasons}`,
282
296
  `M6 incidents ${c.m6.opened} opened, ${c.m6.planned} planned, ${c.m6.dismissed} dismissed, ${c.m6.fixed} fixed; median open→fixed ${median}`,
297
+ `M9 adjusted merges per $ ${c.m9 === null ? "n/a" : c.m9.toFixed(3)}`,
283
298
  ];
284
299
  }
285
300
 
@@ -378,8 +393,8 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
378
393
  ...(limitEvents.length > 0
379
394
  ? [`Main limited: ${limitMinutes >= 60 ? `${Math.round(limitMinutes / 6) / 10} h` : `${limitMinutes} min`} over ${limitEvents.length} episodes`]
380
395
  : []),
381
- "Dismiss rate by kind (opened, planned, dismissed):",
382
- ...kindStats(incidents, cur).map((k) => `- ${k.kind}: ${k.opened}, ${k.planned}, ${k.dismissed} (${Math.round(k.dismissRate * 100)}% dismissed)`),
396
+ "Dismiss rate by kind (opened, planned, fixed, dismissed):",
397
+ ...kindStats(incidents, cur).map((k) => `- ${k.kind}: ${k.opened}, ${k.planned}, ${k.fixed}, ${k.dismissed} (${Math.round(k.dismissRate * 100)}% dismissed)`),
383
398
  ];
384
399
  // P5b: the label ledger's flips in the report. An empty ledger adds no lines at all, so
385
400
  // byte-identical output on a machine that never ran labels.
@@ -0,0 +1,140 @@
1
+ // Rule levels (plan 20261110_1746 P1): one JSON file under the queue state dir, already
2
+ // protected, so agents cannot write it. `block` is today's behaviour, `tell` is a log line
3
+ // with no incident, `off` is dropped. A missing file is empty (every rule blocks). A file
4
+ // that cannot be parsed is corrupt in memory only: every level still reads as block, and
5
+ // nothing here logs — the daily step and the rules command each write that one line.
6
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
7
+ import { dirname, join } from "node:path";
8
+ import type { Config } from "./config.ts";
9
+
10
+ export type Level = "block" | "tell" | "off";
11
+
12
+ export interface RuleEntry {
13
+ level: Level;
14
+ prev?: Level;
15
+ date: string;
16
+ /** Set by a probation raise; the daily step clears it when that window is judged. */
17
+ probation?: true;
18
+ /** Epoch seconds. While this is in the future the daily step does not move the rule. */
19
+ held_until?: number;
20
+ }
21
+
22
+ export interface RuleLevels {
23
+ /** UTC day of the last step that moved a level. The undo's anchor. */
24
+ date?: string;
25
+ /** UTC day of the last daily scan, moved or not. The one-step-per-day gate. */
26
+ checked?: string;
27
+ rules: Record<string, RuleEntry>;
28
+ tuner?: { bar: number };
29
+ /** In memory only. Never written. A corrupt file reads as block and is not overwritten. */
30
+ corrupt?: true;
31
+ }
32
+
33
+ /** Kinds the tuner must never drop: watcher liveness, the undo's own evidence, and the guard rules
34
+ * that guard the owner's own surfaces (landing, notify secrets, protected files, claims, UI start). */
35
+ export const PINNED = ["release-regression", "beat-failed", "beat-stale", "main.push-merge", "tool.notify-secret", "tool.protected", "tool.claim-force", "tool.ui-start", "tool.review-lock"] as const;
36
+
37
+ /** Detector and watcher kinds the tuner may step. Everything else is never scored. */
38
+ export const TUNABLE = [
39
+ "ledger-contradiction",
40
+ "tool-crash",
41
+ "block-loop",
42
+ "owner-correction",
43
+ "claim-unbacked",
44
+ "suspicious-action",
45
+ "block-then-bypass",
46
+ "unreported-finding",
47
+ "beat-failed",
48
+ "beat-stale",
49
+ "unit-failed",
50
+ "ci-red-main",
51
+ "ci-red-mr",
52
+ ] as const;
53
+
54
+ const LEVELS: readonly Level[] = ["block", "tell", "off"];
55
+
56
+ function isObj(value: unknown): value is Record<string, unknown> {
57
+ return typeof value === "object" && value !== null && !Array.isArray(value);
58
+ }
59
+
60
+ function isLevel(value: unknown): value is Level {
61
+ return typeof value === "string" && (LEVELS as readonly string[]).includes(value);
62
+ }
63
+
64
+ function entryOf(value: unknown): RuleEntry | null {
65
+ if (!isObj(value) || !isLevel(value.level) || typeof value.date !== "string") return null;
66
+ if ("prev" in value && !isLevel(value.prev)) return null;
67
+ if ("probation" in value && value.probation !== true) return null;
68
+ if ("held_until" in value && (typeof value.held_until !== "number" || !Number.isFinite(value.held_until))) return null;
69
+ const entry: RuleEntry = { level: value.level, date: value.date };
70
+ if (isLevel(value.prev)) entry.prev = value.prev;
71
+ if (value.probation === true) entry.probation = true;
72
+ if (typeof value.held_until === "number") entry.held_until = value.held_until;
73
+ return entry;
74
+ }
75
+
76
+ function parsed(value: unknown): RuleLevels | null {
77
+ if (!isObj(value) || !isObj(value.rules)) return null;
78
+ if ("date" in value && typeof value.date !== "string") return null;
79
+ if ("checked" in value && typeof value.checked !== "string") return null;
80
+ if ("tuner" in value && (!isObj(value.tuner) || typeof value.tuner.bar !== "number" || !Number.isFinite(value.tuner.bar))) return null;
81
+ const rules: Record<string, RuleEntry> = {};
82
+ for (const id of Object.keys(value.rules)) {
83
+ const entry = entryOf(value.rules[id]);
84
+ if (!entry) return null;
85
+ rules[id] = entry;
86
+ }
87
+ const levels: RuleLevels = { rules };
88
+ if (typeof value.date === "string") levels.date = value.date;
89
+ if (typeof value.checked === "string") levels.checked = value.checked;
90
+ if (isObj(value.tuner) && typeof value.tuner.bar === "number") levels.tuner = { bar: value.tuner.bar };
91
+ return levels;
92
+ }
93
+
94
+ /** Missing file = empty. Unreadable or invalid JSON = corrupt, and the file is left as it is. */
95
+ export function readLevels(cfg: Config): RuleLevels {
96
+ const path = join(cfg.paths.queue_state, "rule-levels.json");
97
+ if (!existsSync(path)) return { rules: {} };
98
+ let text: string;
99
+ try {
100
+ text = readFileSync(path, "utf8");
101
+ } catch {
102
+ return { rules: {}, corrupt: true };
103
+ }
104
+ try {
105
+ const levels = parsed(JSON.parse(text));
106
+ return levels ?? { rules: {}, corrupt: true };
107
+ } catch {
108
+ return { rules: {}, corrupt: true };
109
+ }
110
+ }
111
+
112
+ /**
113
+ * The only read path. Absent, corrupt, pinned, or an inherited name (`constructor`,
114
+ * `__proto__`) is block. Callers must not index `levels.rules` themselves.
115
+ */
116
+ export function levelFor(levels: RuleLevels, id: string): Level {
117
+ if ((PINNED as readonly string[]).includes(id)) return "block";
118
+ if (levels.corrupt) return "block";
119
+ if (!Object.hasOwn(levels.rules, id)) return "block";
120
+ const entry = levels.rules[id];
121
+ return entry && isLevel(entry.level) ? entry.level : "block";
122
+ }
123
+
124
+ /** Temp file in the same directory, then rename, so a reader never sees a half-written file. */
125
+ export function atomicWrite(path: string, text: string): void {
126
+ const tmp = `${path}.${process.pid}.tmp`;
127
+ writeFileSync(tmp, text);
128
+ renameSync(tmp, path);
129
+ }
130
+
131
+ /** Writes the levels file. The in-memory `corrupt` flag is never stored. */
132
+ export function writeLevels(cfg: Config, levels: RuleLevels): void {
133
+ const path = join(cfg.paths.queue_state, "rule-levels.json");
134
+ mkdirSync(dirname(path), { recursive: true });
135
+ const stored: Omit<RuleLevels, "corrupt"> = { rules: levels.rules };
136
+ if (levels.date !== undefined) stored.date = levels.date;
137
+ if (levels.checked !== undefined) stored.checked = levels.checked;
138
+ if (levels.tuner !== undefined) stored.tuner = levels.tuner;
139
+ atomicWrite(path, `${JSON.stringify(stored)}\n`);
140
+ }
@@ -0,0 +1,154 @@
1
+ // Kind scoring for the tuner (plan 20261110_1746 P3). Pure over the incidents and the
2
+ // guard-log text the caller injects: no clock, no files, no home. The daily step applies
3
+ // `tuning`; this function only counts.
4
+ import type { Config } from "./config.ts";
5
+ import { readIncidents, type IncidentView } from "./incidents.ts";
6
+ import { inWindow, readBlocks, windows, type Ev, type Window } from "./metrics.ts";
7
+ import { PINNED, TUNABLE, levelFor, readLevels, type Level, type RuleEntry, type RuleLevels } from "./rule-levels.ts";
8
+
9
+ export type Tuning = Config["tuning"];
10
+
11
+ export interface KindScore {
12
+ kind: string;
13
+ /** Incidents opened in the window plus tell/off tally lines in the window. */
14
+ fires: number;
15
+ planned: number;
16
+ fixed: number;
17
+ dismissed: number;
18
+ /** (planned + fixed) / fires, or 0 when nothing fired. */
19
+ usefulShare: number;
20
+ /** The tuner row only: rule-undo events over demotions, both in the window. */
21
+ undoRate?: number;
22
+ }
23
+
24
+ /** What the daily step reads from a score row: a kind's or a guard id's window score. */
25
+ export type Scored = Pick<KindScore, "kind" | "fires" | "usefulShare">;
26
+
27
+ const TALLY = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z) \[[^\]]*\] rule (\S+) (tell|off): /;
28
+ /** The tuner's own scorecard row (plan 20261110_1746 P6). Not a rule: decideStep never moves it. */
29
+ export const TUNER = "tuner";
30
+ /** The highest bar the undo rate can reach. */
31
+ export const BAR_CAP = 320;
32
+ const RANK: Record<Level, number> = { off: 0, tell: 1, block: 2 };
33
+
34
+ /** The tuner bar after a step: doubled (capped at BAR_CAP) when more than half the window's demotions were undone; never lowered. */
35
+ export function nextBar(bar: number, undoRate: number): number {
36
+ return undoRate > 0.5 ? Math.max(bar, Math.min(BAR_CAP, bar * 2)) : bar;
37
+ }
38
+
39
+ export function scoreKinds(incidents: IncidentView[], logText: string, w: Window, tuning: Tuning, events: Ev[]): KindScore[] {
40
+ if (!Number.isFinite(tuning.min_fires) || !Number.isFinite(tuning.max_useful)) {
41
+ throw new Error("tuning thresholds must be numbers");
42
+ }
43
+ const opened = new Map<string, IncidentView[]>();
44
+ for (const kind of TUNABLE) opened.set(kind, []);
45
+ for (const incident of incidents) {
46
+ if (!opened.has(incident.kind) || !inWindow(incident.ts, w)) continue;
47
+ opened.get(incident.kind)!.push(incident);
48
+ }
49
+ const tallies = new Map<string, number>();
50
+ for (const line of logText.split("\n")) {
51
+ const hit = TALLY.exec(line);
52
+ if (!hit) continue;
53
+ const ts = Date.parse(hit[1]!) / 1000;
54
+ const kind = hit[2]!;
55
+ if (!opened.has(kind) || !inWindow(ts, w)) continue;
56
+ tallies.set(kind, (tallies.get(kind) ?? 0) + 1);
57
+ }
58
+ const rows: KindScore[] = TUNABLE.map((kind) => {
59
+ const list = opened.get(kind) ?? [];
60
+ const fires = list.length + (tallies.get(kind) ?? 0);
61
+ const planned = list.filter((i) => i.resolution?.type === "plan").length;
62
+ const fixed = list.filter((i) => i.resolution?.type === "fixed").length;
63
+ const dismissed = list.filter((i) => i.resolution?.type === "dismiss").length;
64
+ return { kind, fires, planned, fixed, dismissed, usefulShare: fires === 0 ? 0 : (planned + fixed) / fires };
65
+ });
66
+ const demotions = events.filter((e) => e.type === "rule-level" && inWindow(Number(e.ts), w) && RANK[e.to as Level] < RANK[e.from as Level]).length;
67
+ const undos = events.filter((e) => e.type === "rule-undo" && inWindow(Number(e.ts), w)).length;
68
+ return [...rows, { kind: TUNER, fires: demotions, planned: 0, fixed: 0, dismissed: 0, usefulShare: 0, undoRate: undos / Math.max(1, demotions) }];
69
+ }
70
+
71
+ /** Per guard id (plan 20261110_1746 P9a): fires are the window's BLOCK lines naming the id; usefulShare is (fires - bypassed) / fires, where bypassed counts the window's block-then-bypass incidents naming it (clamped at 0). Pinned ids are never scored. */
72
+ export function scoreGuards(cfg: Config, now: number): Scored[] {
73
+ const w = windows(now, cfg.tuning.window_days).cur;
74
+ const fires = new Map<string, number>();
75
+ for (const b of readBlocks(cfg)) {
76
+ if (b.rule === undefined || !inWindow(b.ts, w)) continue;
77
+ fires.set(b.rule, (fires.get(b.rule) ?? 0) + 1);
78
+ }
79
+ const bypassed = new Map<string, number>();
80
+ for (const i of readIncidents(cfg)) {
81
+ if (i.kind !== "block-then-bypass" || i.rule === undefined || !inWindow(i.ts, w)) continue;
82
+ bypassed.set(i.rule, (bypassed.get(i.rule) ?? 0) + 1);
83
+ }
84
+ const ids = new Set([...fires.keys(), ...Object.keys(readLevels(cfg).rules)]);
85
+ return [...ids]
86
+ .filter(id => !(PINNED as readonly string[]).includes(id))
87
+ .map(id => {
88
+ const n = fires.get(id) ?? 0;
89
+ return { kind: id, fires: n, usefulShare: n === 0 ? 0 : Math.max(0, n - (bypassed.get(id) ?? 0)) / n };
90
+ });
91
+ }
92
+
93
+ const DAY_MS = 86_400_000;
94
+
95
+ /** One level move the daily step made; `probe` marks a probation raise (off -> tell). */
96
+ export interface RuleMove {
97
+ rule: string;
98
+ from: Level;
99
+ to: Level;
100
+ probe: boolean;
101
+ }
102
+
103
+ export interface StepResult {
104
+ levels: RuleLevels;
105
+ moves: RuleMove[];
106
+ }
107
+
108
+ /**
109
+ * The daily tuner step (plan 20261110_1746 P4), pure: the caller reads the levels and scores,
110
+ * writes the returned levels and appends the moves. At most one move per rule. Pinned rules and
111
+ * rules under `held_until` never move; a probation ends after `window_days` and is judged then;
112
+ * a `keep_off` rule is never probation-raised. `checked` is always today; `date` only on a move. A `bar` above min_fires raises the down-step threshold for every rule; the tuner row never moves.
113
+ */
114
+ export function decideStep(levels: RuleLevels, scores: Scored[], now: number, today: string, tuning: Tuning, bar = 0): StepResult {
115
+ const rules: Record<string, RuleEntry> = { ...levels.rules };
116
+ const moves: RuleMove[] = [];
117
+ const move = (rule: string, from: Level, to: Level, entry: RuleEntry, probe = false) => {
118
+ rules[rule] = entry;
119
+ moves.push({ rule, from, to, probe });
120
+ };
121
+ for (const s of scores) {
122
+ const id = s.kind;
123
+ if (id === TUNER) continue;
124
+ if ((PINNED as readonly string[]).includes(id)) continue;
125
+ const own: RuleEntry | undefined = levels.rules[id];
126
+ if (own?.held_until !== undefined && own.held_until > now) continue;
127
+ const level = levelFor(levels, id);
128
+ const noisy = s.fires >= tuning.min_fires;
129
+ const useless = s.usefulShare < tuning.max_useful;
130
+ const tightens = s.fires >= Math.max(tuning.min_fires, bar);
131
+ const age = own ? Math.round((Date.parse(today) - Date.parse(own.date)) / DAY_MS) : 0;
132
+ if (level === "off" && own) {
133
+ if (!noisy) move(id, "off", "tell", { level: "tell", prev: "off", date: today });
134
+ else if (!tuning.keep_off.includes(id) && age >= tuning.probation_days) {
135
+ move(id, "off", "tell", { level: "tell", prev: "off", date: today, probation: true }, true);
136
+ }
137
+ } else if (level === "tell" && own) {
138
+ if (own.probation && age < tuning.window_days) continue;
139
+ if (!noisy) move(id, "tell", "block", { level: "block", prev: "tell", date: today });
140
+ else if (useless && tightens) move(id, "tell", "off", { level: "off", prev: "tell", date: today });
141
+ else if (own.probation) {
142
+ const kept: RuleEntry = { level: own.level, date: own.date };
143
+ if (own.prev !== undefined) kept.prev = own.prev;
144
+ if (own.held_until !== undefined) kept.held_until = own.held_until;
145
+ rules[id] = kept;
146
+ }
147
+ } else if (level === "block" && tightens && useless) {
148
+ move(id, "block", "tell", { level: "tell", prev: "block", date: today });
149
+ }
150
+ }
151
+ const next: RuleLevels = { ...levels, rules, checked: today };
152
+ if (moves.length > 0) next.date = today;
153
+ return { levels: next, moves };
154
+ }
package/src/core/watch.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  // `ci-flaky` metric when a commit goes red then green.
13
13
 
14
14
  import { spawnSync } from "node:child_process";
15
- import { existsSync } from "node:fs";
15
+ import { existsSync, readFileSync } from "node:fs";
16
16
  import { join } from "node:path";
17
17
  import { Glob } from "bun";
18
18
  import type { Config } from "./config.ts";
@@ -20,9 +20,9 @@ import type { RunSource } from "./adapter.ts";
20
20
  import { readEvents } from "./agent-score.ts";
21
21
  import { strftime } from "./clock.ts";
22
22
  import { readBeats, type Heartbeat } from "./heartbeat.ts";
23
- import { runDetectorsGated, type GatedInputs } from "./incident-detectors.ts";
23
+ import { runDetectorsGated, suppressedByLevel, type GatedInputs } from "./incident-detectors.ts";
24
24
  import { log, readStaffingEntries } from "./guards.ts";
25
- import { appendMetric, inWindow, readBlocks, readMetricEvents, reasonKey, type Window } from "./metrics.ts";
25
+ import { appendMetric, inWindow, readBlocks, readMetricEvents, reasonKey, windows, type Window } from "./metrics.ts";
26
26
  import { notifyProviders, waitingOwnerMessages } from "./notify.ts";
27
27
  import { addIncident, dismissIncident, openIncidents, readIncidents, type IncidentView } from "./incidents.ts";
28
28
  import { m7, rowsOf, silentFailures, snap } from "./report.ts";
@@ -30,6 +30,8 @@ import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
30
30
  import { ciScan } from "./ci.ts";
31
31
  import type { CommandRunner } from "./mr-sweep.ts";
32
32
  import type { ReleaseTag } from "./results.ts";
33
+ import { levelFor, readLevels, writeLevels, type Level, type RuleLevels } from "./rule-levels.ts";
34
+ import { decideStep, nextBar, scoreGuards, scoreKinds, TUNER } from "./rule-tuning.ts";
33
35
 
34
36
  /** One failed user unit, as the lister reports it. */
35
37
  export interface FailedUnit {
@@ -235,6 +237,7 @@ export function watchOnce(cfg: Config, deps: WatchDeps): WatchReport {
235
237
  const deduped: IncidentView[] = [];
236
238
  const posts: string[] = [];
237
239
  for (const p of problems) {
240
+ if (suppressedByLevel(cfg, p.kind, p.summary)) continue;
238
241
  const { incident, deduped: seen } = addIncident(
239
242
  cfg,
240
243
  { source: "watch", kind: p.kind, summary: p.summary, evidence: p.evidence, fingerprint: p.fingerprint },
@@ -271,6 +274,12 @@ export function watchOnce(cfg: Config, deps: WatchDeps): WatchReport {
271
274
  notify: text => deps.notify(cfg.secrets.redact ? redactSecrets(text, loadKnownSecrets(cfg), cfg.secrets.extra_patterns).text : text),
272
275
  });
273
276
  }
277
+ // (e1) P5b: a WORSE rule-level verdict puts back the rule that change moved (before the daily step).
278
+ if (deps.source) {
279
+ ruleLevelVerdicts(cfg, { now, source: deps.source, notify: text => deps.notify(cfg.secrets.redact ? redactSecrets(text, loadKnownSecrets(cfg), cfg.secrets.extra_patterns).text : text) });
280
+ }
281
+ // (e2) P4: the daily rule-tuning step, once per UTC day (the `checked` gate).
282
+ tuneRules(cfg, now, text => deps.notify(cfg.secrets.redact ? redactSecrets(text, loadKnownSecrets(cfg), cfg.secrets.extra_patterns).text : text));
274
283
  // (f) P9: an owner message that crossed notify.answer_within_min with no hand-back counts M8,
275
284
  // one metric per message — the ledger is the once-only marker, not per-pass state.
276
285
  let ownerWaits = 0;
@@ -284,6 +293,95 @@ export function watchOnce(cfg: Config, deps: WatchDeps): WatchReport {
284
293
  return { opened, deduped, closed, detectors, ownerWaits };
285
294
  }
286
295
 
296
+ // ---- P4: the daily rule-tuning step (plan 20261110_1746): the levels move by the scores.
297
+
298
+ /** The one guard line for a corrupt levels file, true when the file is corrupt. The daily step and `neurastream rules` each call it once per run; readLevels never logs. */
299
+ export function noteCorruptLevels(cfg: Config, levels: RuleLevels): boolean {
300
+ if (!levels.corrupt) return false;
301
+ log(cfg.paths.guard_log, `rule-levels: ${join(cfg.paths.queue_state, "rule-levels.json")} is corrupt; every rule reads as block`);
302
+ return true;
303
+ }
304
+
305
+ /** One tuner step per UTC day (the `checked` gate). A corrupt levels file is skipped with one
306
+ * guard line and nothing written; each move is one ledger metric and one notify line. */
307
+ export function tuneRules(cfg: Config, now: number, notify: (text: string) => void): void {
308
+ if (!cfg.tuning.enabled) return;
309
+ const levels = readLevels(cfg);
310
+ if (noteCorruptLevels(cfg, levels)) return;
311
+ const today = new Date(now * 1000).toISOString().slice(0, 10);
312
+ if (levels.checked === today) return;
313
+ const logText = existsSync(cfg.paths.guard_log) ? readFileSync(cfg.paths.guard_log, "utf8") : "";
314
+ const w = windows(now, cfg.tuning.window_days).cur;
315
+ const scores = scoreKinds(readIncidents(cfg), logText, w, cfg.tuning, readMetricEvents(cfg));
316
+ const guards = cfg.tuning.guards ? scoreGuards(cfg, now) : [];
317
+ const oldBar = levels.tuner?.bar ?? cfg.tuning.min_fires;
318
+ const bar = nextBar(oldBar, scores.find(s => s.kind === TUNER)?.undoRate ?? 0);
319
+ const step = decideStep(levels, [...scores, ...guards], now, today, cfg.tuning, bar);
320
+ writeLevels(cfg, bar === oldBar ? step.levels : { ...step.levels, tuner: { bar } });
321
+ for (const m of step.moves) appendMetric(cfg, { type: m.probe ? "rule-probe" : "rule-level", rule: m.rule, from: m.from, to: m.to, ts: now });
322
+ const parts = step.moves.map(m => `${m.rule} ${m.from}→${m.to}`);
323
+ if (bar !== oldBar) parts.push(`tuner bar ${oldBar}->${bar}`);
324
+ if (parts.length > 0) notify(`rule tuning: ${parts.join("; ")}`);
325
+ }
326
+
327
+ // ---- P5b: an undo on WORSE — a rule-level change that reads WORSE puts back the rule it moved.
328
+
329
+ const UNDO_DAY_SEC = 86_400;
330
+ const UNDO_CHANGE_TYPES = new Set(["rule-level", "rule-probe", "rule-undo"]);
331
+
332
+ /** One rule put back to the level it had before the change that moved it. */
333
+ export interface RuleUndo {
334
+ rule: string;
335
+ from: string;
336
+ to: string;
337
+ }
338
+
339
+ /** Judges each rule-level change once, after its window closes (the `rule-undo-check` marker is the once-only record). On WORSE the rule that change moved goes back to the level it had before, held for window_days, if no later step has moved it and no hold is in force. Corrupt levels are skipped. */
340
+ export function ruleLevelVerdicts(cfg: Config, deps: Pick<ReleaseVerdictDeps, "now" | "source" | "notify">): RuleUndo[] {
341
+ const levels = readLevels(cfg);
342
+ if (levels.corrupt) return [];
343
+ const { now } = deps;
344
+ const holdSec = cfg.tuning.window_days * UNDO_DAY_SEC;
345
+ const metrics = readMetricEvents(cfg);
346
+ const changes = metrics
347
+ .filter(e => UNDO_CHANGE_TYPES.has(String(e.type)))
348
+ .map(e => ({ type: String(e.type), rule: String(e.rule), ts: Number(e.ts), from: e.from as Level, to: e.to as Level }));
349
+ const judged = new Set(metrics.filter(e => e.type === "rule-undo-check").map(e => `${e.rule}@${e.change}`));
350
+ const due = changes
351
+ .filter(c => c.type === "rule-level" && !judged.has(`${c.rule}@${c.ts}`))
352
+ .map(c => {
353
+ const later = changes.filter(o => o.rule === c.rule && o.ts > c.ts).map(o => o.ts);
354
+ return { c, end: Math.min(c.ts + holdSec, ...later) };
355
+ })
356
+ .filter(({ end }) => now >= end)
357
+ .toSorted((a, b) => a.c.ts - b.c.ts);
358
+ const rules: RuleLevels["rules"] = { ...levels.rules };
359
+ const undos: RuleUndo[] = [];
360
+ const today = new Date(now * 1000).toISOString().slice(0, 10);
361
+ for (const { c, end } of due.slice(-VERDICT_MAX_PER_RUN)) {
362
+ const before: Window = { from: c.ts - (end - c.ts), to: c.ts };
363
+ const after: Window = { from: c.ts, to: end };
364
+ // A change of the same rule inside the before-window makes the before reading mixed: no judgment.
365
+ const contaminated = changes.some(o => o.rule === c.rule && o.ts >= before.from && o.ts < c.ts);
366
+ const verdict = contaminated ? "no-before" : (judgeWindows(cfg, `rule ${c.rule}`, before, after, { source: deps.source })?.verdict ?? "no-data");
367
+ appendMetric(cfg, { type: "rule-undo-check", rule: c.rule, change: c.ts, verdict, ts: now });
368
+ if (verdict !== "WORSE") continue;
369
+ // Only this change's own rule goes back, and only if no later step has moved it (its level is
370
+ // still the one this change left) and no hold is in force.
371
+ if (levelFor({ ...levels, rules }, c.rule) !== c.to) continue;
372
+ const held = rules[c.rule]?.held_until;
373
+ if (held !== undefined && held > now) continue;
374
+ rules[c.rule] = { level: c.from, prev: c.to, date: today, held_until: now + holdSec };
375
+ undos.push({ rule: c.rule, from: c.to, to: c.from });
376
+ appendMetric(cfg, { type: "rule-undo", rule: c.rule, from: c.to, to: c.from, ts: now });
377
+ }
378
+ if (undos.length > 0) {
379
+ writeLevels(cfg, { ...levels, rules });
380
+ deps.notify(`rule undo (WORSE): ${undos.map(u => `${u.rule} ${u.from}→${u.to}`).join("; ")}`);
381
+ }
382
+ return undos;
383
+ }
384
+
287
385
  // ---- P11: the release verdict — is the new version better or worse? ----
288
386
 
289
387
  /** The inputs of one verdict pass. Tags and the run source are injected: core never runs git or
@@ -398,13 +496,21 @@ export function releaseVerdicts(cfg: Config, deps: ReleaseVerdictDeps): ReleaseV
398
496
  return out;
399
497
  }
400
498
 
401
- /** Judges one closed after-window against the same-length before window; null reads "not enough data yet". */
402
- function judgeRelease(cfg: Config, tag: string, before: Window, after: Window, deps: ReleaseVerdictDeps): ReleaseVerdict | null {
499
+ /** What one pair of windows reads: the verdict, its post, and the number a WORSE verdict rests on. */
500
+ export interface WindowJudgement {
501
+ verdict: VerdictWord;
502
+ post: string;
503
+ /** The number behind a WORSE verdict (null otherwise); `dailyKey` is the daily-check metric it may fold into. */
504
+ worst: { name: string; vals: string; dailyKey: string | null } | null;
505
+ }
506
+
507
+ /** Judges two windows: the verdict and its post, no write and no incident. Null reads "not enough data yet". */
508
+ export function judgeWindows(cfg: Config, label: string, before: Window, after: Window, deps: { source: RunSource }): WindowJudgement | null {
403
509
  const incidents = readIncidents(cfg);
404
510
  // Watcher gap: a not-running incident open at any time in either window means that window's
405
511
  // watcher-fed numbers read ~0 for want of a watcher — no verdict is possible.
406
512
  if (incidents.some(i => i.fingerprint === "watch:not-running" && (overlapsWindow(i, before) || overlapsWindow(i, after)))) {
407
- return { tag, verdict: "watcher-off", post: `${tag}: watcher off, no verdict` };
513
+ return { verdict: "watcher-off", post: `${label}: watcher off, no verdict`, worst: null };
408
514
  }
409
515
  const callsOf = (w: Window) => deps.source.listRuns(w.from).filter(r => r.kind === "main" && inWindow(r.lastWriteAt, w)).reduce((s, r) => s + r.calls, 0);
410
516
  const bc = callsOf(before);
@@ -490,18 +596,25 @@ function judgeRelease(cfg: Config, tag: string, before: Window, after: Window, d
490
596
  const fresh = nums.filter(n => n.beforeCount === 0 && pctOf(n) === null).map(n => n.name);
491
597
  const freshLine = fresh.length === 0 ? "" : `${(fresh.length > 4 ? [...fresh.slice(0, 4), `+${fresh.length - 4} more`] : fresh).join(", ")} new, not compared`;
492
598
  const thinLine = thin.length === 0 ? "" : `${thin.join(", ")} thin, not compared`;
493
- const post = `${tag}: ${verdict} — ${[...parts, freshLine, thinLine].filter(p => p !== "").join(", ")}`;
494
-
495
- if (verdict === "WORSE") {
496
- const top = worseOnes.toSorted((p, q) => Math.abs(q.pct) - Math.abs(p.pct))[0];
497
- const name = top ? top.n.name : "downgrade";
498
- const vals = top ? `${fmtNum(top.n.before!)}→${fmtNum(top.n.after!)}` : `${downgrade!.from}→${downgrade!.to}`;
499
- // The daily/weekly check may already hold today's open incident on this metric: the shared
500
- // fingerprint dedups into it instead of doubling the story.
501
- const fingerprint = top?.n.dailyKey !== undefined ? `daily:${top.n.dailyKey}:${strftime(deps.now, "%Y-%m-%d")}` : `release:${tag}:${name}`;
502
- addIncident(cfg, { source: "watch", kind: "release-regression", summary: `release ${tag} worse: ${name} ${vals}`, evidence: post, fingerprint }, deps.now);
599
+ const post = `${label}: ${verdict} — ${[...parts, freshLine, thinLine].filter(p => p !== "").join(", ")}`;
600
+
601
+ if (verdict !== "WORSE") return { verdict, post, worst: null };
602
+ const top = worseOnes.toSorted((p, q) => Math.abs(q.pct) - Math.abs(p.pct))[0];
603
+ const worst = top
604
+ ? { name: top.n.name, vals: `${fmtNum(top.n.before!)}→${fmtNum(top.n.after!)}`, dailyKey: top.n.dailyKey ?? null }
605
+ : { name: "downgrade", vals: `${downgrade!.from}→${downgrade!.to}`, dailyKey: null };
606
+ return { verdict, post, worst };
607
+ }
608
+
609
+ /** Judges one closed after-window against the same-length before window; null reads "not enough data yet". A WORSE verdict opens its one incident; the daily/weekly check's open incident on the same metric is folded into, not doubled. */
610
+ function judgeRelease(cfg: Config, tag: string, before: Window, after: Window, deps: ReleaseVerdictDeps): ReleaseVerdict | null {
611
+ const j = judgeWindows(cfg, tag, before, after, deps);
612
+ if (j === null) return null;
613
+ if (j.worst !== null) {
614
+ const fingerprint = j.worst.dailyKey !== null ? `daily:${j.worst.dailyKey}:${strftime(deps.now, "%Y-%m-%d")}` : `release:${tag}:${j.worst.name}`;
615
+ addIncident(cfg, { source: "watch", kind: "release-regression", summary: `release ${tag} worse: ${j.worst.name} ${j.worst.vals}`, evidence: j.post, fingerprint }, deps.now);
503
616
  }
504
- return { tag, verdict, post };
617
+ return { tag, verdict: j.verdict, post: j.post };
505
618
  }
506
619
 
507
620
  /** The plan files a timer run treats as staffed: a plan whose newest spawn (staffing.json) names tasks and is newer than `ciRedHours` before `now`. An older spawn's agent is gone, so its red MR is not held back (I-20261031-265). A timer run has no live job list, so the spawn record is the only signal it has. */
@@ -231,6 +231,15 @@ watch: # the watcher (src/core/watch.ts): heartbeats, fail
231
231
  release_regress_pct: 25 # release verdict: any group but owner pain worse by this percent over the before window reads WORSE
232
232
  release_min_calls: 300 # release verdict: fewer Main tool calls on either side reads "not enough data yet", no verdict
233
233
 
234
+ tuning: # the tuner steps existing rules down and back up (src/core/rule-tuning.ts)
235
+ enabled: true # the daily step runs
236
+ min_fires: 20 # fires in the window before a rule can step down
237
+ max_useful: 0.10 # useful share below this, with enough fires, steps down one level
238
+ window_days: 7 # days a level change is judged over, and how long an undo holds
239
+ probation_days: 7 # days an off rule stays off before a raise to tell
240
+ guards: false # guard ids are scored and stepped only when this is true
241
+ keep_off: [] # rule ids probation never raises
242
+
234
243
  machine:
235
244
  load_over_cores: 4 # load above the core count that draws a warning (used when load_max is 0)
236
245
  load_max: 0 # load ceiling; 0 = core count + load_over_cores