@skathio/somi 5.1.1 → 5.3.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 (58) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.copilot-extension/extension.json +5 -1
  4. package/.copilot-extension/marketplace.json +1 -1
  5. package/README.md +20 -8
  6. package/VERSION +1 -1
  7. package/agents/somi-reviewer.md +3 -1
  8. package/agents/somi-security-reviewer.md +3 -1
  9. package/commands/somi-brief.md +11 -0
  10. package/commands/somi-deliver.md +3 -1
  11. package/commands/somi.md +2 -2
  12. package/hooks/pre-tool/apply-tier.mjs +12 -6
  13. package/library/roles/brief.md +33 -0
  14. package/package.json +1 -2
  15. package/rules/digest.md +6 -0
  16. package/scripts/lib/advisor.mjs +47 -14
  17. package/scripts/lib/brief-own.mjs +13 -0
  18. package/scripts/lib/brief-parse.mjs +94 -0
  19. package/scripts/lib/brief-route.mjs +49 -0
  20. package/scripts/lib/brief.mjs +69 -0
  21. package/scripts/lib/chat-commands.mjs +65 -0
  22. package/scripts/lib/check.mjs +3 -2
  23. package/scripts/lib/git-tree.mjs +37 -8
  24. package/scripts/lib/ledger.mjs +9 -0
  25. package/scripts/lib/policy.mjs +20 -1
  26. package/scripts/lib/pr.mjs +2 -2
  27. package/scripts/lib/prompt.mjs +17 -4
  28. package/scripts/lib/quality/clones.mjs +113 -26
  29. package/scripts/lib/quality/coupling.mjs +115 -0
  30. package/scripts/lib/quality/exports.mjs +33 -0
  31. package/scripts/lib/quality/findings.mjs +18 -0
  32. package/scripts/lib/quality/functions.mjs +71 -0
  33. package/scripts/lib/quality/gate.mjs +134 -144
  34. package/scripts/lib/quality/imports.mjs +88 -0
  35. package/scripts/lib/quality/js-source.mjs +55 -0
  36. package/scripts/lib/quality/limits.mjs +102 -23
  37. package/scripts/lib/quality/metrics.mjs +65 -16
  38. package/scripts/lib/quality/parse.mjs +16 -11
  39. package/scripts/lib/quality/path-aliases.mjs +36 -0
  40. package/scripts/lib/quality/python-exports.mjs +31 -0
  41. package/scripts/lib/quality/python-findings.mjs +82 -0
  42. package/scripts/lib/quality/python-imports.mjs +64 -0
  43. package/scripts/lib/quality/python.mjs +50 -0
  44. package/scripts/lib/quality/repo.mjs +31 -12
  45. package/scripts/lib/quality/run.mjs +2 -2
  46. package/scripts/lib/quality/slop.mjs +168 -0
  47. package/scripts/lib/quality/suppressions.mjs +38 -0
  48. package/scripts/lib/quality/totals.mjs +39 -0
  49. package/scripts/lib/reviews.mjs +20 -9
  50. package/scripts/lib/routes.mjs +2 -1
  51. package/scripts/lib/views.mjs +8 -3
  52. package/scripts/lib/workflows.mjs +24 -1
  53. package/scripts/somi-mcp.mjs +26 -3
  54. package/scripts/somi.mjs +21 -7
  55. package/scripts/vendor/tree-sitter/LICENSE.tree-sitter-python +21 -0
  56. package/scripts/vendor/tree-sitter/manifest.json +11 -1
  57. package/scripts/vendor/tree-sitter/tree-sitter-python.wasm +0 -0
  58. package/workflows/deliver-stages.js +420 -48
@@ -0,0 +1,50 @@
1
+ // quality/python.mjs: what the gate looks for in Python beyond the shape of a function. Leftover debugging and a swallowed error are
2
+ // read from one file's tree (python-findings.mjs). An unused export needs the rest of the repository: a public name the change added is
3
+ // unused when no other file imports it (python-exports.mjs, python-imports.mjs).
4
+
5
+ import { filesAt } from '../git-tree.mjs';
6
+ import { report } from './findings.mjs';
7
+ import { languageOf, parseSource } from './parse.mjs';
8
+ import { exportsOf } from './python-exports.mjs';
9
+ import { pythonFindings } from './python-findings.mjs';
10
+ import { importsOf, isImported, wordOf } from './python-imports.mjs';
11
+
12
+ export { exportsOf, importsOf, isImported, pythonFindings };
13
+
14
+ const inAdded = (added, line) => added.some(([a, b]) => line >= a && line <= b);
15
+ // A package's __init__.py is its public face and __main__.py its entry point, so their names are meant for callers the gate cannot see.
16
+ const NOT_A_MODULE = /(^|\/)(__init__|__main__|conftest|setup)\.py$/;
17
+
18
+ /**
19
+ * Python's own checks on what a change added to one file, for the gate. Findings go to ctx.violations or ctx.warnings. An export is
20
+ * only remembered in ctx.pyExports: whether anything imports it is decided by scoreUnusedExports, once every file has been read.
21
+ */
22
+ export function scorePython(ctx, { file, tree, added, test }) {
23
+ for (const f of pythonFindings(tree, { test, reexports: /(^|\/)__init__\.py$/.test(file) }).filter((x) => inAdded(added, x.line))) {
24
+ report(ctx, { rule: f.rule, file, line: f.line, name: f.name, value: 1, limit: 0 });
25
+ }
26
+ if (test || NOT_A_MODULE.test(file)) return;
27
+ const text = ctx.after.get(file) ?? '';
28
+ const usedHere = (name) => text.split(wordOf(name)).length > 2;
29
+ ctx.pyExports.push(...exportsOf(tree).filter((x) => inAdded(added, x.line) && (x.declared || !usedHere(x.name))).map((x) => ({ ...x, file })));
30
+ }
31
+
32
+ async function importsIn(file, text) {
33
+ const parsed = await parseSource(file, text);
34
+ try { return parsed?.tree ? importsOf(parsed.tree, file) : []; } finally { parsed?.tree?.delete(); }
35
+ }
36
+
37
+ /**
38
+ * A public name the change added that no other file imports, reported as a warning: in an application it is dead code, but in a
39
+ * library it can be the interface, and the gate cannot tell the two apart. Only files that mention one of the names are parsed.
40
+ */
41
+ export async function scoreUnusedExports(ctx, { skipped, maxFiles }) {
42
+ if (ctx.pyExports.length === 0) return;
43
+ const mentioned = (text) => ctx.pyExports.some((x) => text.includes(x.name));
44
+ const files = [...new Set([...ctx.repoFiles, ...ctx.after.keys()])].filter((f) => languageOf(f) === 'python' && !skipped.test(f)).slice(0, maxFiles);
45
+ const others = [];
46
+ for (const [file, text] of filesAt(ctx.root, ctx.to, files)) {
47
+ if (mentioned(text)) others.push({ file, text, imports: await importsIn(file, text) });
48
+ }
49
+ for (const x of ctx.pyExports.filter((e) => !isImported(e.file, e.name, others))) report(ctx, { rule: 'unused-export', file: x.file, line: x.line, name: x.name, value: 1, limit: 0 });
50
+ }
@@ -4,22 +4,25 @@
4
4
 
