@skathio/somi 4.0.0 → 4.1.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 (163) hide show
  1. package/.claude/settings.json +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.copilot-extension/extension.json +1 -1
  5. package/.copilot-extension/marketplace.json +1 -1
  6. package/README.md +11 -5
  7. package/VERSION +1 -1
  8. package/agents/somi-coder.md +4 -228
  9. package/agents/somi-designer.md +4 -160
  10. package/agents/somi-discovery-analyst.md +4 -276
  11. package/agents/somi-flow.md +47 -0
  12. package/agents/somi-general.md +36 -0
  13. package/agents/somi-planner.md +4 -341
  14. package/agents/somi-reviewer.md +4 -199
  15. package/agents/somi.md +81 -253
  16. package/commands/adopt.md +6 -84
  17. package/commands/architecture-review.md +11 -86
  18. package/commands/atlas.md +10 -25
  19. package/commands/code-loop.md +10 -221
  20. package/commands/code-parallel.md +10 -151
  21. package/commands/code.md +9 -157
  22. package/commands/debug.md +9 -131
  23. package/commands/design.md +9 -160
  24. package/commands/discover.md +9 -194
  25. package/commands/impact.md +9 -25
  26. package/commands/incident.md +9 -39
  27. package/commands/plan-loop.md +9 -181
  28. package/commands/plan.md +9 -244
  29. package/commands/pr.md +10 -25
  30. package/commands/refactor-design.md +11 -89
  31. package/commands/refactor.md +11 -50
  32. package/commands/release-readiness.md +11 -70
  33. package/commands/review-panel.md +10 -141
  34. package/commands/review.md +11 -181
  35. package/commands/security-review.md +11 -75
  36. package/commands/ship-loop.md +9 -260
  37. package/commands/ship.md +9 -115
  38. package/commands/somi-config.md +12 -124
  39. package/commands/test-strategy.md +11 -75
  40. package/commands/upgrade.md +9 -72
  41. package/hooks/hooks.json +1 -1
  42. package/hooks/lib/common.mjs +15 -13
  43. package/hooks/pre-tool/block-dangerous-bash.mjs +1 -1
  44. package/hooks/pre-tool/block-secret-writes.mjs +5 -7
  45. package/hooks/pre-tool/guard-cost-lowering.mjs +26 -11
  46. package/hooks/pre-tool/guard-protected-paths.mjs +54 -34
  47. package/hooks/session-start/ensure-default-config.mjs +34 -42
  48. package/package.json +1 -1
  49. package/scripts/lib/config-files.mjs +145 -0
  50. package/scripts/lib/cost-ceiling.mjs +29 -22
  51. package/scripts/lib/cost-defaults.mjs +2 -0
  52. package/scripts/lib/escalation-facts.mjs +146 -0
  53. package/scripts/lib/escalation.mjs +129 -0
  54. package/scripts/lib/findings-ledger.mjs +241 -0
  55. package/scripts/lib/install-text.mjs +97 -0
  56. package/scripts/lib/loop-caps.mjs +140 -0
  57. package/scripts/lib/loop-diff.mjs +12 -70
  58. package/scripts/lib/loop-engine.mjs +226 -0
  59. package/scripts/lib/loop-escalate.mjs +49 -0
  60. package/scripts/lib/loop-exit.mjs +47 -0
  61. package/scripts/lib/loop-notes-compact.mjs +72 -0
  62. package/scripts/lib/loop-notes.mjs +278 -0
  63. package/scripts/lib/loop-review.mjs +355 -12
  64. package/scripts/lib/loop-state.mjs +44 -0
  65. package/scripts/lib/loop-step-close.mjs +75 -0
  66. package/scripts/lib/loop-step-kit.mjs +179 -0
  67. package/scripts/lib/loop-step-review.mjs +140 -0
  68. package/scripts/lib/loop-step-tool.mjs +89 -0
  69. package/scripts/lib/loop-step.mjs +301 -0
  70. package/scripts/lib/mcp-project-root.mjs +18 -7
  71. package/scripts/lib/path-facts.mjs +187 -0
  72. package/scripts/lib/path-safety.mjs +171 -0
  73. package/scripts/lib/run-card.mjs +73 -0
  74. package/scripts/size-budget-overrides.json +5 -13
  75. package/scripts/somi-card.mjs +39 -0
  76. package/scripts/somi-check.mjs +4 -3
  77. package/scripts/somi-config.mjs +113 -50
  78. package/scripts/somi-findings.mjs +56 -271
  79. package/scripts/somi-loop.mjs +77 -446
  80. package/scripts/somi-mcp.mjs +27 -96
  81. package/scripts/validate.sh +92 -54
  82. package/skills/flow-adopt/SKILL.md +92 -0
  83. package/skills/flow-architecture-review/SKILL.md +94 -0
  84. package/skills/flow-atlas/SKILL.md +34 -0
  85. package/skills/flow-code/SKILL.md +167 -0
  86. package/skills/flow-code-loop/SKILL.md +263 -0
  87. package/skills/flow-code-parallel/SKILL.md +160 -0
  88. package/skills/flow-debug/SKILL.md +141 -0
  89. package/skills/flow-design/SKILL.md +170 -0
  90. package/skills/flow-discover/SKILL.md +204 -0
  91. package/skills/flow-impact/SKILL.md +35 -0
  92. package/skills/flow-incident/SKILL.md +49 -0
  93. package/skills/flow-plan/SKILL.md +254 -0
  94. package/skills/flow-plan-loop/SKILL.md +254 -0
  95. package/skills/flow-pr/SKILL.md +34 -0
  96. package/skills/flow-refactor/SKILL.md +58 -0
  97. package/skills/flow-refactor-design/SKILL.md +97 -0
  98. package/skills/flow-release-readiness/SKILL.md +82 -0
  99. package/skills/flow-review/SKILL.md +193 -0
  100. package/skills/flow-review-panel/SKILL.md +154 -0
  101. package/skills/flow-security-review/SKILL.md +83 -0
  102. package/skills/flow-ship/SKILL.md +125 -0
  103. package/skills/flow-ship-loop/SKILL.md +274 -0
  104. package/skills/flow-somi-config/SKILL.md +142 -0
  105. package/skills/flow-status/SKILL.md +43 -0
  106. package/skills/flow-test-strategy/SKILL.md +83 -0
  107. package/skills/flow-upgrade/SKILL.md +82 -0
  108. package/skills/role-coder/SKILL.md +247 -0
  109. package/skills/role-designer/SKILL.md +172 -0
  110. package/skills/role-discovery-analyst/SKILL.md +288 -0
  111. package/skills/role-planner/SKILL.md +353 -0
  112. package/skills/role-reviewer/SKILL.md +218 -0
  113. package/skills/somi-checkpoint/SKILL.md +95 -0
  114. package/skills/somi-dispatch/SKILL.md +14 -14
  115. package/skills/somi-routing/SKILL.md +6 -2
  116. package/tests/hooks/cases/block-secret-writes.json +6 -1
  117. package/tests/hooks/cases/guard-protected-paths.json +44 -2
  118. package/tests/hooks/run.sh +21 -0
  119. package/tests/scripts/checkpoint-gate.sh +2 -2
  120. package/tests/scripts/cost-defaults.sh +2 -0
  121. package/tests/scripts/cost-hardcap.sh +26 -17
  122. package/tests/scripts/dispatch-line-gate.sh +4 -4
  123. package/tests/scripts/dispatch-reference-gate.sh +14 -14
  124. package/tests/scripts/ensure-default-config.sh +4 -4
  125. package/tests/scripts/escalation.sh +409 -0
  126. package/tests/scripts/eval-runner.sh +8 -7
  127. package/tests/scripts/fact-sheet.sh +296 -0
  128. package/tests/scripts/global-config.sh +167 -0
  129. package/tests/scripts/goldens/somi-loop.json +2 -2
  130. package/tests/scripts/lib/dispatch-reference-gate.mjs +14 -5
  131. package/tests/scripts/lib/escalation-facts-tests.mjs +140 -0
  132. package/tests/scripts/lib/escalation-tests.mjs +154 -0
  133. package/tests/scripts/lib/findings-ledger-tests.mjs +118 -0
  134. package/tests/scripts/lib/loop-engine-tests.mjs +287 -0
  135. package/tests/scripts/lib/loop-escalate-tests.mjs +356 -0
  136. package/tests/scripts/lib/loop-flow-gate.mjs +173 -0
  137. package/tests/scripts/lib/loop-notes-tests.mjs +371 -0
  138. package/tests/scripts/lib/loop-step-cli-tests.mjs +141 -0
  139. package/tests/scripts/lib/loop-step-close-tests.mjs +351 -0
  140. package/tests/scripts/lib/loop-step-lenient-tests.mjs +114 -0
  141. package/tests/scripts/lib/loop-step-state-tests.mjs +127 -0
  142. package/tests/scripts/lib/loop-step-tests.mjs +499 -0
  143. package/tests/scripts/lib/loop-step-unwritten-tests.mjs +55 -0
  144. package/tests/scripts/lib/path-facts-tests.mjs +198 -0
  145. package/tests/scripts/lib/path-safety-tests.mjs +201 -0
  146. package/tests/scripts/lib/run-suites.mjs +139 -0
  147. package/tests/scripts/lib/site-roadmap-gate.mjs +64 -0
  148. package/tests/scripts/lib/sizing-score-tests.mjs +210 -0
  149. package/tests/scripts/lib/sizing-set-tests.mjs +131 -0
  150. package/tests/scripts/lib/somi-mcp-loop-tests.mjs +226 -0
  151. package/tests/scripts/lib/somi-mcp-tests.mjs +21 -1
  152. package/tests/scripts/loop-engine.sh +22 -0
  153. package/tests/scripts/loop-flow-gate.sh +11 -0
  154. package/tests/scripts/review-panel-seats.sh +4 -4
  155. package/tests/scripts/run-card.sh +57 -0
  156. package/tests/scripts/run-suites.sh +74 -0
  157. package/tests/scripts/run.sh +11 -0
  158. package/tests/scripts/site-roadmap-gate.sh +76 -0
  159. package/tests/scripts/size-tier.sh +3 -3
  160. package/tests/scripts/somi-agent-dispatch-contract.sh +23 -3
  161. package/tests/scripts/somi-config.sh +9 -4
  162. package/tests/scripts/somi-mcp.sh +1 -0
  163. package/tests/scripts/suite-plan.json +20 -0
