@mmerterden/multi-agent-pipeline 20.41.0 → 20.43.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.
Files changed (114) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +8 -6
  3. package/README.tr.md +8 -6
  4. package/docs/architecture.md +3 -3
  5. package/docs/ecosystem.md +50 -13
  6. package/docs/facts.json +9 -9
  7. package/docs/features.md +9 -4
  8. package/install/claude.mjs +34 -1
  9. package/install/templates/claude-hooks.json +12 -1
  10. package/manifest.json +117 -90
  11. package/package.json +3 -2
  12. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  13. package/pipeline/commands/multi-agent/clean-disk/SKILL.md +134 -0
  14. package/pipeline/commands/multi-agent/review-priority/SKILL.md +143 -0
  15. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  16. package/pipeline/commands/multi-agent/sync/SKILL.md +4 -4
  17. package/pipeline/lib/args.mjs +131 -4
  18. package/pipeline/lib/bg-launch.mjs +5 -2
  19. package/pipeline/lib/credential-store.sh +11 -1
  20. package/pipeline/lib/hook-once.mjs +134 -0
  21. package/pipeline/lib/isotonic.mjs +73 -0
  22. package/pipeline/lib/low-disk.mjs +154 -0
  23. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  24. package/pipeline/lib/md2confluence-v3.py +8 -7
  25. package/pipeline/lib/model-dispatch.sh +26 -2
  26. package/pipeline/lib/normalize-text.mjs +135 -0
  27. package/pipeline/lib/outbound-gate.mjs +21 -3
  28. package/pipeline/lib/plan-todos.sh +17 -4
  29. package/pipeline/lib/redact.mjs +12 -3
  30. package/pipeline/lib/risky-settings.mjs +198 -0
  31. package/pipeline/lib/route-state.sh +1 -0
  32. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  33. package/pipeline/lib/session-usage.mjs +232 -0
  34. package/pipeline/lib/source-digest.mjs +211 -0
  35. package/pipeline/lib/tdd-evidence.mjs +250 -17
  36. package/pipeline/lib/untrusted-fence.mjs +132 -1
  37. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  38. package/pipeline/multi-agent-refs/cross-cli-contract.md +5 -5
  39. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  40. package/pipeline/multi-agent-refs/features/doctor.md +66 -4
  41. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  42. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  43. package/pipeline/multi-agent-refs/features/review-priority.md +123 -0
  44. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  45. package/pipeline/multi-agent-refs/features/usage-reporting.md +4 -2
  46. package/pipeline/multi-agent-refs/help/en.md +3 -1
  47. package/pipeline/multi-agent-refs/help/tr.md +3 -1
  48. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  49. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +1 -1
  50. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  51. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  52. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  53. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  54. package/pipeline/multi-agent-refs/review-priority/rules/example.md +137 -0
  55. package/pipeline/office/toolkit.json +1 -1
  56. package/pipeline/rules/outside-the-pipeline.md +1 -1
  57. package/pipeline/schemas/doctor-report.schema.json +47 -0
  58. package/pipeline/schemas/plan-todos.schema.json +29 -1
  59. package/pipeline/schemas/prefs.schema.json +81 -0
  60. package/pipeline/schemas/route-config.schema.json +51 -0
  61. package/pipeline/schemas/secret-patterns.json +17 -1
  62. package/pipeline/schemas/toolkit-path-params.json +15 -1
  63. package/pipeline/scripts/_cost-advise.mjs +357 -0
  64. package/pipeline/scripts/_cost-budget.mjs +78 -0
  65. package/pipeline/scripts/_cost.mjs +29 -0
  66. package/pipeline/scripts/_decode_text.py +107 -0
  67. package/pipeline/scripts/_guard-probe.mjs +406 -0
  68. package/pipeline/scripts/_guard_rules.py +206 -0
  69. package/pipeline/scripts/_memory-policy.mjs +1 -25
  70. package/pipeline/scripts/_retrieval.mjs +148 -2
  71. package/pipeline/scripts/_secret-scan.mjs +6 -1
  72. package/pipeline/scripts/_stack-routing.mjs +1 -0
  73. package/pipeline/scripts/_test-gaming.mjs +346 -0
  74. package/pipeline/scripts/agent-guard.py +8 -1
  75. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  76. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  77. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  78. package/pipeline/scripts/capture-resume.sh +9 -1
  79. package/pipeline/scripts/cost-analyze.mjs +66 -4
  80. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  81. package/pipeline/scripts/disk-cleaner.mjs +1432 -0
  82. package/pipeline/scripts/doctor.mjs +302 -47
  83. package/pipeline/scripts/evidence-gate.mjs +90 -0
  84. package/pipeline/scripts/gate-ledger.mjs +76 -21
  85. package/pipeline/scripts/gc-tmp.sh +5 -0
  86. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  87. package/pipeline/scripts/learnings-ledger.mjs +16 -12
  88. package/pipeline/scripts/note-agent-event.mjs +2 -0
  89. package/pipeline/scripts/note-mcp-failure.mjs +9 -2
  90. package/pipeline/scripts/note-skill-use.mjs +4 -1
  91. package/pipeline/scripts/pre-commit-check.sh +2 -2
  92. package/pipeline/scripts/pre-push-check.sh +8 -1
  93. package/pipeline/scripts/priority-review.mjs +912 -0
  94. package/pipeline/scripts/publish-staged.mjs +324 -0
  95. package/pipeline/scripts/route-learn.mjs +628 -0
  96. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  97. package/pipeline/scripts/scan-agent-config.sh +1 -1
  98. package/pipeline/scripts/statusline.mjs +309 -0
  99. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  100. package/pipeline/scripts/triage-memory.mjs +12 -4
  101. package/pipeline/scripts/uninstall.mjs +1 -0
  102. package/pipeline/skills/.skill-manifest.json +17 -5
  103. package/pipeline/skills/.skills-index.json +36 -3
  104. package/pipeline/skills/shared/README.md +9 -6
  105. package/pipeline/skills/shared/core/multi-agent-clean-disk/SKILL.md +34 -0
  106. package/pipeline/skills/shared/core/multi-agent-review-priority/SKILL.md +36 -0
  107. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +4 -4
  108. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  109. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +111 -0
  110. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  111. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1432 -0
  112. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  113. package/pipeline/skills/skill-copies.json +4 -0
  114. package/pipeline/skills/skills-index.md +5 -2