5
5
  import { fileAt, listFiles } from '../git-tree.mjs';
6
6
  import { findClones, tokensOf } from './clones.mjs';
7
- import { JS_FAMILY, METRICS, exemption, isTest, scoreComments, scoreCss, skipped, total, withTree } from './gate.mjs';
8
- import { topLevelCognitive, unitsOf } from './metrics.mjs';
7
+ import { report } from './findings.mjs';
8
+ import { METRICS, TOO_DEEP, familyOf, exemption, isTest, scoreComments, scoreCss, skipped, total, withTree } from './gate.mjs';
9
+ import { codeLines, topLevelCognitive, unitsOf } from './metrics.mjs';
9
10
  import { languageOf } from './parse.mjs';
11
+ import { pythonFindings } from './python.mjs';
10
12
 
11
13
  const TOP = 20;
14
+ const NEAR = 0.8;
12
15
 
13
16
  // The change scopes' comment and stylesheet checks, run on every line, since the whole file is what is being measured.
14
17
  const EVERY_LINE = [[1, Number.MAX_SAFE_INTEGER]];
15
18
 
16
19
  function unitFindings(ctx, { file, lines, unit }) {
17
20
  ctx.scored.functions += 1;
18
- ctx.functions.push({ file, line: unit.start, name: unit.name, cognitive: unit.cognitive });
21
+ ctx.functions.push({ file, line: unit.start, name: unit.name, kind: unit.kind, cognitive: unit.cognitive });
19
22
  for (const metric of METRICS.filter((m) => unit[m] > ctx.limits[unit.kind][m])) {
20
23
  const allowed = exemption(ctx, lines, unit, metric);
21
24
  if (allowed) ctx.exemptions.push({ rule: metric, file, line: unit.start, name: unit.name, ...allowed });
22
- else ctx.violations.push({ rule: metric, file, line: unit.start, name: unit.name, kind: unit.kind, value: unit[metric], limit: ctx.limits[unit.kind][metric] });
25
+ else report(ctx, { rule: metric, file, line: unit.start, name: unit.name, kind: unit.kind, value: unit[metric], limit: ctx.limits[unit.kind][metric] });
23
26
  }
24
27
  }
25
28
 
@@ -29,9 +32,13 @@ function codeFindings(ctx, { file, lines, parsed }) {
29
32
  const units = unitsOf(parsed.tree, { file, isTest: test });
30
33
  const readable = (u) => !parsed.errors.some(([a, b]) => a <= u.end && b >= u.start);
31
34
  for (const unit of units.filter(readable)) unitFindings(ctx, { file, lines, unit });
32
- const sum = total(units, topLevelCognitive(parsed.tree));
33
- if (parsed.errors.length === 0 && sum > ctx.limits.file.cognitive) ctx.violations.push({ rule: 'file-cognitive', file, line: 1, value: sum, limit: ctx.limits.file.cognitive });
34
- if (JS_FAMILY.has(parsed.language) && !test) ctx.cloneFiles.push({ file, tokens: tokensOf(parsed.tree), size: ctx.limits.clones.tokens });
35
+ const sums = { cognitive: total(units, topLevelCognitive(parsed.tree)), lines: codeLines(parsed.tree), functions: units.length };
36
+ for (const measure of parsed.errors.length === 0 ? Object.keys(sums) : []) {
37
+ if (sums[measure] > ctx.limits.file[measure]) report(ctx, { rule: `file-${measure}`, file, line: 1, value: sums[measure], limit: ctx.limits.file[measure] });
38
+ }
39
+ if (parsed.language === 'python') for (const f of pythonFindings(parsed.tree, { test }).filter((x) => x.level === 'violation')) report(ctx, { rule: f.rule, file, line: f.line, name: f.name, value: 1, limit: 0 });
40
+ const family = familyOf(parsed.language);
41
+ if (family && !test) ctx.cloneFiles.push({ file, family, tokens: tokensOf(parsed.tree), size: ctx.limits.clones.tokens });
35
42
  }
36
43
 