@@ -0,0 +1,145 @@
1
+ // config-files.mjs -- where SoMi's config lives, how it is read, and how the files combine. Every
2
+ // reader of the config goes through loadConfig() so the hooks, the loops and the resolver cannot
3
+ // disagree on what is configured.
4
+ //
5
+ // Two files, both optional, the same schema:
6
+ // global one per user, read by every project and session (see globalConfigPath below)
7
+ // project <root>/.somi/config.json, usually committed
8
+ // The effective config is the global file with the project file merged over it: objects merge key
9
+ // by key, recursively; any other value (string, number, boolean, null, array) replaces. A project
10
+ // that sets only cost.agents.somi-coder and cost.mapping.<host>.medium therefore changes exactly
11
+ // those two, and a model list in the project replaces the global list for that tier, never extends it.
12
+ //
13
+ // Reading follows links: a junction or symlinked .somi, or a config file linked from elsewhere, is
14
+ // read through. What the read refuses is what could hurt: anything that is not a regular file once
15
+ // opened (a FIFO cannot hang the open, O_NONBLOCK; /dev/zero is not a regular file) and anything over
16
+ // MAX_CONFIG_BYTES, both checked on the open descriptor. A project config is untrusted (cloned) input
17
+ // either way: following a link lets a hostile repo choose which file is read, not see it, because no
18
+ // message echoes file text. Writers never follow links; see scripts/somi-config.mjs.
19
+
20
+ import fs from 'node:fs';
21
+ import os from 'node:os';
22
+ import path from 'node:path';
23
+
24
+ export const MAX_CONFIG_BYTES = 64 * 1024;
25
+ export const GLOBAL_CONFIG_ENV = 'SOMI_GLOBAL_CONFIG';
26
+ // Real configs are a few levels deep. A bound keeps the recursive merge and copy below from running out
27
+ // of stack on a hostile file, the same on every Node version (their stack sizes differ).
28
+ export const MAX_CONFIG_DEPTH = 64;
29
+
30
+ const READ_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0);
31
+
32
+ export class ConfigFileError extends Error {}
33
+
34
+ const isObj = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
35
+
36
+ /**
37
+ * The global config file, or null when there is none to read. SOMI_GLOBAL_CONFIG wins when set (a
38
+ * path; empty means no global config). Otherwise %APPDATA%\somi\config.json on Windows, else
39
+ * $XDG_CONFIG_HOME/somi/config.json (an absolute XDG_CONFIG_HOME only), else ~/.config/somi/config.json.
40
+ */
41
+ export function globalConfigPath(env = process.env, platform = process.platform, home = os.homedir()) {
42
+ if (env[GLOBAL_CONFIG_ENV] !== undefined) {
43
+ const p = env[GLOBAL_CONFIG_ENV];
44
+ return p === '' || p.includes('${') ? null : path.resolve(p);
45
+ }
46
+ if (platform === 'win32') return path.join(env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'somi', 'config.json');
47
+ const xdg = env.XDG_CONFIG_HOME;
48
+ return path.join(xdg && path.isAbsolute(xdg) ? xdg : path.join(home, '.config'), 'somi', 'config.json');
49
+ }
50
+
51
+ export const projectConfigPath = (root) => path.join(root, '.somi', 'config.json');
52
+
53
+ /** The file's text (links followed), or null when nothing is there. Throws ConfigFileError otherwise,
54
+ * including for a link to a missing file. */
55
+ export function readConfigText(file) {
56
+ let fd;
57
+ try {
58
+ fd = fs.openSync(file, READ_FLAGS);
59
+ } catch (e) {
60
+ // A link whose target is gone (say, a shared drive not mounted) is not "no config": the policy it
61
+ // pointed to would silently fall back to the defaults.
62
+ if (e.code === 'ENOENT' && !fs.lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink()) return null;
63
+ throw new ConfigFileError(`${file} cannot be opened (${e.code === 'ENOENT' ? 'a link to a missing file' : e.code ?? 'error'})`);
64
+ }
65
+ try {
66
+ if (!fs.fstatSync(fd).isFile()) throw new ConfigFileError(`${file} is not a regular file`);
67
+ const buf = Buffer.alloc(MAX_CONFIG_BYTES + 1);
68
+ let n = 0;
69
+ while (n < buf.length) {
70
+ const got = fs.readSync(fd, buf, n, buf.length - n, null);
71
+ if (got === 0) break;
72
+ n += got;
73
+ }
74
+ if (n > MAX_CONFIG_BYTES) throw new ConfigFileError(`${file} is over the ${MAX_CONFIG_BYTES}-byte limit`);
75
+ return buf.toString('utf8', 0, n);
76
+ } finally {
77
+ fs.closeSync(fd);
78
+ }
79
+ }
80
+
81
+ // Iterative, so measuring a hostile depth cannot itself overflow the stack.
82
+ function depthExceeds(root, max) {
83
+ const stack = [[root, 1]];
84
+ while (stack.length) {
85
+ const [v, d] = stack.pop();
86
+ if (d > max) return true;
87
+ if (v !== null && typeof v === 'object') for (const c of Object.values(v)) if (c !== null && typeof c === 'object') stack.push([c, d + 1]);
88
+ }
89
+ return false;
90
+ }
91
+
92
+ /**
93
+ * Parses config text into a JSON object. The parser's own message quotes the text, so only its error
94
+ * name and position are reported. Which keys are legal is the validators' decision (cost-config.mjs);
95
+ * a `__proto__` key stays an ordinary own property here and in mergeConfig, never a prototype.
96
+ */
97
+ export function parseConfigText(text, file) {
98
+ let cfg;
99
+ try {
100
+ cfg = JSON.parse(text);
101
+ } catch (e) {
102
+ const pos = /position (\d+)/.exec(String(e.message))?.[1];
103
+ throw new ConfigFileError(`${file} is not valid JSON (${JSON.stringify(e.name)}${pos ? ` at position ${pos}` : ''})`);
104
+ }
105
+ if (!isObj(cfg)) throw new ConfigFileError(`${file} is not a JSON object`);
106
+ if (depthExceeds(cfg, MAX_CONFIG_DEPTH)) throw new ConfigFileError(`${file} is nested deeper than ${MAX_CONFIG_DEPTH} levels`);
107
+ return cfg;
108
+ }
109
+
110
+ /** The parsed file, or null when absent. */
111
+ export function readConfigFile(file) {
112
+ const text = readConfigText(file);
113
+ return text === null ? null : parseConfigText(text, file);
114
+ }
115
+
116
+ // A deep copy whose keys are all own data properties (JSON.parse defines, never assigns), so a
117
+ // `__proto__` key is copied as data and cannot set a prototype.
118
+ const copy = (v) => (v === undefined ? undefined : JSON.parse(JSON.stringify(v)));
119
+ const define = (obj, k, v) => Object.defineProperty(obj, k, { value: v, enumerable: true, writable: true, configurable: true });
120
+
121
+ /** `over` merged onto `base` into a new object; neither argument is modified. Both must be objects. */
122
+ export function mergeConfig(base, over) {
123
+ const out = copy(base);
124
+ for (const [k, v] of Object.entries(over)) {
125
+ const prev = Object.hasOwn(out, k) ? out[k] : undefined;
126
+ define(out, k, isObj(v) && isObj(prev) ? mergeConfig(prev, v) : copy(v));
127
+ }
128
+ return out;
129
+ }
130
+
131
+ /**
132
+ * The effective config for a project: {config, global, project}, each file as {path, present, config}
133
+ * (`path` null for a global config that is switched off). Throws ConfigFileError naming the file.
134
+ */
135
+ export function loadConfig(root, env = process.env) {
136
+ const gPath = globalConfigPath(env);
137
+ const pPath = projectConfigPath(root);
138
+ const g = gPath ? readConfigFile(gPath) : null;
139
+ const p = readConfigFile(pPath);
140
+ return {
141
+ config: mergeConfig(g ?? {}, p ?? {}),
142
+ global: { path: gPath, present: g !== null, config: g ?? {} },
143
+ project: { path: pPath, present: p !== null, config: p ?? {} },
144
+ };
145
+ }
@@ -1,6 +1,9 @@
1
1
  // cost-ceiling.mjs — the session cost ceiling: the tier every dispatch runs at unless an agent has