@@ -50,7 +50,7 @@
50
50
 
51
51
  import { readFileSync } from "node:fs";
52
52
  import { invokedDirectly } from "./invoked-directly.mjs";
53
- import { TABLE_LOADED, normalizeForMatch } from "./normalize-text.mjs";
53
+ import { TABLE_LOADED, decodedVariants, normalizeForMatch } from "./normalize-text.mjs";
54
54
  import { SECRET_PATTERNS } from "./secret-patterns.generated.mjs";
55
55
 
56
56
  /**
@@ -78,7 +78,7 @@ export const RULES = [
78
78
  {
79
79
  name: "email-address",
80
80
  certain: false,
81
- re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
81
+ re: /\b[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,63}\b/g,
82
82
  },
83
83
  // An absolute path under /Users or /home names the operator.
84
84
  { name: "home-directory-path", certain: false, re: /\/(?:Users|home)\/[A-Za-z0-9_.-]+\//g },
@@ -120,8 +120,15 @@ export const SURFACES = [
120
120
  const NEEDS_FOLD = /[^\t -~]/;
121
121
 
122
122
  /**
123
+ * The certain rules also run over the bounded decode of each line
124
+ * (normalize-text.mjs decodedVariants): a token wrapped in base64, hex or
125
+ * rot13 is a token all the same, and the receiving end can undo the wrapping.
126
+ * Such a finding carries `encoding`, the decode path that revealed it. The
127
+ * uncertain rules do not: an email address inside a decoded blob is not worth
128
+ * a report.
129
+ *
123
130
  * @param {string} text
124
- * @returns {{rule: string, certain: boolean, line: number}[]}
131
+ * @returns {{rule: string, certain: boolean, line: number, encoding?: string}[]}
125
132
  */
