@skathio/somi 4.0.0 → 4.0.1

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.
@@ -13,7 +13,7 @@
13
13
  "url": "https://github.com/skathio/somi.git"
14
14
  },
15
15
  "description": "Multi-agent engineering workflow: discover/design → plan → code → review. Each agent has a default cost tier and a per-session ceiling caps it; SOLID, OWASP and clean-code guardrails.",
16
- "version": "4.0.0",
16
+ "version": "4.0.1",
17
17
  "tags": ["workflow", "agents", "review", "security"],
18
18
  "homepage": "https://github.com/skathio/somi"
19
19
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "somi",
3
- "version": "4.0.0",
3
+ "version": "4.0.1",
4
4
  "displayName": "SoMi",
5
5
  "description": "Multi-agent engineering workflow system: plan, code, review — with SOLID/OWASP guardrails, deterministic hooks, and a global ruleset.",
6
6
  "keywords": [
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "somi",
3
3
  "displayName": "SoMi",
4
- "version": "4.0.0",
4
+ "version": "4.0.1",
5
5
  "description": "Multi-agent engineering workflow system: plan, code, review — with SOLID/OWASP guardrails, deterministic hooks, and a global ruleset.",
6
6
  "keywords": [
7
7
  "workflow",
@@ -11,7 +11,7 @@
11
11
  "name": "somi",
12
12
  "source": "github:skathio/somi",
13
13
  "description": "Multi-agent engineering workflow: discover/design → plan → code → review. Each agent has a default cost tier and a per-session ceiling caps it; SOLID, OWASP and clean-code guardrails.",
14
- "version": "4.0.0",
14
+ "version": "4.0.1",
15
15
  "tags": ["workflow", "agents", "review", "security"],
16
16
  "homepage": "https://github.com/skathio/somi"
17
17
  }
package/README.md CHANGED
@@ -4,6 +4,9 @@
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/@skathio/somi?logo=npm)](https://www.npmjs.com/package/@skathio/somi)
6
6
 
7
+ **Overview page:** <https://skathio.github.io/somi/>: the roadmap, the workflow and the cost system on
8
+ one page.
9
+
7
10
  The latest published version is on [npm](https://www.npmjs.com/package/@skathio/somi) and in the
8
11
  [GitHub Releases](https://github.com/skathio/somi/releases); see [CHANGELOG.md](CHANGELOG.md) for
9
12
  release notes.
@@ -149,6 +152,7 @@ tests/ Behavioral fixtures for hooks + end-to-end tests for the runti
149
152
  .copilot-extension/ Copilot extension + marketplace manifests (mirrors .claude-plugin/)
150
153
  examples/ Worked examples + a minimal consuming project
151
154
  docs/ Full documentation
155
+ site/ The overview page (GitHub Pages; not in the npm package)
152
156
  ```
153
157
 
154
158
  When you use SoMi in a project, workflows write their artifacts into a `.somi/` directory
@@ -156,7 +160,8 @@ at the project root. Discovery foundations live under `.somi/rd/<slug>/` (resear
156
160
  FRD, SDD, TDD); plans live under `.somi/plans/<slug>/` (context, spec, decisions, progress, diary,
157
161
  phases — or a one-page `rca.md` for `/debug` items); reviews live under `.somi/reviews/<slug>/`
158
162
  (including the machine-readable findings ledger, `findings.json`); the repo-wide map lives at
159
- `.somi/atlas.md` (from `/atlas`); optional committed policy lives at `.somi/config.json` —
163
+ `.somi/atlas.md` (from `/atlas`); optional committed policy lives at `.somi/config.json`, merged over
164
+ your [global config](docs/USAGE.md#the-global-config) —
160
165
  separate directories, no clutter. See [`docs/WORKFLOWS.md`](docs/WORKFLOWS.md) for the full layout.
161
166
 
162
167
  ---
package/VERSION CHANGED
@@ -1 +1 @@
1
- 4.0.0
1
+ 4.0.1
@@ -1,5 +1,5 @@
1
1
  ---
2
- description: Show and change SoMi's cost settings (the ceiling, each agent's tier, and the model each tier means on a host) in .somi/config.json, with a question for every change. Lowering a tier or remapping a model needs your explicit confirmation.
2
+ description: Show and change SoMi's cost settings (the ceiling, each agent's tier, and the model each tier means on a host) in your global config and the project's .somi/config.json, with a question for every change. Lowering a tier or remapping a model needs your explicit confirmation.
3
3
  argument-hint: "[what to change, e.g. ceiling or security-reviewer]"
4
4
  allowed-tools: AskUserQuestion, Read, Bash
5
5
  ---
@@ -8,8 +8,9 @@ allowed-tools: AskUserQuestion, Read, Bash
8
8
 
9
9
  You are running the **cost-settings workflow** of somi. This command has no `cost:` of its own — nor
10
10
  a `model:` of its own; it runs inline on whatever model this session is already using, and Tasks no
11
- agent. It reads and writes only the `cost.ceiling` and `cost.agents` settings of the project's
12
- `.somi/config.json`, and only through the `somi_config` tool, which validates every change.
11
+ agent. It shows the effective cost settings (your global config with the project's `.somi/config.json`
12
+ merged over it) and writes only the project file's `cost.*` settings, only through the `somi_config`
13
+ tool, which validates every change.
13
14
 
14
15
  The user's hint: **$ARGUMENTS**
15
16
 
@@ -22,7 +23,10 @@ The user's hint: **$ARGUMENTS**
22
23
 
23
24
  - `cost.ceiling` is the tier every agent runs at unless that agent has its own entry.
24
25
  - `cost.agents.<name>` pins one agent to a tier. A pin wins over the ceiling, even above it.
25
- - The file is read on every dispatch, so a change applies to the **next** dispatch.
26
+ - Two files: the **global config** every project reads, and the project's `.somi/config.json`, whose
27
+ values win key by key. The tool changes only the project file; the global one is the user's, with
28
+ `node scripts/somi-config.mjs set <key> <value> --global` (or by editing it).
29
+ - The files are read on every dispatch, so a change applies to the **next** dispatch.
26
30
  - A `SOMI_COST_CEILING` environment variable, or a ceiling an earlier `--ceiling` flag persisted,
27
31
  can
28
32
  outrank the file's value. The tool reports when that is the case; relay it.
@@ -42,9 +46,10 @@ The user's hint: **$ARGUMENTS**
42
46
  mark
43
47
  (`^ above ceiling`) on a row whose override is above the ceiling, and `unknown` on a name SoMi
44
48
  does
45
- not ship. Print every entry of `warnings` **word for word**, never summarised or softened. If the
46
- file does not exist (`exists: false`), say that every agent then follows the ceiling and offer
47
- `init`.
49
+ not ship, and for every pin and the ceiling the file it came from (`from`: global or project).
50
+ Print every entry of `warnings` **word for word**, never summarised or softened. If neither file
51
+ exists (`exists` and `global.exists` both false), say that every agent then follows the ceiling
52
+ and offer `init`.
48
53
  3. **Ask what to do** with the `AskUserQuestion` tool, one question at a time:
49
54
  - change the global ceiling;
50
55
  - pin or unpin one agent;
@@ -119,7 +124,9 @@ supplied; if the tool says there is none, give the same CLI command.
119
124
 
120
125
  - **Only `cost.ceiling`, `cost.agents.<name>` and `cost.mapping.<host>.<tier>`.** Nothing else in
121
126
  the file is touched, and the tool refuses any other key.
122
- - **Never write the file or the persisted ceiling directly**, and never use `Bash` to change either.
127
+ - **Never write a config file or the persisted ceiling directly**, and never use `Bash` to change
128
+ them. The global config is never yours to change: a user who wants a setting everywhere runs the
129
+ `--global` command themselves.
123
130
  The `Bash` tool here is only for the read-only `show` fallback.
124
131
  - **Never pass a hint, a file's text or a guess as a key or value.** The user's answers choose them.
125
132
  - **Never say a change is saved** until the tool has returned success.
@@ -25,6 +25,7 @@
25
25
  import fs from 'node:fs';
26
26
  import path from 'node:path';
27
27
  import { fileURLToPath } from 'node:url';
28
+ import { loadConfig } from '../../scripts/lib/config-files.mjs';
28
29
 
29
30
  // Thrown by denyPretool() (and available to any hook that needs an early,
30
31
  // non-local exit) to unwind to the hook's own top-level handler — mirrors
@@ -213,8 +214,10 @@ export function auditLogPath() {
213
214
  return log;
214
215
  }
215
216
 
216
- // somi::config equivalent — reads a value from the project's committed
217
- // config at .somi/config.json. `fieldPath` is a minimal jq-path string:
217
+ // somi::config equivalent — reads a value from the effective config: the global
218
+ // file with the project's .somi/config.json merged over it, read through
219
+ // scripts/lib/config-files.mjs (links followed, regular file, 64 KiB at most), the
220
+ // same loader every other reader uses. `fieldPath` is a minimal jq-path string:
218
221
  // dotted keys, optionally ending in "[]?" to request every element of an
219
222
  // array (mirrors gate-dep-install.sh's `.dep_install.allow[]?` /
220
223
  // `mapfile -t` idiom). These are the ONLY two shapes any `somi::config` call
@@ -224,7 +227,7 @@ export function auditLogPath() {
224
227
  // shape in this comment.
225
228
  //
226
229
  // Precedence contract (callers enforce it, same as the bash original): env
227
- // var > .somi/config.json > default.
230
+ // var > project .somi/config.json > global config > default.
228
231
  export function config(fieldPath) {
229
232
  const arrayMode = fieldPath.endsWith('[]?');
230
233
  const keys = (arrayMode ? fieldPath.slice(0, -3) : fieldPath)
@@ -232,13 +235,9 @@ export function config(fieldPath) {
232
235
  .split('.')
233
236
  .filter(Boolean);
234
237
 
235
- const base = projectRoot();
236
- const cfgPath = path.join(base, '.somi', 'config.json');
237
- if (!fs.existsSync(cfgPath)) return arrayMode ? [] : '';
238
-
239
238
  let data;
240
239
  try {
241
- data = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
240
+ data = loadConfig(projectRoot()).config;
242
241
  } catch {
243
242
  return arrayMode ? [] : ''; // matches jq's `2>/dev/null || true` on invalid JSON
244
243
  }
@@ -13,6 +13,10 @@
13
13
  // - Write / Edit / MultiEdit of <project>/.somi/config.json (the path is resolved against the project
14
14
  // root, so `.somi/../.somi/config.json` and a symlinked .somi resolve to the same file): `after` = the
15
15
  // written content, or the current text with the edits applied exactly as the Edit tool would.
16
+ // Both sides are judged as the resolver sees them: the global config with the project file merged
17
+ // over it (scripts/lib/config-files.mjs), so a project file that drops below a global pin is a lowering.
18
+ // - Any file-tool write to the global config asks, whatever it changes: that file applies to every
19
+ // project and session, and the somi_config tool never writes it (only the user, through the CLI).
16
20
  //
17
21
  // Fail closed to the user: for a config-file path, any inability to evaluate (unreadable or unparsable
18
22
  // content, an edit that does not apply, an exception) asks. Nothing from any file is ever echoed.
@@ -23,12 +27,14 @@ import fs from 'node:fs';
23
27
  import path from 'node:path';
24
28
  import { pathToFileURL } from 'node:url';
25
29
  import { readPayload, field, askPretool, HookExit, projectRoot, writeTargets } from '../lib/common.mjs';
30
+ import { globalConfigPath, mergeConfig, parseConfigText, readConfigFile, readConfigText } from '../../scripts/lib/config-files.mjs';
26
31
 
27
32
  const LIB = path.join(import.meta.dirname, '..', '..', 'scripts', 'lib');
28
33
  const UNEVALUABLE = 'SoMi: this change to .somi/config.json could not be evaluated, so it needs your confirmation.';
29
34
  const OUTSIDE = 'SoMi: this call names a project directory outside the project root, so it needs your confirmation.';
30
35
  const STATE_WRITE = 'SoMi: this writes the persisted cost ceiling (.somi/somi-state/ceiling.json), which can lower the ceiling, so it needs your confirmation.';
31
36
  const UNREADABLE_WRITE = 'SoMi: this writes the SoMi cost config or ceiling in a form the guard cannot evaluate, so it needs your confirmation.';
37
+ const GLOBAL_WRITE = 'SoMi: this changes your global SoMi config, which every project and session uses, so it needs your confirmation.';
32
38
  const RESOLVE_LOWER = 'SoMi: this somi_resolve call sets a session ceiling lower than the current one, so it needs your confirmation.';
33
39
  const SECURITY_ONLY = 'SoMi: after this change security-reviewer would run below high (it is not pinned to high). Confirm only if you intend that.';
34
40
  const reasonFor = (reasons, REASONS) => (reasons.length === 1 && reasons[0] === REASONS.security
@@ -61,6 +67,12 @@ function isProjectPath(root, target, segs) {
61
67
  }
62
68
  const isConfigPath = (root, target) => isProjectPath(root, target, ['.somi', 'config.json']);
63
69
  const isStatePath = (root, target) => isProjectPath(root, target, ['.somi', 'somi-state', 'ceiling.json']);
70
+ // The global config, by the same identity rules, its directory standing in for the root.
71
+ const isGlobalPath = (root, target, globalFile) => globalFile !== null
72
+ && isProjectPath(path.dirname(globalFile), path.resolve(root, target), [path.basename(globalFile)]);
73
+ const isObj = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
74
+ // The global config as the resolver reads it ({} when there is none); unreadable throws, and the caller asks.
75
+ const globalConfig = () => { const g = globalConfigPath(); return (g && readConfigFile(g)) ?? {}; };
64
76
 
65
77
  // The project directory a somi_config / somi_resolve call acts on: project_dir when it resolves to the root
66
78
  // or inside it, the root when none is given; anything else is something the hook cannot evaluate: ask.
@@ -80,21 +92,21 @@ function applyOneEdit(text, e) {
80
92
  return e.replace_all === true ? text.split(e.old_string).join(e.new_string) : text.replace(e.old_string, () => e.new_string);
81
93
  }
82
94
 
83
- function readCurrent(readTextFile, file) {
84
- try { return readTextFile(file); } catch (e) { if (e.code === 'ENOENT') return null; throw e; }
85
- }
95
+ // The project config's text, links followed (as the resolver reads it), or null when absent.
96
+ const readCurrent = (file) => readConfigText(file);
86
97
 
87
98
  // somi_resolve({ceiling}) persists a CLI-style ceiling; one below the ceiling in force needs the user.
88
99
  async function resolveCheck(payload, input, root) {
89
100
  if (input.ceiling === undefined) return;
90
101
  const dir = narrowedDir(payload, input, root);
91
102
  try {
92
- const [{ readTextFile, loadState, DEFAULT_CEILING }, { VALID_COSTS }] = await Promise.all(
103
+ const [{ loadState, DEFAULT_CEILING }, { VALID_COSTS }] = await Promise.all(
93
104
  ['cost-ceiling', 'cost-model'].map((m) => import(pathToFileURL(path.join(LIB, `${m}.mjs`)).href)),
94
105
  );
95
106
  if (!VALID_COSTS.includes(input.ceiling)) return; // the tool rejects it itself
96
- const text = readCurrent(readTextFile, path.join(dir, '.somi', 'config.json'));
97
- const cfg = text === null ? {} : JSON.parse(text);
107
+ const file = path.join(dir, '.somi', 'config.json');
108
+ const text = readCurrent(file);
109
+ const cfg = mergeConfig(globalConfig(), text === null ? {} : parseConfigText(text, file));
98
110
  const state = loadState(dir);
99
111
  const effective = VALID_COSTS.includes(cfg?.cost?.ceiling) ? cfg.cost.ceiling
100
112
  : (state && ['cli', 'env'].includes(state.ceiling_origin) ? state.ceiling : DEFAULT_CEILING);
@@ -116,14 +128,16 @@ async function main() {
116
128
 
117
129
  const root = projectRoot();
118
130
  if (isResolve) return resolveCheck(payload, input, root);
131
+ const globalFile = globalConfigPath();
119
132
  // Copilot CLI's file tools (Write with `path`, Edit with a raw patch) carry no file_path and no
120
133
  // before/after the evaluation below can read: a write that reaches the config or the persisted
121
134
  // ceiling in that shape asks. One whose target cannot be read at all is the path guards' to refuse.
122
135
  if (isFileTool && !(typeof input.file_path === 'string' && input.file_path !== '')) {
123
136
  const { paths } = writeTargets(payload);
124
- if (paths.some((p) => isConfigPath(root, p) || isStatePath(root, p))) askPretool(payload, UNREADABLE_WRITE);
137
+ if (paths.some((p) => isConfigPath(root, p) || isStatePath(root, p) || isGlobalPath(root, p, globalFile))) askPretool(payload, UNREADABLE_WRITE);
125
138
  return;
126
139
  }
140
+ if (isFileTool && isGlobalPath(root, input.file_path, globalFile)) askPretool(payload, GLOBAL_WRITE);
127
141
  // Any write to the persisted ceiling file asks: it is the other way to lower the ceiling.
128
142
  if (isFileTool && typeof input.file_path === 'string' && input.file_path !== '' && isStatePath(root, input.file_path)) askPretool(payload, STATE_WRITE);
129
143
  let projDir = root; // the directory whose config is evaluated (and whose persisted ceiling applies)
@@ -140,10 +154,11 @@ async function main() {
140
154
 
141
155
  // From here the call is about the project config: any failure asks.
142
156
  try {
143
- const [{ readTextFile }, { applyEdit, EditError }, { lowers, REASONS }] = await Promise.all(
144
- ['cost-ceiling', 'cost-config-edit', 'cost-lowering'].map((m) => import(pathToFileURL(path.join(LIB, `${m}.mjs`)).href)),
157
+ const [{ applyEdit, EditError }, { lowers, REASONS }] = await Promise.all(
158
+ ['cost-config-edit', 'cost-lowering'].map((m) => import(pathToFileURL(path.join(LIB, `${m}.mjs`)).href)),
145
159
  );
146
- const currentText = readCurrent(readTextFile, file);
160
+ const base = globalConfig();
161
+ const currentText = readCurrent(file);
147
162
  let before = {};
148
163
  if (currentText !== null) { try { before = JSON.parse(currentText); } catch { before = {}; } }
149
164
  let after;
@@ -165,7 +180,7 @@ async function main() {
165
180
  }
166
181
  after = JSON.parse(text);
167
182
  }
168
- const verdict = lowers(before, after, projDir);
183
+ const verdict = lowers(mergeConfig(base, isObj(before) ? before : {}), isObj(after) ? mergeConfig(base, after) : after, projDir);
169
184
  if (verdict.lowers) askPretool(payload, reasonFor(verdict.reasons, REASONS));
170
185
  } catch (e) {
171
186
  if (e instanceof HookExit) throw e;
@@ -7,9 +7,13 @@
7
7
  // file pins each agent to the highest tier it declares and sets the ceiling; see
8
8
  // scripts/lib/cost-defaults.mjs for the table and the exact text this hook writes.
9
9
  //
10
+ // With a global config (scripts/lib/config-files.mjs), that file already supplies the defaults, and a
11
+ // fully pinned project file would mask every one of its values, so nothing is written.
12
+ //
10
13
  // Guarantees (a project's own files are untrusted, and a hook must never block a session):
11
- // - Acts only when NOTHING exists at <root>/.somi/config.json (lstat ENOENT). An existing file of
12
- // any kind — valid, invalid JSON, a symlink (even dangling), a directory — is left untouched.
14
+ // - Acts only when NOTHING exists at <root>/.somi/config.json (lstat ENOENT) and no global config
15
+ // file exists. An existing file of any kind — valid, invalid JSON, a symlink (even dangling), a
16
+ // directory — is left untouched.
13
17
  // - `.somi` must be a real directory (lstat) or absent; a symlink or file there writes nothing.
14
18
  // It is created with mode 0700 only when absent.
15
19
  // - The file is created with O_CREAT|O_EXCL|O_NOFOLLOW, so a race or a planted link at the path
@@ -17,56 +21,38 @@
17
21
  // - The content is a fixed constant, never derived from any existing file.
18
22
  // - Exit code is 0 on every path; no file content or error text is printed. On success it prints
19
23
  // one short, fixed notice through the same SessionStart channel the sibling hook uses.
20
- // - When a regular config file already exists, it is only READ (O_NOFOLLOW, at most 64 KiB): if it
21
- // parses to an object with no own cost.agents["somi-security-reviewer"] tier, or one pinned below high,
22
- // one fixed notice says so (a distinct text for each).
23
- // Nothing from the file reaches the notice, and the file is never written.
24
+ // - When a config file already exists (project or global), the effective config is only READ,
25
+ // through the shared loader (links followed, regular files of at most 64 KiB): if it has no
26
+ // cost.agents["somi-security-reviewer"] tier, or one below high, one fixed notice says so (a distinct
27
+ // text for each, naming the global config when there is one). An unreadable or invalid config prints
28
+ // nothing (the resolver reports it). Nothing from a file reaches the notice, and no file is written.
24
29
 
25
30
  import fs from 'node:fs';
26
31
  import path from 'node:path';
27
32
  import { fileURLToPath, pathToFileURL } from 'node:url';
28
33
  import { projectRoot, contextOutput, runHook } from '../lib/common.mjs';
29
34
 
30
- const DEFAULTS_LIB = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'scripts', 'lib', 'cost-defaults.mjs');
35
+ const LIB = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'scripts', 'lib');
36
+ const DEFAULTS_LIB = path.join(LIB, 'cost-defaults.mjs');
37
+ const CONFIG_LIB = path.join(LIB, 'config-files.mjs');
31
38
  const CREATE = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0);
32
-
33
- const MAX_READ = 64 * 1024;
34
- const READ = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
35
39
  const LOW_PIN_NOTICE = 'SoMi: .somi/config.json pins somi-security-reviewer below high; its security reviews run at that lower tier.';
36
40
  const PIN_NOTICE = 'SoMi: .somi/config.json has no cost.agents pin for somi-security-reviewer, so it runs at the ceiling (below high by default). Pin it under cost.agents to keep the strong pass.';
41
+ const GLOBAL_LOW_PIN_NOTICE = 'SoMi: the SoMi config (your global config, with any .somi/config.json over it) pins somi-security-reviewer below high; its security reviews run at that lower tier.';
42
+ const GLOBAL_PIN_NOTICE = 'SoMi: the SoMi config (your global config, with any .somi/config.json over it) has no cost.agents pin for somi-security-reviewer, so it runs at the ceiling (below high by default). Pin it under cost.agents to keep the strong pass.';
37
43
 
38
44
  function writeAll(fd, text) {
39
45
  const buf = Buffer.from(text);
40
46
  for (let off = 0; off < buf.length;) off += fs.writeSync(fd, buf, off, buf.length - off);
41
47
  }
42
48
 
43
- // For a config that parses to an object: 'missing' when it has no own, valid-tier
44
- // cost.agents["somi-security-reviewer"], 'low' when that entry is below high, else null. Any doubt
45
- // (symlink, not a regular file, oversize, unparsable) is null: the resolver reports those.
46
- function securityPinState(file) {
47
- let fd;
48
- try {
49
- fd = fs.openSync(file, READ);
50
- if (!fs.fstatSync(fd).isFile()) return null;
51
- const buf = Buffer.alloc(MAX_READ + 1);
52
- let n = 0;
53
- while (n < buf.length) {
54
- const got = fs.readSync(fd, buf, n, buf.length - n, null);
55
- if (got === 0) break;
56
- n += got;
57
- }
58
- if (n > MAX_READ) return null;
59
- const cfg = JSON.parse(buf.toString('utf8', 0, n));
60
- if (cfg === null || typeof cfg !== 'object' || Array.isArray(cfg)) return null;
61
- const agents = cfg.cost && typeof cfg.cost === 'object' ? cfg.cost.agents : undefined;
62
- const tier = agents && typeof agents === 'object' && Object.hasOwn(agents, 'somi-security-reviewer') ? agents['somi-security-reviewer'] : undefined;
63
- if (tier === 'low' || tier === 'medium') return 'low';
64
- return tier === 'high' ? null : 'missing';
65
- } catch {
66
- return null;
67
- } finally {
68
- if (fd !== undefined) try { fs.closeSync(fd); } catch { /* already closed */ }
69
- }
49
+ // For the effective config: 'missing' when it has no own, valid-tier cost.agents["somi-security-reviewer"],
50
+ // 'low' when that entry is below high, else null.
51
+ function securityPinState(cfg) {
52
+ const agents = cfg.cost && typeof cfg.cost === 'object' ? cfg.cost.agents : undefined;
53
+ const tier = agents && typeof agents === 'object' && Object.hasOwn(agents, 'somi-security-reviewer') ? agents['somi-security-reviewer'] : undefined;
54
+ if (tier === 'low' || tier === 'medium') return 'low';
55
+ return tier === 'high' ? null : 'missing';
70
56
  }
71
57
 
72
58
  function lstatOrNull(p) {
@@ -79,14 +65,20 @@ async function main() {
79
65
  if (!fs.statSync(root).isDirectory()) return;
80
66
  const somi = path.join(root, '.somi');
81
67
  const file = path.join(somi, 'config.json');
68
+ const { loadConfig, globalConfigPath } = await import(pathToFileURL(CONFIG_LIB).href);
69
+ const globalFile = globalConfigPath();
70
+ const hasGlobal = globalFile !== null && lstatOrNull(globalFile) !== null;
82
71
  const dir = lstatOrNull(somi);
83
- if (dir && !dir.isDirectory()) return; // a symlink or a file: write nothing
84
- const existing = dir ? lstatOrNull(file) : null;
85
- if (existing) { // anything already there is left alone; a regular file is only read
86
- const pin = existing.isFile() ? securityPinState(file) : null;
87
- if (pin) contextOutput('SessionStart', pin === 'low' ? LOW_PIN_NOTICE : PIN_NOTICE);
72
+ const existing = lstatOrNull(file); // through a linked .somi too: reads follow links
73
+ if (existing || hasGlobal) { // a config exists: it is only read, never written
74
+ let files = null;
75
+ try { files = loadConfig(root); } catch { /* the resolver reports an unreadable config */ }
76
+ const pin = files && (files.project.present || files.global.present) ? securityPinState(files.config) : null;
77
+ if (pin === 'low') contextOutput('SessionStart', hasGlobal ? GLOBAL_LOW_PIN_NOTICE : LOW_PIN_NOTICE);
78
+ else if (pin) contextOutput('SessionStart', hasGlobal ? GLOBAL_PIN_NOTICE : PIN_NOTICE);
88
79
  return;
89
80
  }
81
+ if (dir && !dir.isDirectory()) return; // a symlinked .somi or a file: write nothing
90
82
  const { serializeDefaultConfig, buildDefaultConfig } = await import(pathToFileURL(DEFAULTS_LIB).href);
91
83
  const text = serializeDefaultConfig();
92
84
  const ceiling = buildDefaultConfig().cost.ceiling;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skathio/somi",
3
- "version": "4.0.0",
3
+ "version": "4.0.1",
4
4
  "scripts": {
5
5
  "test": "bash scripts/validate.sh",
6
6
  "eval:behavioral": "node tests/evals/run.mjs",
@@ -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
+ }