2
2
  // its own override in .somi/config.json.
3
3
  //
4
+ // "The config" below is the effective one: the global file with the project's .somi/config.json
5
+ // merged over it (scripts/lib/config-files.mjs).
6
+ //
4
7
  // The ceiling is re-resolved on every call, nothing is frozen once. Precedence, highest first:
5
8
  // 1. a value given THIS call: an argument the caller parsed itself (a CLI flag) or SOMI_COST_CEILING
6
9
  // 2. `cost.ceiling` in .somi/config.json, read live on every call
@@ -30,6 +33,7 @@ import fs from 'node:fs';
30
33
  import path from 'node:path';
31
34
  import { resolveModel, VALID_COSTS } from './cost-model.mjs';
32
35
  import { validateCostConfig, quote } from './cost-config.mjs';
36
+ import { loadConfig, ConfigFileError, MAX_CONFIG_BYTES as CONFIG_LIMIT } from './config-files.mjs';
33
37
 
34
38
  export const CEILING_ENV = 'SOMI_COST_CEILING';
35
39
  export const DEFAULT_CEILING = 'medium';
@@ -45,13 +49,14 @@ function nowIso() {
45
49
  return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
46
50
  }
47
51
 
48
- // A committed config is untrusted input, read whole into memory and into the model's reach; a file
49
- // this large is not a config, so it is refused rather than parsed.
50
- export const MAX_CONFIG_BYTES = 64 * 1024;
52
+ // A file this large is neither a config nor a state file, so it is refused rather than parsed.
53
+ export const MAX_CONFIG_BYTES = CONFIG_LIMIT;
51
54
 