126
133
  export function scan(text) {
127
134
  // Without the fold table a disguised credential would pass as clean text,
@@ -135,6 +142,7 @@ export function scan(text) {
135
142
  // A credential written with an invisible character or a look-alike letter
136
143
  // still matches: the certain rules also run on the folded line.
137
144
  const folded = NEEDS_FOLD.test(lines[i]) ? normalizeForMatch(lines[i]) : lines[i];
145
+ let decoded = null;
138
146
  for (const rule of RULES) {
139
147
  // `lastIndex` survives between calls on a /g regex and would make every
140
148
  // second line skip its start. Reset per line.
@@ -146,6 +154,16 @@ export function scan(text) {
146
154
  }
147
155
  if (hit) {
148
156
  findings.push({ rule: rule.name, certain: rule.certain, line: i + 1 });
157
+ continue;
158
+ }
159
+ if (!rule.certain) continue;
160
+ decoded ??= decodedVariants(folded);
161
+ const via = decoded.find((v) => {
162
+ rule.re.lastIndex = 0;
163
+ return rule.re.test(v.text);
164
+ });
165
+ if (via) {
166
+ findings.push({ rule: rule.name, certain: true, line: i + 1, encoding: via.kind });
149
167
  }
150
168
  }
151
169
  }
@@ -22,8 +22,12 @@
22
22
  # prefs.global.tddEvidence.mode (off | warn | enforce, default warn)
23
23
  # tdd-red <task-id> <todo-id> <results> [--tests a,b] [--already-passing <reason>]
24
24
  # Record the RED run (a named test fails) from JUnit XML / xcresult / log
25
- # (under enforce, --tests needs results that name failing tests)
26
- # tdd-green <task-id> <todo-id> <results> Record the GREEN run (no failures, RED's tests among them)
25
+ # (under enforce, --tests needs results that name failing tests);
26
+ # keeps the work tree's new and changed test files (red.testFiles)
27
+ # tdd-green <task-id> <todo-id> <results> [--test-edit-reason <why>]
28
+ # Record the GREEN run (no failures, RED's tests among them);
29
+ # refuses when a test file RED kept was changed, unless the reason is given
30
+ # tdd-restore <task-id> <todo-id> Write the RED bytes of the kept test files back
27
31
  # fail <task-id> <todo-id> <reason> Mark failed
28
32
  # skip <task-id> <todo-id> <reason> Mark skipped (counts as satisfied for dependents)
29
33
  # next <task-id> Print the next ready todo (deps-respecting, ranked by what it unblocks); empty if none, blocked todos named on stderr
@@ -275,10 +279,10 @@ do_tdd_run() {
275
279
  local extra=()
276
280
  while [ $# -gt 0 ]; do
277
281
  case "$1" in
278
- --tests|--already-passing)
282
+ --tests|--already-passing|--test-edit-reason)
279
283
  [ $# -ge 2 ] || { echo "tdd-$kind: $1 needs a value" >&2; exit 64; }
280
284
  extra+=("$1" "$2"); shift 2 ;;
281
- *) echo "tdd-$kind: unsupported flag '$1' (only --tests and --already-passing)" >&2; exit 64 ;;
285
+ *) echo "tdd-$kind: unsupported flag '$1' (only --tests, --already-passing and --test-edit-reason)" >&2; exit 64 ;;
282
286
  esac
283
287
  done
284
288
  local state_path; state_path=$(resolve_state "$task_id")
@@ -289,6 +293,14 @@ do_tdd_run() {
289
293
  write_tdd "$state_path" "$todo_id" "$record"
290
294
  }
291
295
 
296
+ do_tdd_restore() {
297
+ local task_id="${1:-}"; local todo_id="${2:-}"
298
+ [ -z "$task_id" ] || [ -z "$todo_id" ] && { echo "usage: tdd-restore <task-id> <todo-id>" >&2; exit 64; }
299
+ local state_path; state_path=$(resolve_state "$task_id")
300
+ require_todo "$state_path" "$todo_id"
301
+ node "$TDD_EVIDENCE" restore --state "$state_path" --todo "$todo_id" || exit 2
302
+ }
303
+
292
304
  do_complete() {
293
305
  local task_id="${1:-}"; local todo_id="${2:-}"; local notes="" no_tests=""
294
306
  [ -z "$task_id" ] || [ -z "$todo_id" ] && { echo "usage: complete <task-id> <todo-id> [notes] [--no-tests <reason>]" >&2; exit 64; }
@@ -470,6 +482,7 @@ case "$CMD" in
470
482
  complete) do_complete "$@" ;;
471
483
  tdd-red) do_tdd_run red "$@" ;;
472
484
  tdd-green) do_tdd_run green "$@" ;;
485
+ tdd-restore) do_tdd_restore "$@" ;;
473
486
  fail) do_fail "$@" ;;
474
487
  skip) do_skip "$@" ;;
475
488
  next) do_next "$@" ;;
@@ -26,6 +26,11 @@ import { foldWithIndex, normalizeForMatch } from "./normalize-text.mjs";
26
26
 
27
27
  const CERTAIN = RULES.filter((r) => r.certain);
28
28
 
29
+ // Printable ASCII, tab and line breaks fold to themselves, so text made only
30
+ // of them skips the fold and its per-character index.
31
+ const NEEDS_FOLD = /[^\t\n\r -~]/;
32
+ const folds = (text) => NEEDS_FOLD.test(text);
33
+
29
34
  const globalCopy = (re) =>
30
35
  new RegExp(re.source, re.flags.includes("g") ? re.flags : `${re.flags}g`);
31
36
  const marker = (name) =>
