@skathio/somi 3.1.1 → 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.
- package/.claude/settings.json +13 -0
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/.copilot-extension/extension.json +1 -1
- package/.copilot-extension/marketplace.json +2 -2
- package/README.md +34 -24
- package/VERSION +1 -1
- package/agents/{architecture-reviewer.md → somi-architecture-reviewer.md} +10 -11
- package/agents/{atlas.md → somi-atlas.md} +3 -5
- package/agents/{coder.md → somi-coder.md} +26 -23
- package/agents/{designer.md → somi-designer.md} +9 -11
- package/agents/{discovery-analyst.md → somi-discovery-analyst.md} +7 -9
- package/agents/{impact.md → somi-impact.md} +6 -8
- package/agents/{incident.md → somi-incident.md} +2 -4
- package/agents/{plan-reviewer.md → somi-plan-reviewer.md} +9 -11
- package/agents/{planner.md → somi-planner.md} +16 -24
- package/agents/{pr.md → somi-pr.md} +2 -4
- package/agents/{refactor-designer.md → somi-refactor-designer.md} +14 -15
- package/agents/{refactorer.md → somi-refactorer.md} +11 -12
- package/agents/{reviewer.md → somi-reviewer.md} +8 -7
- package/agents/{sdlc-reviewer.md → somi-sdlc-reviewer.md} +8 -10
- package/agents/{security-reviewer.md → somi-security-reviewer.md} +8 -8
- package/agents/{test-strategist.md → somi-test-strategist.md} +4 -6
- package/agents/somi.md +25 -12
- package/commands/adopt.md +9 -10
- package/commands/architecture-review.md +4 -5
- package/commands/atlas.md +3 -3
- package/commands/code-loop.md +38 -14
- package/commands/code-parallel.md +4 -4
- package/commands/code.md +24 -15
- package/commands/debug.md +8 -9
- package/commands/design.md +14 -15
- package/commands/discover.md +11 -12
- package/commands/impact.md +2 -2
- package/commands/incident.md +3 -4
- package/commands/plan-loop.md +16 -12
- package/commands/plan.md +15 -16
- package/commands/pr.md +2 -2
- package/commands/refactor-design.md +10 -11
- package/commands/refactor.md +7 -8
- package/commands/release-readiness.md +6 -7
- package/commands/review-panel.md +24 -23
- package/commands/review.md +14 -14
- package/commands/security-review.md +8 -7
- package/commands/ship-loop.md +107 -28
- package/commands/ship.md +6 -6
- package/commands/somi-config.md +138 -0
- package/commands/test-strategy.md +3 -4
- package/commands/upgrade.md +4 -5
- package/examples/code-review-example.md +1 -1
- package/examples/discovery-example.md +1 -1
- package/examples/feature-plan-example.md +2 -2
- package/hooks/hooks.json +14 -1
- package/hooks/lib/common.mjs +71 -9
- package/hooks/post-tool/audit-log.mjs +3 -2
- package/hooks/pre-tool/block-secret-writes.mjs +12 -11
- package/hooks/pre-tool/guard-cost-lowering.mjs +192 -0
- package/hooks/pre-tool/guard-protected-paths.mjs +13 -3
- package/hooks/session-start/detect-repo-instructions.mjs +27 -2
- package/hooks/session-start/ensure-default-config.mjs +113 -0
- package/package.json +1 -1
- package/rules/00-priorities.md +1 -1
- package/rules/30-security-owasp.md +1 -1
- package/rules/50-collaboration.md +9 -6
- package/rules/CLAUDE.md +11 -10
- package/scripts/lib/agent-info.mjs +85 -0
- package/scripts/lib/agent-registry.mjs +92 -0
- package/scripts/lib/config-files.mjs +145 -0
- package/scripts/lib/cost-ceiling.mjs +190 -179
- package/scripts/lib/cost-config-edit.mjs +102 -0
- package/scripts/lib/cost-config.mjs +64 -0
- package/scripts/lib/cost-defaults.mjs +51 -0
- package/scripts/lib/cost-lowering.mjs +89 -0
- package/scripts/lib/cost-model.mjs +37 -22
- package/scripts/lib/dispatch-resolver.mjs +59 -50
- package/scripts/lib/loop-diff.mjs +96 -0
- package/scripts/lib/loop-dispatch.mjs +19 -0
- package/scripts/lib/loop-review.mjs +52 -0
- package/scripts/lib/run-budget.mjs +28 -0
- package/scripts/lib/size-tier.mjs +184 -0
- package/scripts/lib/tier-record.mjs +82 -0
- package/scripts/size-budget-overrides.json +7 -15
- package/scripts/somi-check.mjs +4 -3
- package/scripts/somi-config.mjs +421 -0
- package/scripts/somi-dispatch.mjs +1 -1
- package/scripts/somi-loop.mjs +75 -99
- package/scripts/somi-mcp.mjs +135 -14
- package/scripts/somi-tier.mjs +393 -0
- package/scripts/validate.sh +57 -215
- package/skills/api-design/SKILL.md +1 -1
- package/skills/clean-code/SKILL.md +1 -1
- package/skills/market-research/SKILL.md +2 -2
- package/skills/owasp-defense/SKILL.md +2 -2
- package/skills/plan-review/SKILL.md +5 -1
- package/skills/reasoning-craft/SKILL.md +1 -1
- package/skills/requirements-engineering/SKILL.md +3 -3
- package/skills/solid-principles/SKILL.md +1 -1
- package/skills/somi-dispatch/SKILL.md +104 -109
- package/skills/somi-routing/SKILL.md +88 -1
- package/skills/testing-playbook/SKILL.md +2 -2
- package/skills/threat-modeling/SKILL.md +3 -3
- package/templates/BRIEF.md.tmpl +2 -2
- package/templates/DESIGN.md.tmpl +1 -1
- package/templates/DOD.md.tmpl +2 -2
- package/templates/PHASE.md.tmpl +2 -2
- package/templates/RCA.md.tmpl +1 -1
- package/templates/REVIEW.md.tmpl +3 -2
- package/templates/SDD.md.tmpl +1 -1
- package/templates/SPEC.md.tmpl +1 -1
- package/templates/TDD.md.tmpl +1 -1
- package/tests/hooks/cases/block-secret-writes.json +130 -17
- package/tests/hooks/cases/detect-repo-instructions.json +22 -1
- package/tests/hooks/cases/guard-protected-paths.json +175 -25
- package/tests/scripts/agent-model-frontmatter.sh +38 -0
- package/tests/scripts/agent-names.sh +77 -0
- package/tests/scripts/check-frontmatter.sh +1 -1
- package/tests/scripts/checkpoint-gate.sh +44 -3
- package/tests/scripts/convergence-runner.sh +10 -6
- package/tests/scripts/cost-ceiling.sh +127 -215
- package/tests/scripts/cost-defaults.sh +128 -0
- package/tests/scripts/cost-hardcap.sh +338 -0
- package/tests/scripts/cost-lowering.sh +261 -0
- package/tests/scripts/cost-model.sh +18 -14
- package/tests/scripts/dispatch-guard.sh +7 -7
- package/tests/scripts/dispatch-line-gate.sh +61 -0
- package/tests/scripts/dispatch-reference-gate.sh +13 -13
- package/tests/scripts/ensure-default-config.sh +162 -0
- package/tests/scripts/eval-runner.sh +9 -9
- package/tests/scripts/evals-packaging.sh +127 -20
- package/tests/scripts/fixtures/size-tier-cases.json +87 -0
- package/tests/scripts/global-config.sh +167 -0
- package/tests/scripts/goldens/loop-state-done.json +1 -1
- package/tests/scripts/goldens/somi-loop.json +3 -3
- package/tests/scripts/lib/agent-registry-tests.mjs +95 -0
- package/tests/scripts/lib/brief-only-guard.mjs +27 -0
- package/tests/scripts/lib/checkpoint-gate.mjs +40 -3
- package/tests/scripts/lib/dispatch-reference-gate.mjs +5 -5
- package/tests/scripts/lib/retirement-gate.mjs +7 -2
- package/tests/scripts/lib/ship-loop-sizing-guard.mjs +52 -0
- package/tests/scripts/lib/site-roadmap-gate.mjs +64 -0
- package/tests/scripts/lib/size-tier-drift.mjs +74 -0
- package/tests/scripts/lib/somi-mcp-config-tests.mjs +92 -0
- package/tests/scripts/lib/somi-mcp-tests.mjs +66 -28
- package/tests/scripts/lib/somi-mcp-tier-tests.mjs +64 -0
- package/tests/scripts/retirement-gate.sh +19 -0
- package/tests/scripts/review-panel-seats.sh +2 -2
- package/tests/scripts/run.sh +95 -0
- package/tests/scripts/site-roadmap-gate.sh +76 -0
- package/tests/scripts/size-tier.sh +562 -0
- package/tests/scripts/somi-agent-dispatch-contract.sh +20 -11
- package/tests/scripts/somi-config.sh +286 -0
- package/tests/scripts/somi-dispatch.sh +150 -98
- package/tests/scripts/somi-mcp.sh +2 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// agent-info.mjs — the read-only somi_agent_info lookup: the agent catalog, or one identifier (a
|
|
2
|
+
// canonical name or a registered alias) normalised through agent-registry.mjs and resolved through the
|
|
3
|
+
// shared dispatch resolver with persist:false, so a lookup reports what a dispatch would get right now
|
|
4
|
+
// and writes nothing (no ceiling argument is accepted, and an env ceiling is never remembered).
|
|
5
|
+
//
|
|
6
|
+
// Pure apart from the resolver's reads: the caller supplies the project root lookup (the MCP server's
|
|
7
|
+
// can be a roots/list round trip) and the install root, and turns {ok, ...} into its own surface.
|
|
8
|
+
|
|
9
|
+
import { buildRegistry, normalize, agentTypeFor, catalog, ORCHESTRATOR } from './agent-registry.mjs';
|
|
10
|
+
import { resolveDispatch, EXIT_USAGE, EXIT_UNKNOWN_AGENT } from './dispatch-resolver.mjs';
|
|
11
|
+
|
|
12
|
+
// Built once: an alias collision fails at import, before any lookup answers.
|
|
13
|
+
const REGISTRY = buildRegistry();
|
|
14
|
+
const HOST_RE = /^[a-z][a-z0-9-]{0,31}$/;
|
|
15
|
+
|
|
16
|
+
export const AGENT_INFO_TOOL = {
|
|
17
|
+
name: 'somi_agent_info',
|
|
18
|
+
description:
|
|
19
|
+
'Read-only agent registry and dispatch lookup. Without `agent`: the catalog of every canonical ' +
|
|
20
|
+
'SoMi agent with the aliases hosts actually register for it and its default tier. With `agent` ' +
|
|
21
|
+
'(a canonical name such as "somi-coder" or a registered alias such as "somi:somi-coder"): the ' +
|
|
22
|
+
'canonical agent, the alias that matched, `agent_type` (the id to pass as the host subagent ' +
|
|
23
|
+
'type), and the tier and model it would run at right now on `host` — from the same resolver as ' +
|
|
24
|
+
'somi_resolve, but nothing is written: no ceiling is set or remembered. Failures: 64 invalid ' +
|
|
25
|
+
'identifier or arguments, 65 unknown agent or alias (never routed to another agent), 67 ' +
|
|
26
|
+
'project environment failure (as somi_resolve).',
|
|
27
|
+
inputSchema: {
|
|
28
|
+
type: 'object',
|
|
29
|
+
properties: {
|
|
30
|
+
agent: { type: 'string', description: 'canonical name or registered alias; omit for the catalog' },
|
|
31
|
+
host: { type: 'string', description: '"claude-code" or "copilot"; defaults to "claude-code"' },
|
|
32
|
+
project_dir: { type: 'string', description: 'absolute path of the consuming project, as for somi_resolve (lookup only)' },
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const fail = (code, message) => ({ ok: false, code, message });
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @param {{agent?: unknown, host?: unknown}} args
|
|
41
|
+
* @param {{resolveRoot: () => Promise<{ok: boolean, root?: string, code?: number, message?: string}>, installRoot: string}} env
|
|
42
|
+
* @returns {Promise<{ok: true, result: object} | {ok: false, code: number, message: string}>}
|
|
43
|
+
*/
|
|
44
|
+
export async function agentInfo(args, { resolveRoot, installRoot }) {
|
|
45
|
+
const host = args?.host;
|
|
46
|
+
if (host !== undefined && (typeof host !== 'string' || !HOST_RE.test(host))) {
|
|
47
|
+
return fail(EXIT_USAGE, `host must be a lowercase host name, got ${JSON.stringify(host)}`);
|
|
48
|
+
}
|
|
49
|
+
if (args?.agent === undefined) return { ok: true, result: { agents: catalog(REGISTRY) } };
|
|
50
|
+
const n = normalize(REGISTRY, args.agent);
|
|
51
|
+
if (!n.ok) return fail(n.reason === 'invalid' ? EXIT_USAGE : EXIT_UNKNOWN_AGENT, n.message);
|
|
52
|
+
const HOST = host || 'claude-code';
|
|
53
|
+
const identity = {
|
|
54
|
+
requested_as: args.agent,
|
|
55
|
+
canonical_name: n.canonical,
|
|
56
|
+
matched_alias: n.matched_alias,
|
|
57
|
+
aliases: REGISTRY.aliasesOf.get(n.canonical).filter((a) => a !== n.matched_alias),
|
|
58
|
+
agent_type: agentTypeFor(REGISTRY, n.canonical, HOST),
|
|
59
|
+
host: HOST,
|
|
60
|
+
};
|
|
61
|
+
if (n.canonical === ORCHESTRATOR) {
|
|
62
|
+
return { ok: true, result: { ...identity, role: 'orchestrator', dispatch: null, reason: 'the front door is selected by the user, never dispatched; the host binds its model' } };
|
|
63
|
+
}
|
|
64
|
+
const root = await resolveRoot();
|
|
65
|
+
if (!root.ok) return fail(root.code, root.message);
|
|
66
|
+
const outcome = resolveDispatch({ agent: n.canonical, host: HOST, projectRoot: root.root, installRoot, persist: false });
|
|
67
|
+
if (!outcome.ok) return outcome;
|
|
68
|
+
const r = outcome.result;
|
|
69
|
+
return {
|
|
70
|
+
ok: true,
|
|
71
|
+
result: {
|
|
72
|
+
...identity,
|
|
73
|
+
role: 'specialist',
|
|
74
|
+
session_ceiling: { value: r.ceiling, source: r.ceiling_source, origin: r.ceiling_origin },
|
|
75
|
+
default_tier: r.declared[0],
|
|
76
|
+
dispatch_tier: r.tier,
|
|
77
|
+
tier_source: r.tier_source,
|
|
78
|
+
degraded: r.degraded,
|
|
79
|
+
model: r.model,
|
|
80
|
+
...(r.model_candidates ? { model_candidates: r.model_candidates } : {}),
|
|
81
|
+
enforced: r.enforced,
|
|
82
|
+
...(r.reason ? { reason: r.reason } : {}),
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// agent-registry.mjs — the one source of SoMi agent identity: canonical names, the aliases hosts
|
|
2
|
+
// actually register for them, and the normalisation from either one to the canonical name.
|
|
3
|
+
//
|
|
4
|
+
// Canonical names are the default tier table's keys (every specialist, `somi-` prefixed) plus the
|
|
5
|
+
// front-door orchestrator `somi`, which is exempt from cost resolution. tests/scripts/agent-registry.sh
|
|
6
|
+
// keeps this set equal to agents/*.md.
|
|
7
|
+
//
|
|
8
|
+
// Aliases are never guessed. A host that registers SoMi's plugin agents under ids of its own is
|
|
9
|
+
// declared in HOST_REGISTRATIONS with the rule it applies; an alias exists only for a host listed
|
|
10
|
+
// there. Both shipped hosts namespace a plugin agent as `<plugin>:<file stem>`:
|
|
11
|
+
// - copilot: the loader in Copilot CLI 1.0.70 (configLoaderParsePluginAgentFile in its runtime.node),
|
|
12
|
+
// run on this repo, returns ids such as `somi:somi-planner`; its task tool accepts any registered
|
|
13
|
+
// id and rejects a bare stem with `Unknown agent_type`.
|
|
14
|
+
// - claude-code: the Task tool lists plugin agents as `somi:<file stem>`.
|
|
15
|
+
// So today every agent has exactly one alias, `somi:<canonical>`, registered on both hosts. The
|
|
16
|
+
// pre-4.0.0 bare names (`coder`) are deliberately NOT aliases: they are unknown, with a derived hint.
|
|
17
|
+
|
|
18
|
+
import { AGENT_DEFAULT_TIERS } from './cost-defaults.mjs';
|
|
19
|
+
|
|
20
|
+
export const PLUGIN_NAME = 'somi';
|
|
21
|
+
export const ORCHESTRATOR = 'somi';
|
|
22
|
+
|
|
23
|
+
// host -> the id that host's subagent tool takes for a plugin agent's canonical name.
|
|
24
|
+
export const HOST_REGISTRATIONS = Object.freeze({
|
|
25
|
+
'claude-code': (canonical) => `${PLUGIN_NAME}:${canonical}`,
|
|
26
|
+
copilot: (canonical) => `${PLUGIN_NAME}:${canonical}`,
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
// An identifier as a caller may supply it: a canonical name, or `<plugin>:<name>`. Checked before
|
|
30
|
+
// any lookup, so nothing downstream ever sees an unvalidated string.
|
|
31
|
+
export const IDENTIFIER_RE = /^[a-z0-9][a-z0-9-]{0,63}(?::[a-z0-9][a-z0-9-]{0,63})?$/;
|
|
32
|
+
|
|
33
|
+
export class RegistryError extends Error {}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Builds the registry from a tier table and host registrations (both overridable for tests).
|
|
37
|
+
* Throws RegistryError when one alias would map to two agents or shadow a canonical name.
|
|
38
|
+
*/
|
|
39
|
+
export function buildRegistry(table = AGENT_DEFAULT_TIERS, registrations = HOST_REGISTRATIONS) {
|
|
40
|
+
const specialists = Object.keys(table).sort();
|
|
41
|
+
const agents = [...specialists, ORCHESTRATOR];
|
|
42
|
+
const canonical = new Set(agents);
|
|
43
|
+
const aliasOwner = new Map();
|
|
44
|
+
const aliasesOf = new Map(agents.map((n) => [n, []]));
|
|
45
|
+
const agentTypes = new Map(agents.map((n) => [n, {}]));
|
|
46
|
+
for (const host of Object.keys(registrations).sort()) {
|
|
47
|
+
for (const name of agents) {
|
|
48
|
+
const alias = registrations[host](name);
|
|
49
|
+
agentTypes.get(name)[host] = alias;
|
|
50
|
+
if (alias === name) continue;
|
|
51
|
+
if (canonical.has(alias)) throw new RegistryError(`alias "${alias}" (host ${host}) shadows the canonical agent "${alias}"`);
|
|
52
|
+
const owner = aliasOwner.get(alias);
|
|
53
|
+
if (owner !== undefined && owner !== name) throw new RegistryError(`alias "${alias}" maps to both "${owner}" and "${name}"`);
|
|
54
|
+
if (owner === undefined) {
|
|
55
|
+
aliasOwner.set(alias, name);
|
|
56
|
+
aliasesOf.get(name).push(alias);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return { specialists, canonical, aliasOwner, aliasesOf, agentTypes, table };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* -> {ok: true, canonical, matched_alias} | {ok: false, reason: 'invalid'|'unknown', message}.
|
|
65
|
+
* An identifier that is a pre-4.0.0 bare name gets a hint, derived rather than stored.
|
|
66
|
+
*/
|
|
67
|
+
export function normalize(registry, identifier) {
|
|
68
|
+
if (typeof identifier !== 'string' || !IDENTIFIER_RE.test(identifier)) {
|
|
69
|
+
return { ok: false, reason: 'invalid', message: `invalid agent identifier ${JSON.stringify(identifier)} (expected ${IDENTIFIER_RE})` };
|
|
70
|
+
}
|
|
71
|
+
if (registry.canonical.has(identifier)) return { ok: true, canonical: identifier, matched_alias: null };
|
|
72
|
+
const owner = registry.aliasOwner.get(identifier);
|
|
73
|
+
if (owner !== undefined) return { ok: true, canonical: owner, matched_alias: identifier };
|
|
74
|
+
const renamed = `somi-${identifier}`;
|
|
75
|
+
const hint = registry.canonical.has(renamed) ? ` (renamed in 4.0.0: use "${renamed}")` : '';
|
|
76
|
+
return { ok: false, reason: 'unknown', message: `unknown agent "${identifier}"${hint}` };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The id `host`'s subagent tool takes for `canonical`, or null when the host registers none. */
|
|
80
|
+
export function agentTypeFor(registry, canonical, host) {
|
|
81
|
+
return registry.agentTypes.get(canonical)?.[host] ?? null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The catalog: one entry per agent, specialists first, in name order. */
|
|
85
|
+
export function catalog(registry) {
|
|
86
|
+
return [...registry.specialists, ORCHESTRATOR].map((name) => ({
|
|
87
|
+
canonical_name: name,
|
|
88
|
+
role: name === ORCHESTRATOR ? 'orchestrator' : 'specialist',
|
|
89
|
+
aliases: [...registry.aliasesOf.get(name)],
|
|
90
|
+
default_tier: registry.table[name] ?? null,
|
|
91
|
+
}));
|
|
92
|
+
}
|
|
@@ -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
|
+
}
|