52
- // Opened with O_NOFOLLOW (a committed symlink -- say to /dev/zero -- is refused, never followed) and
53
- // O_NONBLOCK (a FIFO cannot hang the open), then checked on the open descriptor, not the path, so
54
- // there is no stat-then-read race. At most MAX_CONFIG_BYTES+1 bytes are ever read.
55
+ // The reader for SoMi's own state files (the persisted ceiling): opened with O_NOFOLLOW (a planted
56
+ // symlink -- say to /dev/zero -- is refused, never followed) and O_NONBLOCK (a FIFO cannot hang the
57
+ // open), then checked on the open descriptor, not the path, so there is no stat-then-read race. At
58
+ // most MAX_CONFIG_BYTES+1 bytes are ever read. Config files are read by config-files.mjs instead,
59
+ // which follows links (a junction or symlinked .somi, a linked config) under the same other checks.
55
60
  const OPEN_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
56
61
 
57
62
  export function readTextFile(file) {
@@ -85,23 +90,16 @@ function parseFailure(file, e) {
85
90
  return new Error(`cost-ceiling: ${file} is not valid JSON (${JSON.stringify(e.name)}${pos ? ` at position ${pos}` : ''})`);
86
91
  }
87
92
 
93
+ // The effective config. A file that fails to PARSE is not "unconfigured" -- silently returning {}
94
+ // would bootstrap DEFAULT_CEILING and PERSIST it, inverting a team's `low` policy until someone
95
+ // notices, and outliving the typo once fixed. Dies loudly, naming the file.
88
96
  export function readConfig(root) {
89
- const file = path.join(root, '.somi', 'config.json');
90
- let raw;
91
97
  try {
92
- raw = readTextFile(file);
98
+ return loadConfig(root).config;
93
99
  } catch (e) {
94
- if (e.code === 'ENOENT') return {}; // no config committed: nothing configured, defaults apply
100
+ if (e instanceof ConfigFileError) throw new Error(`cost-ceiling: ${e.message}`);
95
101
  throw e;
96
102
  }
97
- try {
98
- return JSON.parse(raw);
99
- } catch (e) {
100
- // A committed config that fails to PARSE is not "unconfigured" -- silently returning {} here
101
- // would bootstrap DEFAULT_CEILING and PERSIST it, inverting a team's `low` policy until
102
- // someone notices, and outliving the typo once fixed. Dies loudly, naming the file.
103
- throw parseFailure(file, e);
104
- }
105
103
  }
106
104
 
107
105
  // A `cost` that isn't an object, has an unrecognized key (a typo), or a `ceiling` misplaced at
@@ -110,12 +108,21 @@ export function readConfig(root) {
110
108
  // Exported: this is also the one config reader scripts/somi-dispatch.mjs uses to pull `mapping`
111
109
  // (its `ceiling` sibling), so a project's cost config is never parsed by two independent readers
112
110
  // that could drift on what counts as malformed.
111
+ // Each file's own cost block is validated first, so an error names the file it is in; then the merge.
113
112
  export function readCostConfig(root) {
114
- const cfg = readConfig(root);
115
- if (cfg.ceiling !== undefined) {
116
- throw new Error('cost-ceiling: "ceiling" in .somi/config.json belongs under "cost.ceiling"');
113
+ let files;
114
+ try {
115
+ files = loadConfig(root);
116
+ } catch (e) {
117
+ if (e instanceof ConfigFileError) throw new Error(`cost-ceiling: ${e.message}`);
118
+ throw e;
119
+ }
120
+ for (const f of [files.global, files.project]) {
121
+ if (!f.present) continue;
122
+ if (f.config.ceiling !== undefined) throw new Error(`cost-ceiling: "ceiling" in ${f.path} belongs under "cost.ceiling"`);
123
+ try { validateCostConfig(f.config.cost); } catch (e) { throw new Error(`${e.message} (in ${f.path})`); }
117
124
  }
118
- return validateCostConfig(cfg.cost);
125
+ return validateCostConfig(files.config.cost);
119
126
  }
120
127
 
121
128
  function validateCeiling(raw, label) {
@@ -19,6 +19,8 @@ export const AGENT_DEFAULT_TIERS = Object.freeze(Object.assign(Object.create(nul
19
19
  'somi-coder': 'medium',
20
20
  'somi-designer': 'high',
21
21
  'somi-discovery-analyst': 'high',
22
+ 'somi-flow': 'medium',
23
+ 'somi-general': 'medium',
22
24
  'somi-impact': 'medium',
23
25
  'somi-incident': 'medium',
24
26
  'somi-plan-reviewer': 'high',
@@ -0,0 +1,146 @@
1
+ // escalation-facts.mjs — diffFacts(rows, options): the facts escalation() reads, from the per-file rows of a diff.
2
+ //
3
+ // A row is { file, added, deleted, status }: the changed-file listing's shape plus git's status letter. The listing must be
4
+ // read NUL-separated (`-z`): git's default form quotes a non-ASCII name (`"\303\251/a.pem"`), which the deny list cannot
5
+ // read, so a name that starts with a double quote is an unusable row here (a name that really starts with one over-flags),
6
+ // and so is a name with a control, format or line-separator character (`.e<ZWNJ>nv` is `.env` on HFS+).
7
+ // Pure but for a clock: no filesystem, no git, no content, and no path in the result. Returns
8
+ // { facts, source, notes }
9
+ // facts escalation()'s input: counts, flags and class names from its closed lists
10
+ // source where each plan input came from: { plan: ['target'|'paths'], sdlc: ['slug'|'paths'] }, as ids
11
+ // notes ids of what degraded: rows_unusable (not a list, over MAX_ROWS, or a count past the safe integers), row_unusable, time_box, config_refused,
12
+ // internal_error (a bug here: the result is the floor, never a throw)
13
+ // options: { config, slug, target, planPaths, workItemPaths, budgetMs }. `config` is loadConfig's `{global, project}` result or
14
+ // nothing: any other shape (a merged `.config` erases the user's own additions) is noted `config_refused`, adds the sensitive name
15
+ // `config` (a refused config must raise, never lower) and the built-in lists apply. The layers are read once, into plain copies
16
+ // (a getter cannot answer differently on a later read), and those copies are what the classifier sees.
17
+ // A key of it that classifyPaths refuses is noted too. Only a refused `sensitive_paths` adds `config`; a refused `module_containers`
18
+ // adds nothing, and the module count then reads low (the container names group more children into modules).
19
+ // `target` is the review target a caller names (a plan directory, a brief or an ADR path), judged by its name only. `planPaths`
20
+ // and `workItemPaths` are names-only lists the caller built; only whether they are empty matters. `budgetMs` can only shorten
21
+ // TIME_BOX_MS.
22
+ //
23
+ // Every degraded outcome (an unusable row too: it may hide anything) is the FLOOR, the top of the lattice: every count at the cap, every
24
+ // class name, every flag, so each seat, reason, hard-surface id and flag is at least a full read's. A time box cannot interrupt
25
+ // synchronous code, so the clock is read between chunks of CHUNK rows: the bound is the budget plus one chunk, which is small
26
+ // because classifyPaths caps the cost of one path. The clock starts before the first row is read, so the row checks count too, and
27
+ // it is read at least once whatever the kept count. A denied name sets `denied` whatever its status or prefix: a deleted `.env`
28
+ // floors, and so does one under `.somi/`. Rows under `.somi/` and `.claude/` are ignored (the measurement excludes them), by their
29
+ // exact prefix, and every row, ignored or not, is read for the guard: on its segments folded as the deny list folds them (case,
30
+ // compatibility forms, trailing dots and spaces, either separator) a segment `.claude` at any depth and with no exemption, a
31
+ // `CLAUDE.md`, `CLAUDE.local.md` or `AGENTS.md` segment at any depth, a `.mcp.json` segment at any depth, a `.vscode` segment directly followed by
32
+ // `mcp.json` (project MCP servers: a command that runs on a developer's machine), or a first segment `.somi` alone or followed
33
+ // by `config.json` or `rules`, is the sensitive name `config`. A case variant (`agents.md`) raises too: the folded name is the name. A row that is not a plain name (an empty, `.` or `..`
34
+ // segment, git never writes one) is unusable.
35
+ // `new_top_dirs` counts first directories whose every changed row is an add; a diff cannot know the base, so a directory that
36
+ // existed and only gained files reads as new, and the residual is one extra architecture seat.
37
+ import { MAX_GLOBS, classifyPaths } from './path-facts.mjs';
38
+ import { MAX_PATH_CHARS, UNSAFE_CHARS, denyListed, foldName, trimDots } from './path-safety.mjs';
39
+ import { CLASS_NAMES } from './escalation.mjs';
40
+
41
+ export const MAX_ROWS = 2000;
42
+ export const TIME_BOX_MS = 3000;
43
+ const CHUNK = 10; // rows per clock read: well under classifyPaths' list cap, and about 0.6 s at its worst-case cost per path
44
+ const KINDS = ['sensitive', 'boundary', 'contract'];
45
+ const COUNTS = ['production_lines', 'production_files', 'test_lines_added', 'test_lines_deleted', 'test_files_deleted', 'test_files_changed', 'modules', 'new_top_dirs'];
46
+
47
+ const count = (v) => Number.isSafeInteger(v) && v >= 0;
48
+ const SEP = /[\\/]/;
49
+ // A name's segments as the deny list reads them: each raw segment folded and re-split (a fold can make a separator), dots and spaces trimmed off the end.
50
+ const pieces = (file) => file.split(SEP).flatMap((s) => foldName(s).split(SEP)).map(trimDots);
51
+ const sane = (r) => r !== null && typeof r === 'object' && typeof r.file === 'string' && r.file.length > 0 && r.file.length <= MAX_PATH_CHARS && foldName(r.file).length <= MAX_PATH_CHARS
52
+ && !r.file.startsWith('"') && !UNSAFE_CHARS.test(r.file) && !pieces(r.file).includes('') && count(r.added) && count(r.deleted) && typeof r.status === 'string' && /^[A-Z]$/.test(r.status);
53
+ const hidden = (file) => ['.somi', '.claude'].includes(file.split('/')[0]);
54
+ const guarded = (file) => {
55
+ const segs = pieces(file); const [head, second] = segs;
56
+ return segs.includes('.claude') || segs.includes('claude.md') || segs.includes('claude.local.md') || segs.includes('agents.md') || segs.includes('.mcp.json')
57
+ || segs.some((s, i) => s === '.vscode' && segs[i + 1] === 'mcp.json') || (head === '.somi' && (second === undefined || second === 'config.json' || second === 'rules'));
58
+ };
59
+ const plain = (o) => o !== null && typeof o === 'object' && !Array.isArray(o);
60
+ const once = (o, k) => (plain(o) && Object.hasOwn(o, k) ? o[k] : undefined); // the one read of a key
61
+ // A list read by index into a plain array, capped just over the limit (a list over the cap stays over it); a hole reads as undefined, which the classifier refuses.
62
+ const glist = (v) => (Array.isArray(v) ? Array.from({ length: Math.min(v.length, MAX_GLOBS + 1) }, (_, i) => v[i]) : v);
63
+ // The config layers as plain copies of what the classifier reads, each accessor read once; null when the shape is not loadConfig's.
64
+ function layersOf(c) {
65
+ if (c === undefined) return [];
66
+ const layers = [];
67
+ for (const k of ['global', 'project']) {
68
+ const cfg = once(once(c, k), 'config');
69
+ if (!plain(cfg)) return null;
70
+ const sizing = once(cfg, 'sizing');
71
+ layers.push({ sizing: { sensitive_paths: glist(once(sizing, 'sensitive_paths')), module_containers: glist(once(sizing, 'module_containers')) } });
72
+ }
73
+ return layers;
74
+ }
75
+ const given = (v) => v !== undefined && v !== null && v !== false && v !== '' && !(Array.isArray(v) && v.length === 0);
76
+ const PLAN_TARGET = /(^|\/)(\.somi\/plans|adrs?|decisions)(\/|$)|(^|\/)(brief\.md|adr[-_]?\d[^/]*)$/;
77
+ const names = (set) => [...set].sort();
78
+
79
+ // An unusable `target` (not a string, or over the length cap) counts as a plan target: a bad input raises a seat, never removes one.
80
+ function planInputs({ slug, target, planPaths, workItemPaths }) {
81
+ const named = given(target) && (typeof target !== 'string' || target.length > MAX_PATH_CHARS || PLAN_TARGET.test(target.normalize('NFKC').toLowerCase().replaceAll('\\', '/')));
82
+ const facts = { plan_target: named, plan_paths: given(planPaths), slug_given: given(slug), work_item_paths: given(workItemPaths) };
83
+ const source = { plan: [...(named ? ['target'] : []), ...(facts.plan_paths ? ['paths'] : [])], sdlc: [...(facts.slug_given ? ['slug'] : []), ...(facts.work_item_paths ? ['paths'] : [])] };
84
+ return { facts, source };
85
+ }
86
+
87
+ const EVERY_PLAN_SEAT = { facts: { plan_target: true, plan_paths: true, slug_given: true, work_item_paths: true }, source: { plan: ['target', 'paths'], sdlc: ['slug', 'paths'] } };
88
+
89
+ // No test lines added and no test file changed keep `tests_weakened` and `untested_production` on: they are the two facts a count cannot raise.
90
+ const floor = (plan) => ({ ...Object.fromEntries(COUNTS.map((k) => [k, 1e9])), test_lines_added: 0, test_files_changed: 0, denied: true, ...plan,
91
+ classes: Object.fromEntries(Object.entries(CLASS_NAMES).map(([k, v]) => [k, [...v]])) });
92
+
93
+ function measure(rows, opts, plan) {
94
+ const start = Date.now();
95
+ if (!Array.isArray(rows) || rows.length > MAX_ROWS) return { facts: floor(plan), notes: ['rows_unusable'] };
96
+ if (!rows.every(sane)) return { facts: floor(plan), notes: ['row_unusable'] };
97
+ const f = { ...Object.fromEntries(COUNTS.map((k) => [k, 0])), denied: false, ...plan };
98
+ const seen = { sensitive: new Set(), boundary: new Set(), contract: new Set() };
99
+ const modules = new Set(); const tops = new Map(); const kept = []; const notes = new Set();
100
+ const layers = layersOf(opts.config);
101
+ if (layers === null) { notes.add('config_refused'); seen.sensitive.add('config'); }
102
+ const config = layers ?? [];
103
+ const refused = classifyPaths([], config).refused; // no row may be needed to learn that a key was refused
104
+ if (refused.length > 0) notes.add('config_refused');
105
+ if (refused.includes('sensitive_paths')) seen.sensitive.add('config');
106
+ for (const r of rows) {
107
+ if (guarded(r.file)) seen.sensitive.add('config');
108
+ if (!hidden(r.file)) kept.push(r); else f.denied ||= denyListed(r.file);
109
+ }
110
+ const budget = Math.min(TIME_BOX_MS, Number.isFinite(opts.budgetMs) && opts.budgetMs >= 0 ? opts.budgetMs : TIME_BOX_MS);
111
+ let at = 0;
112
+ do { // the clock is read at least once, whatever the kept count
113
+ if (Date.now() - start >= budget) return { facts: floor(plan), notes: ['time_box'] };
114
+ const chunk = kept.slice(at, at + CHUNK);
115
+ const result = classifyPaths(chunk.map((r) => r.file), config);
116
+ result.files.forEach((c, j) => {
117
+ const r = chunk[j];
118
+ f.denied ||= c.denied;
119
+ for (const k of KINDS) c[k].forEach((n) => seen[k].add(n));
120
+ modules.add(c.module);
121
+ if (c.production) { f.production_lines += r.added + r.deleted; f.production_files++; } else {
122
+ f.test_lines_added += r.added; f.test_lines_deleted += r.deleted; f.test_files_changed++;
123
+ if (r.status === 'D') f.test_files_deleted++;
124
+ }
125
+ const dirs = r.file.split(/[\\/]+/).filter((x) => x !== '' && x !== '.');
126
+ if (dirs.length > 1) tops.set(dirs[0], (tops.get(dirs[0]) ?? true) && r.status === 'A');
127
+ });
128
+ at += CHUNK;
129
+ } while (at < kept.length);
130
+ f.modules = modules.size; f.new_top_dirs = [...tops.values()].filter(Boolean).length;
131
+ if (!COUNTS.every((k) => count(f[k]))) return { facts: floor(plan), notes: ['rows_unusable'] }; // a sum past the safe integers is no count
132
+ // CI paths are a sensitive name (they raise security); `classes.ci` carries the hard-surface id beside it.
133
+ f.classes = { sensitive: names(seen.sensitive), boundary: names(seen.boundary), contract: names(seen.contract), ci: seen.sensitive.has('ci') ? ['ci'] : [] };
134
+ return { facts: f, notes: names(notes) };
135
+ }
136
+
137
+ export function diffFacts(rows, options) {
138
+ let plan = EVERY_PLAN_SEAT; // until the options are read
139
+ try {
140
+ const opts = options ?? {};
141
+ plan = planInputs(opts);
142
+ return { ...measure(rows, opts, plan.facts), source: plan.source };
143
+ } catch {
144
+ return { facts: floor(plan.facts), source: plan.source, notes: ['internal_error'] };
145
+ }
146
+ }
@@ -0,0 +1,129 @@
1
+ // escalation.mjs — escalation(facts): which review lenses does the shape of a diff warrant?
2
+ //
3
+ // Pure: no import, no filesystem, no clock, no content. The input is counts, flags and class names (what
4
+ // classifyPaths and a diff's per-file rows give); no path and no diff text goes in, so none can come out. Output:
5
+ // { review_min, reasons, tests_weakened, size_flag, hard_surface, seats: { <lens>: { seat, reasons } } }
6
+ // `review_min` is `security` or null and nothing else (the loop's validator allows only that). A sensitive or
7
+ // boundary class name, a denied name or weakened tests raise it. Size only marks: `size_flag` changes no lens.
8
+ //
9
+ // Raise-only, with two exceptions: every fact is ordered (a class name present, a flag set, a count over its edge is the
10
+ // more alarming value) and every output grows with it, so a fact added never removes a seat, a reason, a hard-surface id
11
+ // or the flag, except more test lines added (`tests_weakened` reads net lines, so padding tests switches it off) and a
12
+ // test file changed (drops `untested_production`). There is no config. A result is never lowered across passes because
13
+ // the loop takes the max with the earlier pass. The input is a closed grammar read once into a plain
14
+ // copy: an unknown or missing key, a wrong type, a negative count, an unknown class name, an accessor or a
15
+ // non-plain object is the refused result, which is the raising result (every seat, every hard-surface id), as
16
+ // size-tier does for unreadable signals. An unexpected error in the rules themselves (a bug, not the input) is the same raising
17
+ // result under its own reason id, so it is not reported as unreadable input. `escalation` never throws.
18
+ //
19
+ // Provisional: the numbers are the research report's guesses (150 lines, 5 files) or the planner's, and live
20
+ // here so they can be fitted without touching the rules.
21
+
22
+ export const SIZE_FLAG_LINES = 150;
23
+ export const SIZE_FLAG_FILES = 5;
24
+ export const WEAKENED_NET_LINES = 20;
25
+ export const MAX_MODULES_SEAT = 2;
26
+ export const LARGE_TEST_CHANGE = 100;
27
+ export const UNTESTED_PRODUCTION_LINES = 60;
28
+ export const MAX_CLASS_NAMES = 16;
29
+ export const REFUSED_REASON = 'facts_unreadable';
30
+ export const INTERNAL_REASON = 'internal_error';
31
+ const DENY = 'deny_list';
32
+
33
+ const freezeAll = (o) => Object.freeze(Object.fromEntries(Object.entries(o).map(([k, v]) => [k, Object.freeze(v)])));
34
+ export const HARD_SURFACE_IDS = Object.freeze(['ci', DENY, 'lockfile', 'manifest', 'migration', 'schema']);
35
+ export const CLASS_NAMES = freezeAll({
36
+ sensitive: ['auth', 'ci', 'config', 'crypto', DENY, 'infra', 'migrations', 'secrets'],
37
+ boundary: ['data', DENY, 'input', 'process', 'routes'],
38
+ contract: ['lockfile', 'manifest', 'schema'],
39
+ ci: ['ci'],
40
+ });
41
+ // The reason ids each lens can carry (`sensitive:<name>` and `contract:<name>` are listed by prefix); the lens table in
42
+ // the review-panel flow is compared with this.
43
+ export const SEAT_REASONS = freezeAll({
44
+ 'somi-reviewer': ['always'],
45
+ 'somi-security-reviewer': ['sensitive', 'boundary', DENY, 'tests_weakened'],
46
+ 'somi-architecture-reviewer': ['new_top_dirs', 'contract', 'modules'],
47
+ 'somi-test-strategist': ['tests_weakened', 'large_test_change', 'untested_production'],
48
+ 'somi-plan-reviewer': ['plan_target', 'plan_paths'],
49
+ 'somi-sdlc-reviewer': ['slug_given', 'work_item_paths'],
50
+ });
51
+ const SEATS = Object.keys(SEAT_REASONS);
52
+ const COUNTS = ['production_lines', 'production_files', 'test_lines_added', 'test_lines_deleted', 'test_files_deleted', 'test_files_changed', 'modules', 'new_top_dirs'];
53
+ const FLAGS = ['denied', 'plan_target', 'plan_paths', 'slug_given', 'work_item_paths'];
54
+
55
+ const refuse = () => { throw new TypeError('unreadable facts'); };
56
+ const isPlain = (o) => o !== null && typeof o === 'object' && [Object.prototype, null].includes(Object.getPrototypeOf(o));
57
+ const own = (o, k) => { const d = Object.getOwnPropertyDescriptor(o, k); return d && 'value' in d ? d.value : refuse(); };
58
+ const keysAre = (o, want) => { const have = Reflect.ownKeys(o); return (have.length === want.length && want.every((k) => have.includes(k))) || refuse(); };
59
+
60
+ function names(list, allowed) {
61
+ if (!Array.isArray(list) || Object.getPrototypeOf(list) !== Array.prototype || list.length > MAX_CLASS_NAMES) refuse();
62
+ const slots = Array.from({ length: list.length }, (_, i) => String(i));
63
+ keysAre(list, [...slots, 'length']);
64
+ const out = slots.map((i) => own(list, i));
65
+ return out.every((n) => allowed.includes(n)) ? [...new Set(out)].sort() : refuse();
66
+ }
67
+
68
+ function read(facts) {
69
+ if (!isPlain(facts)) refuse();
70
+ keysAre(facts, [...COUNTS, ...FLAGS, 'classes']);
71
+ const f = {};
72
+ for (const k of COUNTS) { const v = own(facts, k); f[k] = Number.isSafeInteger(v) && v >= 0 ? v : refuse(); }
73
+ for (const k of FLAGS) { const v = own(facts, k); f[k] = typeof v === 'boolean' ? v : refuse(); }
74
+ const classes = own(facts, 'classes');
75
+ if (!isPlain(classes)) refuse();
76
+ keysAre(classes, Object.keys(CLASS_NAMES));
77
+ f.classes = Object.fromEntries(Object.keys(CLASS_NAMES).map((k) => [k, names(own(classes, k), CLASS_NAMES[k])]));
78
+ return f;
79
+ }
80
+
81
+ const seated = (byLens) => Object.fromEntries(SEATS.map((l) => [l, { seat: byLens[l].length > 0, reasons: byLens[l] }]));
82
+ const when = (on, id) => (on ? [id] : []);
83
+
84
+ function judge(f) {
85
+ const { sensitive, boundary, contract, ci } = f.classes;
86
+ const net = f.test_lines_added - f.test_lines_deleted;
87
+ const tests_weakened = net < 0 && (f.test_files_deleted >= 1 || -net >= WEAKENED_NET_LINES);
88
+ const denied = f.denied || sensitive.includes(DENY) || boundary.includes(DENY);
89
+ const reasons = [
90
+ ...sensitive.filter((n) => n !== DENY).map((n) => `sensitive:${n}`),
91
+ ...boundary.filter((n) => n !== DENY).map((n) => `boundary:${n}`),
92
+ ...when(denied, DENY), ...when(tests_weakened, 'tests_weakened'),
93
+ ];
94
+ const hard = [...contract, ...when(sensitive.includes('migrations'), 'migration'), ...when(ci.length > 0 || sensitive.includes('ci'), 'ci'), ...when(denied, DENY)];
95
+ return {
96
+ review_min: reasons.length > 0 ? 'security' : null,
97
+ reasons,
98
+ tests_weakened,
99
+ size_flag: f.production_lines > SIZE_FLAG_LINES || f.production_files > SIZE_FLAG_FILES,
100
+ hard_surface: [...new Set(hard)].sort(),
101
+ seats: seated({
102
+ 'somi-reviewer': ['always'],
103
+ 'somi-security-reviewer': reasons,
104
+ 'somi-architecture-reviewer': [...when(f.new_top_dirs >= 1, 'new_top_dirs'), ...contract.map((n) => `contract:${n}`), ...when(f.modules > MAX_MODULES_SEAT, 'modules')],
105
+ 'somi-test-strategist': [
106
+ ...when(tests_weakened, 'tests_weakened'),
107
+ ...when(f.test_lines_added + f.test_lines_deleted >= LARGE_TEST_CHANGE, 'large_test_change'),
108
+ ...when(f.production_lines >= UNTESTED_PRODUCTION_LINES && f.test_files_changed === 0, 'untested_production'),
109
+ ],
110
+ 'somi-plan-reviewer': [...when(f.plan_target, 'plan_target'), ...when(f.plan_paths, 'plan_paths')],
111
+ 'somi-sdlc-reviewer': [...when(f.slug_given, 'slug_given'), ...when(f.work_item_paths, 'work_item_paths')],
112
+ }),
113
+ };
114
+ }
115
+
116
+ const refused = (reason) => ({
117
+ review_min: 'security',
118
+ reasons: [reason],
119
+ tests_weakened: false,
120
+ size_flag: true,
121
+ hard_surface: [...HARD_SURFACE_IDS],
122
+ seats: seated(Object.fromEntries(SEATS.map((l) => [l, [reason]]))),
123
+ });
124
+
125
+ export function escalation(facts) {
126
+ let f;
127
+ try { f = read(facts); } catch { return refused(REFUSED_REASON); }
128
+ try { return judge(f); } catch { return refused(INTERNAL_REASON); }
129
+ }