@@ -60,7 +65,9 @@ function findSpans(text) {
60
65
  if (m[0]) spans.push([m.index, m.index + m[0].length, rule.name]);
61
66
  }
62
67
  }
63
- const { folded, start, end } = foldWithIndex(text);
68
+ const { folded, start, end } = folds(text)
69
+ ? foldWithIndex(text)
70
+ : { folded: text, start: [], end: [] };
64
71
  if (folded !== text) {
65
72
  for (const rule of CERTAIN) {
66
73
  for (const m of folded.matchAll(globalCopy(rule.re))) {
@@ -84,8 +91,10 @@ function findSpans(text) {
84
91
  }
85
92
 
86
93
  function stillMatches(text) {
87
- const folded = normalizeForMatch(text);
88
- return CERTAIN.find((r) => globalCopy(r.re).test(text) || globalCopy(r.re).test(folded));
94
+ const folded = folds(text) ? normalizeForMatch(text) : text;
95
+ return CERTAIN.find(
96
+ (r) => globalCopy(r.re).test(text) || (folded !== text && globalCopy(r.re).test(folded)),
97
+ );
89
98
  }
90
99
 
91
100
  /** @param {string} text */
@@ -0,0 +1,198 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * risky-settings.mjs - what in a Claude Code settings.json lets things run
4
+ * that nobody approved.
5
+ *
6
+ * The installer runs this on ~/.claude/settings.json before it merges its own
7
+ * hooks into it (install/claude.mjs configureSettings). It reports and never
8
+ * edits: removing a person's setting is their decision, which
9
+ * /multi-agent:setup asks about from the report the installer leaves at
10
+ * ~/.claude/multi-agent-risky-settings.json. A clean scan removes that report.
11
+ *
12
+ * HIGH bypass-with-broad-allow permission prompts off (bypassPermissions)
13
+ * together with a blanket Bash allow or every
14
+ * project MCP server enabled: any command
15
+ * and any server runs without a question
16
+ * hook-remote-exec a hook command that runs fetched or
17
+ * decoded code (curl or wget piped into a
18
+ * shell, /dev/tcp, base64 -d into a shell,
19
+ * nc -e)
20
+ * literal-secret a credential shape in env, in a hook
21
+ * command or in an MCP server entry
22
+ * MEDIUM bypass-mode bypassPermissions, or the dangerous-mode
23
+ * prompt skipped
24
+ * blanket-bash-allow Bash, Bash(*), Bash(:*) in the allow list
25
+ * all-project-mcp enableAllProjectMcpServers
26
+ * mcp-floating / mcp-mutable / mcp-insecure-transport
27
+ * an MCP launch whose code can change
28
+ * between two starts, or a plain-http
29
+ * server (lib/mcp-config-audit.mjs)
30
+ *
31
+ * A finding names the rule and where it is, never the value.
32
+ *
33
+ * CLI: risky-settings.mjs [--settings <path>] [--json]
34
+ * exit 0 no HIGH finding, 1 a HIGH finding, 2 the file is not JSON.
35
+ *
36
+ * @module pipeline/lib/risky-settings
37
+ */
38
+
39
+ import { readFileSync } from "node:fs";
40
+ import { homedir } from "node:os";
41
+ import { join } from "node:path";
42
+
43
+ import { parseArgs } from "./args.mjs";
44
+ import { invokedDirectly } from "./invoked-directly.mjs";
45
+ import { auditMcpConfig } from "./mcp-config-audit.mjs";
46
+ import { scan } from "./outbound-gate.mjs";
47
+ import { SECRET_PATTERNS } from "./secret-patterns.generated.mjs";
48
+
49
+ export const RISKY_REPORT = "multi-agent-risky-settings.json";
50
+
51
+ const BLANKET_BASH = new Set(["Bash", "Bash(*)", "Bash(:*)", "Bash(*:*)"]);
52
+ const REMOTE_EXEC =
53
+ /\b(?:curl|wget)\b[^|\n]{0,500}\|\s*(?:sudo\s+)?(?:ba|z|da|k)?sh\b|\/dev\/(?:tcp|udp)\/|\bbase64\s+(?:-d|--decode)\b[^|\n]{0,200}\|\s*(?:ba|z|da|k)?sh\b|\bnc\b[^|\n]{0,100}\s-e\s/;
54
+ const SECRET_MCP_KINDS = new Set([
55
+ "env-secret",
56
+ "header-secret",
57
+ "arg-secret",
58
+ "url-credentials",
59
+ "url-secret-param",
60
+ ]);
61
+
62
+ const finding = (level, rule, where, message) => ({ level, rule, where, message });
63
+
64
+ function hookCommands(settings) {
65
+ const out = [];
66
+ for (const [event, groups] of Object.entries(settings?.hooks ?? {})) {
67
+ if (!Array.isArray(groups)) continue;
68
+ groups.forEach((g, i) => {
69
+ for (const h of Array.isArray(g?.hooks) ? g.hooks : []) {
70
+ if (typeof h?.command === "string")
71
+ out.push({ where: `hooks.${event}[${i}]`, command: h.command });
72
+ }
73
+ });
74
+ }
75
+ return out;
76
+ }
77
+
78
+ const hasSecret = (text) => scan(String(text)).some((f) => f.certain);
79
+
80
+ /**
81
+ * Findings for one parsed settings document.
82
+ *
83
+ * @param {object} settings
84
+ * @returns {{level: "HIGH"|"MEDIUM", rule: string, where: string, message: string}[]}
85
+ */
86
+ export function scanRiskySettings(settings) {
87
+ if (!settings || typeof settings !== "object" || Array.isArray(settings)) return [];
88
+ const out = [];
89
+ const perms =
90
+ settings.permissions && typeof settings.permissions === "object" ? settings.permissions : {};
91
+ const bypass = perms.defaultMode === "bypassPermissions";
92
+ const allow = Array.isArray(perms.allow) ? perms.allow : [];
93
+ const blanket = allow.filter((a) => BLANKET_BASH.has(String(a).trim()));
94
+ const allMcp = settings.enableAllProjectMcpServers === true;
95
+
96
+ if (bypass && (blanket.length || allMcp)) {
97
+ out.push(
98
+ finding(
99
+ "HIGH",
100
+ "bypass-with-broad-allow",
101
+ "permissions.defaultMode",
102
+ `permission prompts are off and ${blanket.length ? "every Bash command is allowed" : "every project MCP server is enabled"}, so anything runs without a question`,
103
+ ),
104
+ );
105
+ }
106
+ if (bypass || settings.skipDangerousModePermissionPrompt === true) {
107
+ out.push(
108
+ finding(
109
+ "MEDIUM",
110
+ "bypass-mode",
111
+ bypass ? "permissions.defaultMode" : "skipDangerousModePermissionPrompt",
112
+ "permission prompts are switched off",
113
+ ),
114
+ );
115
+ }
116
+ if (blanket.length) {
117
+ out.push(
118
+ finding("MEDIUM", "blanket-bash-allow", "permissions.allow", "every Bash command is allowed"),
119
+ );
120
+ }
121
+ if (allMcp) {
122
+ out.push(
123
+ finding(
124
+ "MEDIUM",
125
+ "all-project-mcp",
126
+ "enableAllProjectMcpServers",
127
+ "every MCP server a project's .mcp.json names starts without approval",
128
+ ),
129
+ );
130
+ }
131
+ for (const { where, command } of hookCommands(settings)) {
132
+ if (REMOTE_EXEC.test(command)) {
133
+ out.push(finding("HIGH", "hook-remote-exec", where, "a hook runs fetched or decoded code"));
134
+ }
135
+ if (hasSecret(command)) {
136
+ out.push(finding("HIGH", "literal-secret", where, "a hook command carries a credential"));
137
+ }
138
+ }
139
+ for (const [key, value] of Object.entries(settings.env ?? {})) {
140
+ if (typeof value === "string" && hasSecret(`${key}=${value}`)) {
141
+ out.push(finding("HIGH", "literal-secret", `env.${key}`, "an env value is a credential"));
142
+ }
143
+ }
144
+ if (settings.mcpServers && typeof settings.mcpServers === "object") {
145
+ const audit = auditMcpConfig(
146
+ { mcpServers: settings.mcpServers },
147
+ { secretPatterns: SECRET_PATTERNS },
148
+ );
149
+ for (const s of audit.servers ?? []) {
150
+ const where = `mcpServers.${s.name}`;
151
+ if (s.verdict === "floating" || s.verdict === "mutable") {
152
+ out.push(finding("MEDIUM", `mcp-${s.verdict}`, where, s.reason));
153
+ }
154
+ for (const i of s.issues ?? []) {
155
+ if (SECRET_MCP_KINDS.has(i.kind)) {
156
+ out.push(finding("HIGH", "literal-secret", where, i.detail));
157
+ } else if (i.kind === "insecure-transport") {
158
+ out.push(finding("MEDIUM", "mcp-insecure-transport", where, i.detail));
159
+ }
160
+ }
161
+ }
162
+ }
163
+ return out;
164
+ }
165
+
166
+ /** The report the installer leaves for setup. */
167
+ export function riskyReport(findings, settingsPath) {
168
+ return {
169
+ settings: settingsPath,
170
+ at: new Date().toISOString(),
171
+ high: findings.filter((f) => f.level === "HIGH").length,
172
+ medium: findings.filter((f) => f.level === "MEDIUM").length,
173
+ findings,
174
+ };
175
+ }
176
+
177
+ if (invokedDirectly(import.meta.url)) {
178
+ const { flags } = parseArgs(process.argv.slice(2), { booleans: ["json"] });
179
+ const path =
180
+ typeof flags.settings === "string"
181
+ ? flags.settings
182
+ : join(homedir(), ".claude", "settings.json");
183
+ let settings;
184
+ try {
185
+ settings = JSON.parse(readFileSync(path, "utf8"));
186
+ } catch (err) {
187
+ process.stderr.write(`risky-settings: cannot read ${path}: ${err.message}\n`);
188
+ process.exit(2);
189
+ }
190
+ const report = riskyReport(scanRiskySettings(settings), path);
191
+ if (flags.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
192
+ else {
193
+ for (const f of report.findings) {
194
+ process.stdout.write(`[${f.level}] ${f.rule} (${f.where}): ${f.message}\n`);
195
+ }
196
+ }
197
+ process.exit(report.high ? 1 : 0);
198
+ }
@@ -130,6 +130,7 @@ case "$ACTION" in
130
130
  echo "free: $FREE$([ "$FREE" = "true" ] && echo " (data policy: $([ "$TRAIN" = "true" ] && echo any || echo no-training))")"
131
131
  echo "ceiling: $CEIL"
132
132
  echo "decisions: $REC"
133
+ echo "learned: $(jq -r '.global.modelRouting.learned.enabled // false' "$PREFS")"
133
134
  echo ""
134
135
 
135
136
  if [ "$ENABLED" != "true" ]; then
@@ -232,10 +232,14 @@ export const SECRET_PATTERNS = [
232
232
  id: "url-with-credentials",
233
233
  label: "URL with embedded credentials",
234
234
  kind: "context",
235
- re: /\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:[^\s/@]+@/g,
235
+ re: /\b[a-z][a-z0-9+.-]{0,31}:\/\/[^\s/:@]{1,255}:[^\s/@]+@/g,
236
236
  lead: null,
237
237
  blockEnd: null,
238
- samples: [["https://user:", "s", 12, "@example.com/x.git"]],
238
+ samples: [
239
+ ["https://user:", "s", 12, "@example.com/x.git"],
240
+ ["https://user:", "s", 300, "@example.com/x.git"],
241
+ ["https://user:", "s", 2000, "@example.com/x.git"],
242
+ ],
239
243
  },
240
244
  {
241
245
  id: "bearer-header",
@@ -21,18 +21,42 @@
21
21
  * from the end of each file; a file cut that way is reported `truncated`,
22
22
  * so an undercount is visible rather than silent.
23
23
  *
24
+ * Codex CLI keeps its own ledger: `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`
25
+ * (and `archived_sessions/`), where `event_msg` / `token_count` events carry a
26
+ * RUNNING total (`info.total_token_usage`) and `turn_context` names the model.
27
+ * `codexUsageSince` sums the deltas between consecutive totals; a total that
28
+ * goes down is a reset (compaction or a new thread) and starts a fresh base
29
+ * rather than producing a negative delta. Cached input is a subset of
30
+ * `input_tokens`, so fresh input is the difference; reasoning tokens are part
31
+ * of `output_tokens` and are not added twice. A forked rollout replays its
32
+ * parent's events, so an event counts once per (session, time, totals). A
33
+ * Codex home with rollouts but no event in that shape is reported as an
34
+ * unrecognized format, UNMEASURED rather than zero.
35
+ *
24
36
  * Prices come from cost-table.json through _cost.mjs. Cache writes are priced
25
37
  * by lifetime: `usage.cache_creation` splits them into 1h writes (2x input)
26
38
  * and 5m writes (1.25x input); a write the split does not cover prices at
27
39
  * 1.25x. The result is an estimate at list price and says so.
28
40
  *
41
+ * Run directly it prints one window's usage:
42
+ *
43
+ * session-usage.mjs [--host claude|codex] [--since <ISO> | --days N] [--json]
44
+ *
45
+ * `--host claude` (the default) reads `~/.claude/projects`; `--host codex`
46
+ * reads `$CODEX_HOME` or `~/.codex`. The window defaults to today. A host that
47
+ * cannot be read prints UNMEASURED and exits 0; a usage error exits 2.
48
+ *
29
49
  * @module pipeline/lib/session-usage
30
50
  */
31
51
 
32
52
  import { closeSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs";
53
+ import { homedir } from "node:os";
33
54
  import { basename, dirname, join } from "node:path";
34
55
 
35
56
  import { modelRateLookup, priceUsage } from "../scripts/_cost.mjs";
57
+ import { ArgsError, parseArgs, unknownSubcommand } from "./args.mjs";
58
+ import { exitOnHelp } from "./cli-help.mjs";
59
+ import { invokedDirectly } from "./invoked-directly.mjs";
36
60
 
37
61
  export const DEFAULT_MAX_BYTES = 64 * 1024 * 1024;
38
62
  const CHUNK = 1024 * 1024;
@@ -386,3 +410,211 @@ export function createUsageCache({ maxBytes = DEFAULT_MAX_BYTES } = {}) {
386
410
  },
387
411
  };
388
412
  }
413
+
414
+ const CODEX_FIELDS = ["input_tokens", "cached_input_tokens", "output_tokens"];
415
+
416
+ /** Every `rollout-*.jsonl` under a Codex home, active sessions before archived. */
417
+ function codexRollouts(home) {
418
+ const out = [];
419
+ const walk = (dir, depth) => {
420
+ for (const e of listDir(dir)) {
421
+ const p = join(dir, e.name);
422
+ if (e.isDirectory() && depth > 0) walk(p, depth - 1);
423
+ else if (e.isFile() && e.name.startsWith("rollout-") && e.name.endsWith(".jsonl"))
424
+ out.push(p);
425
+ }
426
+ };
427
+ for (const sub of ["sessions", "archived_sessions"]) {
428
+ const before = out.length;
429
+ walk(join(home, sub), 4);
430
+ const added = out.splice(before).sort();
431
+ out.push(...added);
432
+ }
433
+ return out;
434
+ }
435
+
436
+ /**
437
+ * Codex CLI usage of every token_count event stamped at or after `since`.
438
+ *
439
+ * @param {string} home the Codex home, `$CODEX_HOME` or `~/.codex`
440
+ * @param {{since?: number}} [opts]
441
+ */
442
+ export function codexUsageSince(home, { since = 0 } = {}) {
443
+ const models = emptyModels();
444
+ const result = (extra) => {
445
+ const priced = priceModels(models);
446
+ return {
447
+ host: "codex",
448
+ since: new Date(since).toISOString(),
449
+ models,
450
+ totals: sumModels(models),
451
+ usd: priced.usd,
452
+ unpricedModels: priced.unpricedModels,
453
+ estimated: true,
454
+ ...extra,
455
+ };
456
+ };
457
+ let files;
458
+ try {
459
+ statSync(home);
460
+ files = codexRollouts(home);
461
+ } catch {
462
+ return result({
463
+ measured: false,
464
+ format: "absent",
465
+ reason: `no Codex home at ${home}`,
466
+ files: 0,
467
+ malformed: 0,
468
+ resets: 0,
469
+ });
470
+ }
471
+ const seenFiles = new Set();
472
+ const seenEvents = new Set();
473
+ let read = 0;
474
+ let events = 0;
475
+ let malformed = 0;
476
+ let resets = 0;
477
+ for (const path of files) {
478
+ const id = basename(path);
479
+ if (seenFiles.has(id)) continue;
480
+ seenFiles.add(id);
481
+ let model = "";
482
+ let session = id;
483
+ let prev = null;
484
+ try {
485
+ eachLine(path, 0, (text) => {
486
+ if (
487
+ !text.includes('"token_count"') &&
488
+ !text.includes('"turn_context"') &&
489
+ !text.includes('"session_meta"')
490
+ )
491
+ return;
492
+ let line;
493
+ try {
494
+ line = JSON.parse(text);
495
+ } catch {
496
+ malformed += 1;
497
+ return;
498
+ }
499
+ const payload = line?.payload;
500
+ if (line?.type === "session_meta") {
501
+ if (typeof payload?.id === "string" && payload.id) session = payload.id;
502
+ return;
503
+ }
504
+ if (line?.type === "turn_context") {
505
+ if (typeof payload?.model === "string") model = payload.model;
506
+ return;
507
+ }
508
+ const total = payload?.type === "token_count" ? payload.info?.total_token_usage : null;
509
+ if (!total || typeof total !== "object") return;
510
+ events += 1;
511
+ const reset = prev !== null && CODEX_FIELDS.some((f) => tokens(total[f]) < tokens(prev[f]));
512
+ if (reset) resets += 1;
513
+ const delta = {};
514
+ for (const f of CODEX_FIELDS)
515
+ delta[f] = tokens(total[f]) - (prev && !reset ? tokens(prev[f]) : 0);
516
+ prev = total;
517
+ if (CODEX_FIELDS.every((f) => delta[f] === 0)) return;
518
+ const t = Date.parse(line.timestamp);
519
+ if (!Number.isFinite(t) || (since > 0 && t < since)) return;
520
+ const key = JSON.stringify([
521
+ session,
522
+ line.timestamp,
523
+ ...CODEX_FIELDS.map((f) => tokens(total[f])),
524
+ ]);
525
+ if (seenEvents.has(key)) return;
526
+ seenEvents.add(key);
527
+ const name = MODEL_ID.test(model) ? model : "unknown";
528
+ const m = (models[name] ??= emptyModel());
529
+ const cached = Math.min(delta.cached_input_tokens, delta.input_tokens);
530
+ m.input += delta.input_tokens - cached;
531
+ m.cacheRead += cached;
532
+ m.output += delta.output_tokens;
533
+ m.messages += 1;
534
+ });
535
+ read += 1;
536
+ } catch {
537
+ /* unreadable rollout: counted by its absence from `files` */
538
+ }
539
+ }
540
+ if (read > 0 && events === 0) {
541
+ return result({
542
+ measured: false,
543
+ format: "unrecognized",
544
+ reason: `${read} rollout(s) under ${home} carry no token_count event in the expected shape`,
545
+ files: read,
546
+ malformed,
547
+ resets,
548
+ });
549
+ }
550
+ if (read === 0) {
551
+ return result({
552
+ measured: false,
553
+ format: "absent",
554
+ reason: `no Codex rollouts under ${home}`,
555
+ files: 0,
556
+ malformed,
557
+ resets,
558
+ });
559
+ }
560
+ return result({ measured: true, format: "rollout", files: read, malformed, resets });
561
+ }
562
+
563
+ const HOSTS = ["claude", "codex"];
564
+
565
+ function cli(argv, env) {
566
+ const { flags } = parseArgs(argv, {
567
+ unknown: "error",
568
+ booleans: ["json"],
569
+ strings: ["host", "since", "days"],
570
+ positionals: false,
571
+ });
572
+ const host = flags.host ?? "claude";
573
+ if (!HOSTS.includes(host)) throw unknownSubcommand(host, HOSTS);
574
+ let since = startOfLocalDay();
575
+ if (flags.since !== undefined) {
576
+ since = Date.parse(flags.since);
577
+ if (!Number.isFinite(since))
578
+ throw new ArgsError(`--since takes an ISO date`, { kind: "unexpected", token: flags.since });
579
+ } else if (flags.days !== undefined) {
580
+ const days = Number(flags.days);
581
+ if (!(days > 0))
582
+ throw new ArgsError(`--days takes a positive number`, {
583
+ kind: "unexpected",
584
+ token: flags.days,
585
+ });
586
+ since = Date.now() - days * 86_400_000;
587
+ }
588
+ const home = env.HOME || homedir();
589
+ const out =
590
+ host === "codex"
591
+ ? codexUsageSince(env.CODEX_HOME || join(home, ".codex"), { since })
592
+ : {
593
+ host: "claude",
594
+ measured: true,
595
+ ...usageSince(join(home, ".claude", "projects"), { since }),
596
+ };
597
+ if (host === "claude" && out.files === 0) {
598
+ out.measured = false;
599
+ out.reason = `no transcripts under ${join(home, ".claude", "projects")}`;
600
+ }
601
+ if (flags.json) return `${JSON.stringify(out, null, 2)}\n`;
602
+ if (!out.measured) return `UNMEASURED: ${out.reason}\n`;
603
+ const t = out.totals;
604
+ return (
605
+ `${host} since ${out.since}: in ${t.input} + cached ${t.cacheRead} + written ${t.cacheCreation}, out ${t.output}, ${t.messages} turns, ~$${out.usd.toFixed(2)} (estimate)` +
606
+ (out.unpricedModels.length ? `\n unpriced: ${out.unpricedModels.join(", ")}` : "") +
607
+ "\n"
608
+ );
609
+ }
610
+
611
+ if (invokedDirectly(import.meta.url)) {
612
+ exitOnHelp(import.meta.url);
613
+ try {
614
+ process.stdout.write(cli(process.argv.slice(2), process.env));
615
+ } catch (e) {
616
+ if (!(e instanceof ArgsError)) throw e;
617
+ process.stderr.write(`session-usage: ${e.message}\n`);
618
+ process.exitCode = 2;
619
+ }
620
+ }