37
44
  function scoreParsed(ctx, { file, text, parsed }) {
@@ -43,6 +50,14 @@ function scoreParsed(ctx, { file, text, parsed }) {
43
50
  else codeFindings(ctx, { file, lines: text.split('\n'), parsed });
44
51
  }
45
52
 
53
+ // Code nested deeper than the measuring walks can follow is unanalyzed rather than ending the report.
54
+ function measured(ctx, file, run) {
55
+ try { run(); } catch (e) {
56
+ if (!(e instanceof RangeError)) throw e;
57
+ ctx.unanalyzed.push({ file, reason: TOO_DEEP });
58
+ }
59
+ }
60
+
46
61
  function summary(ctx) {
47
62
  const byRule = {};
48
63
  const byFile = {};
@@ -53,17 +68,21 @@ function summary(ctx) {
53
68
  return {
54
69
  by_rule: byRule,
55
70
  most_complex: ctx.functions.sort((a, b) => b.cognitive - a.cognitive).slice(0, TOP),
71
+ // Functions just under the complexity limit. Code shaped to pass a number bunches here, so a reviewer may want to look.
72
+ near_limit: ctx.functions.filter((f) => f.kind === 'function' && f.cognitive >= Math.ceil(ctx.limits.function.cognitive * NEAR) && f.cognitive <= ctx.limits.function.cognitive).length,
56
73
  most_findings: Object.entries(byFile).sort((a, b) => b[1] - a[1]).slice(0, TOP).map(([file, findings]) => ({ file, findings })),
57
74
  };
58
75
  }
59
76
 
60
- /** The codebase at `rev`, measured against `limits`: { ok, violations, exemptions, unanalyzed, scored, summary }. */
77
+ /** The codebase at `rev`, measured against `limits`: { ok, violations, warnings, exemptions, unanalyzed, scored, summary }. */
61
78
  export async function repoQuality(root, { rev, limits, now = new Date().toISOString() }) {
62
- const ctx = { limits, now, mode: 'project', violations: [], exemptions: [], unanalyzed: [], functions: [], cloneFiles: [], scored: { files: 0, functions: 0 } };
79
+ const ctx = { limits, now, mode: 'project', violations: [], warnings: [], exemptions: [], unanalyzed: [], functions: [], cloneFiles: [], scored: { files: 0, functions: 0 } };
63
80
  for (const file of listFiles(root, rev).filter((f) => languageOf(f))) {
64
81
  const text = fileAt(root, rev, file);
65
- if (text !== null && !skipped(file, text)) await withTree(file, text, (parsed) => scoreParsed(ctx, { file, text, parsed }));
82
+ if (text !== null && !skipped(file, text)) await withTree(file, text, (parsed) => measured(ctx, file, () => scoreParsed(ctx, { file, text, parsed })));
83
+ }
84
+ for (const family of new Set(ctx.cloneFiles.map((f) => f.family))) {
85
+ for (const c of findClones({ after: ctx.cloneFiles.filter((f) => f.family === family) })) ctx.violations.push({ rule: 'clone', file: c.file, line: c.line, value: c.lines, limit: 0, other: c.other, similarity: c.similarity });
66
86
  }
67
- for (const c of findClones({ after: ctx.cloneFiles })) ctx.violations.push({ rule: 'clone', file: c.file, line: c.line, value: c.lines, limit: 0, other: c.other });
68
- return { ok: ctx.violations.length === 0, violations: ctx.violations, exemptions: ctx.exemptions, unanalyzed: ctx.unanalyzed, scored: ctx.scored, summary: summary(ctx) };
87
+ return { ok: ctx.violations.length === 0, violations: ctx.violations, warnings: ctx.warnings, exemptions: ctx.exemptions, unanalyzed: ctx.unanalyzed, scored: ctx.scored, summary: summary(ctx) };
69
88
  }
@@ -50,9 +50,9 @@ export function describeAll(violations, scope) {
50
50
  return lines.length > MAX_SHOWN ? [...lines.slice(0, MAX_SHOWN), `and ${lines.length - MAX_SHOWN} more: somi_quality with scope ${scope} lists them`] : lines;
51
51
  }
52
52
 
53
- /** { ok, failures: [line], warnings: n } for one scope, where each failure names the rule, the place and the numbers, or { error }. */
53
+ /** { ok, failures: [line], warnings: n, level } for one scope, where each failure names the rule, the place and the numbers, or { error }. */
54
54
  export function qualityStep(root, { scope, env = process.env }) {
55
55
  const result = runQuality(root, { scope, env });
56
56
  if (result.error) return { ok: false, failures: [result.error], warnings: 0, error: result.error };
57
- return { ok: result.ok, failures: describeAll(result.violations, scope), warnings: result.warnings.length };
57
+ return { ok: result.ok, failures: describeAll(result.violations, scope), warnings: result.warnings.length, level: result.level ?? 'strict' };
58
58
  }
@@ -0,0 +1,168 @@
1
+ // quality/slop.mjs: habits of hastily written code, looked for in what a change added. Each is cheap to see in the parse tree and each
2
+ // has an honest use now and then, so most are advice, while debugger, focused-test and unsafe-cast fail:
3
+ // - empty-catch: a catch that does nothing and does not say why. A comment inside is the why.
4
+ // - log-only-catch: a catch that only logs, so the failure carries on as if it had not happened.
5
+ // - rethrow-catch: a catch that throws the same error unchanged, which only adds nesting.
6
+ // - focused-test and skipped-test: .only, fit, .skip and xit left in a test file. A focused test silently stops the rest of the suite.
7
+ // - test-without-assertion: a test whose body asserts nothing, so it passes whatever the code does.
8
+ // - console and debugger: debugging output and breakpoints left in product code.
9
+ // - unused-binding: a local, or a trailing parameter, that nothing reads.
10
+ // - pass-through: a function that only calls another with the same arguments, which adds a name and no behaviour.
11
+ // - unsafe-cast: in TypeScript product code, a cast that switches the type checker off: as any, as never, <any>, or a double cast
12
+ // through unknown or any. An independent review of benchmark changes blocked on these. It fails: well-kept projects hold many, but
13
+ // their recent commits added one in 2 of 126 (1.6%), so a change rarely needs one. Test code is not checked.
14
+
15
+ import { report, inAdded, overlaps } from './findings.mjs';
16
+
17
+ const field = (node, name) => node.childForFieldName(name);
18
+ const lineOf = (node) => node.startPosition.row + 1;
19
+ const FUNCTIONS = new Set(['function_declaration', 'function_expression', 'function', 'arrow_function', 'method_definition', 'generator_function_declaration', 'generator_function']);
20
+ const CONSOLE = /^console\.(log|debug|trace|dir|table)$/;
21
+ const LOGGER = /^(console|logger|log|this\.logger|this\.log)\.\w+$/;
22
+ const FOCUSED = /^(describe|it|test|context|suite|specify)\.only$|^(fit|fdescribe|ftest)$/;
23
+ const SKIPPED = /^(describe|it|test|context|suite|specify)\.skip$|^(xit|xdescribe|xtest|xcontext)$/;
24
+ const TEST = /^(it|test|specify)(\.(only|concurrent|sequential|serial))?$/;
25
+ const ASSERTION = /\b(expect|assert|should)\b|(^|\.)(expect|assert|should|verify|ensure|check)\w*$|^(t|st|tt)\.[\w.]+$|\.(to\w*|throws|rejects|resolves|matchSnapshot)$/i;
26
+
27
+ // Every node of a type under `node`.
28
+ function nodes(node, types, out = []) {
29
+ if (types.has(node.type)) out.push(node);
30
+ for (const c of node.namedChildren) nodes(c, types, out);
31
+ return out;
32
+ }
33
+
34
+ // The nodes of some types that start on a line the change added.
35
+ const addedNodes = (tree, types, added) => nodes(tree.rootNode, new Set(types)).filter((n) => inAdded(added, lineOf(n)));
36
+ const flag = (ctx, file, node, rule) => report(ctx, { rule, file, line: lineOf(node), value: 1, limit: 0 });
37
+
38
+ const statements = (block) => (block ? block.namedChildren.filter((c) => c.type !== 'comment') : []);
39
+ const calleeText = (call) => field(call, 'function')?.text.replace(/\s+/g, '') ?? '';
40
+
41
+ function catchRule(clause) {
42
+ const body = field(clause, 'body') ?? clause.namedChildren.find((c) => c.type === 'block');
43
+ const inside = statements(body);
44
+ if (inside.length === 0) return body?.namedChildren.length ? null : 'empty-catch';
45
+ if (inside.length !== 1) return null;
46
+ const [only] = inside;
47
+ const call = only.type === 'expression_statement' ? only.namedChildren[0] : null;
48
+ if (call?.type === 'call_expression' && LOGGER.test(calleeText(call))) return 'log-only-catch';
49
+ const declaration = clause.namedChildren.find((c) => c.type === 'catch_declaration');
50
+ const param = field(clause, 'parameter') ?? (declaration && field(declaration, 'name'));
51
+ const thrown = only.type === 'throw_statement' ? only.namedChildren.filter((c) => c.type !== 'comment') : null;
52
+ return thrown && (thrown.length === 0 || (param && thrown[0].text === param.text)) ? 'rethrow-catch' : null;
53
+ }
54
+
55
+ function scoreCatches(ctx, { file, tree, added }) {
56
+ for (const clause of addedNodes(tree, ['catch_clause'], added)) {
57
+ const rule = catchRule(clause);
58
+ if (rule) flag(ctx, file, clause, rule);
59
+ }
60
+ }
61
+
62
+ // A test is a call of it or test with a function as its body. Assertions in a helper it calls are not seen, which is why this is advice.
63
+ function scoreTests(ctx, { file, tree, added }) {
64
+ for (const call of addedNodes(tree, ['call_expression'], added)) {
65
+ const callee = calleeText(call);
66
+ if (FOCUSED.test(callee)) flag(ctx, file, call, 'focused-test');
67
+ if (SKIPPED.test(callee)) flag(ctx, file, call, 'skipped-test');
68
+ const body = TEST.test(callee) ? field(call, 'arguments')?.namedChildren.find((a) => FUNCTIONS.has(a.type)) : null;
69
+ if (body && !nodes(body, new Set(['call_expression'])).some((c) => ASSERTION.test(calleeText(c)))) flag(ctx, file, call, 'test-without-assertion');
70
+ }
71
+ }
72
+
73
+ function scoreDebugging(ctx, { file, tree, added }) {
74
+ for (const node of addedNodes(tree, ['call_expression', 'debugger_statement'], added)) {
75
+ if (node.type === 'debugger_statement') flag(ctx, file, node, 'debugger');
76
+ else if (CONSOLE.test(calleeText(node))) flag(ctx, file, node, 'console');
77
+ }
78
+ }
79
+
80
+ const ESCAPES = new Set(['any', 'never']);
81
+ const CASTS = new Set(['as_expression', 'type_assertion']);
82
+ const unwrap = (node) => (node?.type === 'parenthesized_expression' ? unwrap(node.namedChildren[0]) : node);
83
+ const castType = (node) => node.namedChildren.find((c) => c.type !== 'comment' && (node.type === 'type_assertion' ? c.type === 'type_arguments' : c !== node.namedChildren[0]));
84
+ const castTarget = (node) => castType(node)?.text.replace(/[<>()\s]/g, '');
85
+ const castInner = (node) => unwrap(node.namedChildren.find((c) => c !== castType(node) && c.type !== 'comment'));
86
+ const enclosingCast = (node) => { let p = node.parent; while (p?.type === 'parenthesized_expression') p = p.parent; return CASTS.has(p?.type); };
87
+ // A cast the checker cannot check: to any or never, or to anything at all by way of unknown or any, with or without parentheses and in
88
+ // either syntax. Only the outermost cast of a chain is flagged, so x as unknown as T is one finding.
89
+ function unsafeCast(node) {
90
+ if (enclosingCast(node)) return false;
91
+ const chain = [];
92
+ for (let n = node; CASTS.has(n?.type); n = castInner(n)) chain.push(castTarget(n));
93
+ return chain.some((t) => ESCAPES.has(t)) || (chain.length > 1 && chain.slice(1).some((t) => t === 'unknown'));
94
+ }
95
+
96
+ function scoreCasts(ctx, { file, tree, added }) {
97
+ for (const node of addedNodes(tree, ['as_expression', 'type_assertion'], added)) if (unsafeCast(node)) flag(ctx, file, node, 'unsafe-cast');
98
+ }
99
+
100
+ // The simple names a function takes, in order: a, b = 1, and TypeScript's a: T. A destructured parameter is null.
101
+ function paramNames(fn) {
102
+ const params = field(fn, 'parameters')?.namedChildren.filter((c) => c.type !== 'comment') ?? (field(fn, 'parameter') ? [field(fn, 'parameter')] : []);
103
+ return params.map((p) => {
104
+ const name = p.type === 'identifier' ? p : field(p, 'pattern') ?? field(p, 'left');
105
+ return name?.type === 'identifier' ? name : null;
106
+ });
107
+ }
108
+
109
+ // How often each name is read inside a function, nested functions included, counting every identifier with its text.
110
+ function reads(fn) {
111
+ const counts = new Map();
112
+ for (const id of nodes(fn, new Set(['identifier', 'shorthand_property_identifier']))) counts.set(id.text, (counts.get(id.text) ?? 0) + 1);
113
+ return counts;
114
+ }
115
+
116
+ // The locals a function declares itself, not those of a function nested in it.
117
+ function locals(fn) {
118
+ const out = [];
119
+ const visit = (n) => {
120
+ if (n !== fn && FUNCTIONS.has(n.type)) return;
121
+ if (n.type === 'variable_declarator' && field(n, 'name')?.type === 'identifier') out.push(field(n, 'name'));
122
+ for (const c of n.namedChildren) visit(c);
123
+ };
124
+ visit(fn);
125
+ return out;
126
+ }
127
+
128
+ function scoreBindings(ctx, { file, fn, added }) {
129
+ const counts = reads(fn);
130
+ const unread = (id) => id && !id.text.startsWith('_') && (counts.get(id.text) ?? 0) <= 1 && inAdded(added, lineOf(id));
131
+ const params = paramNames(fn);
132
+ // A parameter before one that is read holds its place, so only those after the last read one are unused.
133
+ const lastRead = params.findLastIndex((p) => p === null || !unread(p));
134
+ const unused = counts.has('arguments') || !field(fn, 'body') ? [] : params.slice(lastRead + 1);
135
+ for (const id of [...unused, ...locals(fn).filter(unread)]) report(ctx, { rule: 'unused-binding', file, line: lineOf(id), name: id.text, value: 0, limit: 1 });
136
+ }
137
+
138
+ // A named function whose whole body is a call of another with its own parameters, in order.
139
+ function passThrough(fn) {
140
+ if (!['function_declaration', 'arrow_function', 'function_expression'].includes(fn.type)) return false;
141
+ if (fn.type !== 'function_declaration' && fn.parent?.type !== 'variable_declarator') return false;
142
+ const body = field(fn, 'body');
143
+ const only = body?.type === 'statement_block' ? statements(body) : [body];
144
+ const returned = only.length === 1 && only[0]?.type === 'return_statement' ? only[0].namedChildren[0] : only[0];
145
+ const call = returned?.type === 'await_expression' ? returned.namedChildren[0] : returned;
146
+ if (call?.type !== 'call_expression' || calleeText(call) === 'super') return false;
147
+ const args = field(call, 'arguments')?.namedChildren.filter((c) => c.type !== 'comment') ?? [];
148
+ const params = paramNames(fn);
149
+ return params.length > 0 && params.every(Boolean) && args.length === params.length && args.every((a, i) => a.type === 'identifier' && a.text === params[i].text);
150
+ }
151
+
152
+ function scoreFunctions(ctx, { file, tree, added }) {
153
+ for (const fn of nodes(tree.rootNode, FUNCTIONS)) {
154
+ if (!overlaps(added, lineOf(fn), fn.endPosition.row + 1)) continue;
155
+ scoreBindings(ctx, { file, fn, added });
156
+ if (inAdded(added, lineOf(fn)) && passThrough(fn)) flag(ctx, file, fn, 'pass-through');
157
+ }
158
+ }
159
+
160
+ /** Every habit above in what a change added to one file. C# is checked for its catches only. */
161
+ export function scoreSlop(ctx, { file, tree, added, language, test }) {
162
+ scoreCatches(ctx, { file, tree, added });
163
+ if (language === 'c-sharp') return;
164
+ if (test) return scoreTests(ctx, { file, tree, added });
165
+ scoreDebugging(ctx, { file, tree, added });
166
+ scoreFunctions(ctx, { file, tree, added });
167
+ if (language === 'typescript' || language === 'tsx') scoreCasts(ctx, { file, tree, added });
168
+ }
@@ -0,0 +1,38 @@
1
+ // quality/suppressions.mjs: newly added comments that switch a check off. A suppression without a reason is a shortcut, and in a
2
+ // benchmark so is every suppression and every exemption the agent wrote itself.
3
+
4
+ import { inAdded } from './findings.mjs';
5
+
6
+ const SUPPRESSION = /eslint-disable|@ts-ignore|@ts-expect-error|@ts-nocheck|NOSONAR|#\s*noqa|\/\/\s*nolint|@SuppressWarnings|#\s*type:\s*ignore|#\s*pylint:\s*(disable|skip-file)|#\s*(flake8|ruff):\s*noqa|#\s*mypy:\s*ignore-errors|istanbul ignore|c8 ignore|stylelint-disable/;
7
+ // A suppression that says why, the way ESLint's -- description or text after @ts-expect-error does, is a decision rather than a
8
+ // shortcut. Outside a benchmark it passes.
9
+ // In Python the reason is the rule it names: a bare # noqa or # type: ignore hides everything on the line, a coded one hides one thing.
10
+ // A file-wide switch (flake8: noqa, ruff: noqa, pylint: skip-file, mypy: ignore-errors) and pylint's disable=all hide everything, so
11
+ // they are never reasoned.
12
+ const REASONED = /eslint-disable[^\n]*\s--\s+\S.{8,}|@ts-(expect-error|ignore)\s*:?\s+\S.{8,}|stylelint-disable[^\n]*\s--\s+\S.{8,}|#\s*noqa:\s*[A-Z]+\d+|#\s*type:\s*ignore\[[\w, -]+\]|#\s*pylint:\s*disable=(?![^#]*\ball\b)[\w-]+(\s*,\s*[\w-]+)*/;
13
+ const FILE_WIDE = /#\s*(flake8|ruff):\s*noqa|#\s*pylint:\s*skip-file|#\s*mypy:\s*ignore-errors/;
14
+ // A directive opens its comment: // eslint-disable-next-line, /* @ts-nocheck */. A comment that only mentions one is prose.
15
+ const DIRECTIVE = /^(\/\/|\/\*+|#)\s*(eslint-disable|@ts-ignore|@ts-expect-error|@ts-nocheck|NOSONAR|nolint|noqa|type:\s*ignore|pylint:\s*(disable|skip-file)|(flake8|ruff):\s*noqa|mypy:\s*ignore-errors|stylelint-disable|istanbul ignore|c8 ignore|somi-gate-allow)/;
16
+ // flake8 reads # noqa anywhere in a comment, as in `x = 1 # why # noqa`, and pylint its pragma. A type checker reads # type: ignore
17
+ // only at the start of one, so prose that mentions it later, as black's own comments do, is not a directive.
18
+ const LATER = /^#.*#\s*(noqa|pylint:\s*disable)/;
19
+ const isDirective = (text) => DIRECTIVE.test(text) || LATER.test(text);
20
+
21
+ function scoreComment(ctx, file, line, text) {
22
+ if (SUPPRESSION.test(text) && (ctx.mode === 'benchmark' || FILE_WIDE.test(text) || !REASONED.test(text))) ctx.violations.push({ rule: 'suppression', file, line, value: 1, limit: ctx.limits.suppressions.added });
23
+ if (ctx.mode === 'benchmark' && /somi-gate-allow/.test(text)) ctx.violations.push({ rule: 'exemption', file, line, value: 1, limit: 0 });
24
+ }
25
+
26
+ /** Comments the change added. Only comments count, so a string that mentions eslint-disable is not one. */
27
+ export function scoreComments(ctx, file, tree, added) {
28
+ const visit = (n) => {
29
+ if (n.type === 'comment') { if (inAdded(added, n.startPosition.row + 1) && isDirective(n.text)) scoreComment(ctx, file, n.startPosition.row + 1, n.text); return; }
30
+ for (const c of n.children) visit(c);
31
+ };
32
+ visit(tree.rootNode);
33
+ }
34
+
35
+ /** With no tree to read comments from, every added line is checked instead. */
36
+ export function scoreLines(ctx, file, lines, added) {
37
+ for (const [i, line] of lines.entries()) if (inAdded(added, i + 1)) scoreComment(ctx, file, i + 1, line);
38
+ }
@@ -0,0 +1,39 @@
1
+ // quality/totals.mjs: a touched file's totals. A change may not take a file over a limit, nor add more than the per-change limit at
2
+ // once, however its functions are cut up. What it moved in from another file it touched is not added, so splitting a file into modules
3
+ // is not refused for its size.
4
+
5
+ import { report } from './findings.mjs';
6
+
7
+ // Each total, the limit a change may not take the file over, and the limit on how much one change may add.
8
+ const MEASURES = [
9
+ { measure: 'cognitive', over: 'file-cognitive', limit: 'cognitive', added: 'file-added-cognitive', addedLimit: 'added_cognitive' },
10
+ { measure: 'lines', over: 'file-lines', limit: 'lines', added: 'file-added-lines', addedLimit: 'added_lines' },
11
+ { measure: 'functions', over: 'file-functions', limit: 'functions' },
12
+ ];
13
+
14
+ // A function's text, trimmed line by line, so the same function moved elsewhere, or indented differently, has the same key.
15
+ export const keyOf = (lines, u) => lines.slice(u.start - 1, u.end).map((l) => l.trim()).join('\n');
16
+ const countOf = (keys) => keys.reduce((m, k) => m.set(k, (m.get(k) ?? 0) + 1), new Map());
17
+
18
+ // A test file grows with the code it tests, so only its complexity is held to the file limits.
19
+ function scoreFile(ctx, { file, now, was, moved }) {
20
+ const limits = ctx.limits.file;
21
+ for (const m of ctx.isTest(file) ? MEASURES.slice(0, 1) : MEASURES) {
22
+ if (now[m.measure] > limits[m.limit] && was[m.measure] <= limits[m.limit]) report(ctx, { rule: m.over, file, line: 1, value: now[m.measure], limit: limits[m.limit], before: was[m.measure] });
23
+ const added = now[m.measure] - was[m.measure] - moved[m.measure];
24
+ if (m.added && added > limits[m.addedLimit]) report(ctx, { rule: m.added, file, line: 1, value: added, limit: limits[m.addedLimit], ...(moved[m.measure] > 0 ? { moved: moved[m.measure] } : {}) });
25
+ }
26
+ }
27
+
28
+ // A function is moved, not added, when its file did not have it, the files the change touched did, and it occurs no more often after
29
+ // the change than before. A copy occurs more often, and a function changed on the way has a new key, so both still count in full.
30
+ export function scoreTotals(ctx) {
31
+ const before = countOf(ctx.moves.before);
32
+ const after = countOf(ctx.moves.after);
33
+ const isMoved = (key) => (before.get(key) ?? 0) >= after.get(key);
34
+ for (const { units, own, ...totals } of ctx.totals) {
35
+ const credited = units.filter((u) => !own.has(u.key) && isMoved(u.key));
36
+ const moved = { cognitive: credited.reduce((s, u) => s + u.cognitive, 0), lines: credited.reduce((s, u) => s + u.lines, 0), functions: credited.length };
37
+ scoreFile(ctx, { ...totals, moved });
38
+ }
39
+ }
@@ -6,23 +6,28 @@
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { readDiff, resolveRef, reviewDiffCommand, snapshotTree, workBase } from './git-tree.mjs';
9
- import { ReviewInputError, decideAfterReview, isBlocking, parseReviews } from './policy.mjs';
9
+ import { ReviewInputError, decideAfterReview, isBlocking, markRequested, parseReviews } from './policy.mjs';
10
+ import { saveRequest, userWords } from './prompt.mjs';
10
11
  import { computeSignals, RECORDED_ONLY, SECURITY_SIGNALS } from './signals.mjs';
11
12
  import { StateError, appendStateFile, statePaths } from './state.mjs';
12
13
  import { resolveSpawn } from './tiers.mjs';
14
+ import { ASKED_SECURITY_REVIEW, securityReviewTier } from './workflows.mjs';
13
15
 
14
16
  const REVIEWER = 'somi-reviewer';
15
17
  const SECURITY_REVIEWER = 'somi-security-reviewer';
16
18
  const OBJECT_ID = /^[0-9a-f]{40,64}$/;
17
19
  const REVIEWER_PROMPT = 'Fresh, read-only review. Run the diff command, read what you need, return only the JSON your instructions define.';
18
- // Judging a diff is judgement work, so the code reviewer runs on medium and the security reviewer on high.
19
20
  const TIERS = Object.freeze({ [REVIEWER]: 'medium', [SECURITY_REVIEWER]: 'high' });
20
21
  const bare = (agent) => String(agent ?? '').split(':').pop();
21
22
 
22
- // Who reviews is review policy, so only the user's own config chooses the model, and a committed project config has no say.
23
- const seat = (ctx, agent, diff) => {
24
- const { tier, model } = resolveSpawn(ctx.configLayers?.[0] ?? {}, ctx.host, TIERS[agent]);
25
- return { agent: `somi:${agent}`, tier, ...(model ? { model } : {}), brief: `${REVIEWER_PROMPT}\n\nThe diff command:\n${diff}` };
23
+ // Who reviews is review policy, so only the user's own config chooses the model, and a committed project config can only raise the
24
+ // security reviewer's tier. Judging a diff is judgement work: the code reviewer runs on medium, the security reviewer on high unless
25
+ // the user chose medium for it, and on high whenever the user asks for a security review.
26
+ const seat = (ctx, agent, { diff, asked, request }) => {
27
+ const wanted = agent === SECURITY_REVIEWER ? securityReviewTier({ global: ctx.configLayers?.[0], project: ctx.configLayers?.[1] }, { asked }) : TIERS[agent];
28
+ const { tier, model } = resolveSpawn(ctx.configLayers?.[0] ?? {}, ctx.host, wanted);
29
+ const marked = agent === SECURITY_REVIEWER && asked ? `${ASKED_SECURITY_REVIEW}\n\n` : '';
30
+ return { agent: `somi:${agent}`, tier, ...(model ? { model } : {}), brief: `${marked}${REVIEWER_PROMPT}\n\nThe diff command:\n${diff}${request ? `\n\nWhat the user asked for, word for word: ${request}` : ''}` };
26
31
  };
27
32
 
28
33
  const triggers = (signals) => [...signals.review.filter((s) => !RECORDED_ONLY.includes(s)), ...signals.security];
@@ -62,7 +67,8 @@ export function reviewPlan(ctx, { base, always = false, security = false } = {})
62
67
  const covered = agents.length > 0 && !always && !security && coveringReview(ctx, tree, agents);
63
68
  if (covered && (covered.findings ?? []).filter(isBlocking).length === 0) return { needed: false, covered: true, reviewers: [], required: agents, base: from, tree, signals: fired };
64
69
  const diff = reviewDiffCommand(from, tree);
65
- return { needed: agents.length > 0, reviewers: agents.map((a) => seat(ctx, a, diff)), required: agents, base: from, tree, signals: fired, diff };
70
+ const request = agents.length > 0 ? saveRequest(ctx.root, ctx.env) : null;
71
+ return { needed: agents.length > 0, reviewers: agents.map((a) => seat(ctx, a, { diff, asked: security, request })), required: agents, base: from, tree, signals: fired, diff };
66
72
  }
67
73
 
68
74
  // Hosts hand reviewers the absolute path of the working copy, and a report is not worth paying for twice over that.
@@ -79,6 +85,7 @@ const ADVICE = Object.freeze({
79
85
  fix: 'These findings block this change from leaving. Fix them where the change was made: if a worker built it, start the same worker with its brief and these findings below it, and otherwise fix them here. Then call somi_review with no reviews, run the reviewers it names, and record what they return. If a finding has needs_verification, check it first: a reviewer asking to remove a check is not enough reason to remove it.',
80
86
  fixHere: 'These findings block this change from leaving, and security signals fired on its diff. Fix them here, on this conversation\'s model, and not on a low worker, even if one built the change. Then call somi_review with no reviews, run the reviewers it names, and record what they return. If a finding has needs_verification, check it first: a reviewer asking to remove a check is not enough reason to remove it.',
81
87
  ask: 'Tell the user: blocking findings remain after repeated review passes. Show them, and let the user choose between more fixing and stopping. SoMi will not write clean pull request text until a review clears them.',
88
+ decide: 'These findings are behaviour the user\'s own words ask for, so they do not block the change and they are the user\'s call. Show each one to the user briefly with the words it quotes, and do not change that behaviour unless the user asks.',
82
89
  close: 'Nothing here blocks the change. Pass the logged findings on to the user briefly, and do not act on them unless the user asks.',
83
90
  });
84
91
 
@@ -88,7 +95,9 @@ export function recordReviews(ctx, { reviews, base, tree: reviewed, always = fal
88
95
  const list = normalized(ctx, reviews);
89
96
  const named = list.map((r) => r?.agent).filter((a) => Object.hasOwn(TIERS, a));
90
97
  const dispatched = [...new Set([...plan.required, ...named])].map((agent) => ({ agent }));
91
- const { findings, verdicts } = parseReviews(list, dispatched);
98
+ const parsed = parseReviews(list, dispatched);
99
+ const findings = markRequested(parsed.findings, userWords(ctx.root, ctx.env));
100
+ const { verdicts } = parsed;
92
101
  const earlier = readReviews(ctx.root, ctx.env).filter((r) => r.base === plan.base);
93
102
  const pass = earlier.length + 1;
94
103
  const previousBlocking = earlier.at(-1)?.blocking ?? [];
@@ -97,7 +106,8 @@ export function recordReviews(ctx, { reviews, base, tree: reviewed, always = fal
97
106
  const securityFired = plan.signals.some((s) => SECURITY_SIGNALS.includes(s));
98
107
  const record = { v: 1, at: ctx.now(), base: plan.base, tree, pass, verdicts, findings, blocking: blocking.map((f) => f.fingerprint) };
99
108
  appendStateFile(ctx.root, statePaths(ctx.root, ctx.env).reviews, `${JSON.stringify(record)}\n`, ctx.env);
100
- const logged = findings.filter((f) => !isBlocking(f));
109
+ const decisions = findings.filter((f) => f.requested);
110
+ const logged = findings.filter((f) => !isBlocking(f) && !f.requested);
101
111
  const trimmed = verdicts.filter((v) => v.trimmed).map((v) => ({ agent: v.agent, dropped: v.trimmed }));
102
112
  return {
103
113
  verdict: decision.next === 'close' ? 'clear' : decision.next === 'fix' ? 'fix' : 'ask-user',
@@ -106,6 +116,7 @@ export function recordReviews(ctx, { reviews, base, tree: reviewed, always = fal
106
116
  logged,
107
117
  advice: decision.next === 'fix' && securityFired ? ADVICE.fixHere : ADVICE[decision.next],
108
118
  ...(decision.stop ? { stop: decision.stop } : {}),
119
+ ...(decisions.length ? { decisions, decisions_advice: ADVICE.decide } : {}),
109
120
  ...(trimmed.length ? { trimmed, trimmed_note: 'These reports were over the size cap, so their least severe findings were dropped to fit. Tell the user how many.' } : {}),
110
121
  };
111
122
  }
@@ -54,7 +54,8 @@ const TICKET_KEY = /^\s*[A-Z][A-Z0-9]+-\d+\s*$/;
54
54
  const ANSWER = /\?\s*$|^\s*(what|why|how|where|when|who|which|does|do|is|are|can|explain|show me|list)\b/i;
55
55
  const TICKET_TYPES = Object.freeze({ bug: 'debug', defect: 'debug', incident: 'incident', epic: 'plan', spike: 'design', story: 'build', task: 'build', feature: 'build', improvement: 'build' });
56
56
 
57
- export const ROUTE_NAMES = Object.freeze([...new Set([...FIRST, ...KINDS].map(([r]) => r)), 'answer', 'build']);
57
+ // brief is reached only by /somi-brief's hint: preparing work is something the user asks for, never a reading of their words.
58
+ export const ROUTE_NAMES = Object.freeze([...new Set([...FIRST, ...KINDS].map(([r]) => r)), 'answer', 'build', 'brief']);
58
59
 
59
60
  // What the coordinator reads when it has to choose. Short, because it is read on the session's model.
60
61
  export const LONG_REQUEST = 600;
@@ -5,7 +5,7 @@ import { isBlocking } from './policy.mjs';
5
5
 
6
6
  const plain = (s) => String(s ?? '').replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ').trim();
7
7
  const place = (f) => (f.line ? `${plain(f.file)}:${f.line}` : plain(f.file));
8
- const finding = (f) => `- ${plain(f.severity)} ${place(f)}: ${plain(f.claim)}`;
8
+ const finding = (f) => `- ${plain(f.severity)} ${place(f)}: ${plain(f.claim)}${f.requested ? ` (the user's decision: they asked "${plain(f.objects_to_requested)}")` : ''}`;
9
9
 
10
10
  function loggedFindings(reviews, migrated = []) {
11
11
  const seen = new Set();
@@ -17,12 +17,15 @@ function loggedFindings(reviews, migrated = []) {
17
17
  return [...logged, ...migrated];
18
18
  }
19
19
 
20
- export function renderStatus({ plan, ledger, reviews = [], check, migrated }) {
20
+ const briefLine = (brief) => (brief.invalid ? `Brief: does not read: ${plain(brief.invalid)}` : `Brief: ${plain(brief.title)} (${brief.requirements} requirements, hand off to ${brief.handoff})`);
21
+
22
+ export function renderStatus({ plan, brief, ledger, reviews = [], check, migrated }) {
21
23
  const lines = [];
22
24
  if (plan) {
23
25
  lines.push(`Plan: ${plan.done} of ${plan.total} milestones done`);
24
26
  if (plan.next) lines.push(`Next: ${plain(plan.next)}`);
25
27
  } else lines.push('No plan open.');
28
+ if (brief) lines.push(briefLine(brief));
26
29
  const last = reviews.at(-1);
27
30
  if (last) lines.push('', `Last review: ${(last.verdicts ?? []).map((v) => `${plain(v.agent)}: ${plain(v.verdict)}`).join(', ')}`);
28
31
  const blocking = (last?.findings ?? []).filter(isBlocking);
@@ -40,7 +43,7 @@ const NOT_REVIEWED = (gate) => (gate.reason === 'open-blocking'
40
43
 
41
44
  // Only what a PR reader can use. The commits and the review speak for the work, and local ids stay out, because they do not resolve for
42
45
  // anyone who clones the repository.
43
- export function renderPr({ subjects = [], gate, ledger, reviews = [], check, tree, migrated }) {
46
+ export function renderPr({ subjects = [], gate, level = 'strict', ledger, reviews = [], check, tree, migrated }) {
44
47
  const lines = [];
45
48
  if (!gate.ok) lines.push(NOT_REVIEWED(gate), '');
46
49
  lines.push('## Summary', '');
@@ -58,5 +61,7 @@ export function renderPr({ subjects = [], gate, ledger, reviews = [], check, tre
58
61
  if (said.length > 0) lines.push('', '## Decisions', '', ...said);
59
62
  const full = check?.full && check.tree === tree;
60
63
  lines.push('', '## Checks', '', full ? `Full suite: ${check.ok ? 'passed' : 'failed'}.` : 'Full suite: not recorded for this code.');
64
+ // A reader judges the code by the bar it met, so a gate looser than the default says which one.
65
+ if (level !== 'strict') lines.push(`Quality gate: passed at the ${level} level, looser than the default strict one.`);
61
66
  return `${lines.join('\n')}\n`;
62
67
  }
@@ -2,6 +2,7 @@
2
2
  // what a host lists.
3
3
  // kind code work that changes code, which ends in a look at the diff to see whether a review is due.
4
4
  // kind plan a plan the user approves, then milestones with fresh context.
5
+ // kind brief the user and the agent settle the work into a brief, in the conversation, and no code changes.
5
6
  // kind report a worker or reviewer produces an answer, and no code changes.
6
7
  // kind command one SoMi command, and its output relayed.
7
8
  // kind direct answered from what is on disk, with no agent.
@@ -23,6 +24,7 @@ export const WORKFLOWS = Object.freeze({
23
24
  incident: { kind: 'code', role: 'incident', tier: 'medium', skills: [] },
24
25
  accessibility: { kind: 'code', role: 'accessibility', tier: 'medium', skills: ['accessibility'] },
25
26
  plan: { kind: 'plan', role: 'plan', tier: 'medium', skills: [] },
27
+ brief: { kind: 'brief', role: 'brief', tier: 'medium', skills: ['testing-checklist', 'threat-modeling'] },
26
28
  design: { kind: 'report', role: 'design', tier: 'high', skills: ['threat-modeling'] },
27
29
  discover: { kind: 'report', role: 'discover', tier: 'medium', skills: [] },
28
30
  atlas: { kind: 'report', role: 'atlas', tier: 'medium', skills: [] },
@@ -41,10 +43,31 @@ const WORKERS = Object.freeze({ 'somi-worker-low': 'low', 'somi-worker-medium':
41
43
  const REVIEWERS = Object.freeze({ 'somi-reviewer': 'medium', 'somi-security-reviewer': 'high' });
42
44
  const plainName = (name) => String(name ?? '').split(':').pop();
43
45
  export const tierForWorker = (name) => (Object.hasOwn(WORKERS, plainName(name)) ? WORKERS[plainName(name)] : null);
44
- export const tierForReviewer = (name) => (Object.hasOwn(REVIEWERS, plainName(name)) ? REVIEWERS[plainName(name)] : null);
46
+ export const tierForReviewer = (name, layers = {}, opts = {}) => {
47
+ const agent = plainName(name);
48
+ if (!Object.hasOwn(REVIEWERS, agent)) return null;
49
+ return agent === 'somi-security-reviewer' ? securityReviewTier(layers, opts) : REVIEWERS[agent];
50
+ };
51
+
52
+ // The security reviewer runs on high. The user's own config may set review.security_tier to medium, to spend less on each review while
53
+ // the high tier stays for work that climbs to it. A project's config is cloned input, so it may set high but never lower it, and a user
54
+ // who asks for a security review always gets high.
55
+ // A security review the user asked for says so in its brief, and the tier hook keeps it on high only then. It only ever raises a tier,
56
+ // so it is a marker for cost, not a trust boundary: a session that copies it pays for high and loosens nothing.
57
+ export const ASKED_SECURITY_REVIEW = 'The user asked for this security review.';
58
+ export const SECURITY_REVIEW_TIERS = Object.freeze(['medium', 'high']);
59
+ export function securityReviewTier({ global, project } = {}, { asked = false } = {}) {
60
+ if (asked || project?.review?.security_tier === 'high') return 'high';
61
+ const chosen = global?.review?.security_tier;
62
+ return SECURITY_REVIEW_TIERS.includes(chosen) ? chosen : 'high';
63
+ }
45
64
 
46
65
  const LIBRARY = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'library');
47
66
  export const libraryPath = (kind, name) => path.join(LIBRARY, kind, `${name}.md`);
67
+ // SoMi's rules reach the conversation through a session-start hook, which an agent SoMi starts does not get. In the staged workflow on
68
+ // two security tasks, the builder never saw the security floor and missed the trap the main session caught, so a brief names the file.
69
+ export const RULES_FILE = path.join(LIBRARY, '..', 'rules', 'digest.md');
70
+ export const rulesLine = (file = RULES_FILE) => `SoMi's rules, which hold for this work, are in ${file}. Read that file before anything else.`;
48
71
  export const roleBrief = (role) => fs.readFileSync(libraryPath('roles', role), 'utf8').trim();
49
72
 
50
73
  export function expertiseIndex() {