@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.
- package/.claude/settings.json +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.copilot-extension/extension.json +1 -1
- package/.copilot-extension/marketplace.json +1 -1
- package/README.md +11 -5
- package/VERSION +1 -1
- package/agents/somi-coder.md +4 -228
- package/agents/somi-designer.md +4 -160
- package/agents/somi-discovery-analyst.md +4 -276
- package/agents/somi-flow.md +47 -0
- package/agents/somi-general.md +36 -0
- package/agents/somi-planner.md +4 -341
- package/agents/somi-reviewer.md +4 -199
- package/agents/somi.md +81 -253
- package/commands/adopt.md +6 -84
- package/commands/architecture-review.md +11 -86
- package/commands/atlas.md +10 -25
- package/commands/code-loop.md +10 -221
- package/commands/code-parallel.md +10 -151
- package/commands/code.md +9 -157
- package/commands/debug.md +9 -131
- package/commands/design.md +9 -160
- package/commands/discover.md +9 -194
- package/commands/impact.md +9 -25
- package/commands/incident.md +9 -39
- package/commands/plan-loop.md +9 -181
- package/commands/plan.md +9 -244
- package/commands/pr.md +10 -25
- package/commands/refactor-design.md +11 -89
- package/commands/refactor.md +11 -50
- package/commands/release-readiness.md +11 -70
- package/commands/review-panel.md +10 -141
- package/commands/review.md +11 -181
- package/commands/security-review.md +11 -75
- package/commands/ship-loop.md +9 -260
- package/commands/ship.md +9 -115
- package/commands/somi-config.md +12 -124
- package/commands/test-strategy.md +11 -75
- package/commands/upgrade.md +9 -72
- package/hooks/hooks.json +1 -1
- package/hooks/lib/common.mjs +15 -13
- package/hooks/pre-tool/block-dangerous-bash.mjs +1 -1
- package/hooks/pre-tool/block-secret-writes.mjs +5 -7
- package/hooks/pre-tool/guard-cost-lowering.mjs +26 -11
- package/hooks/pre-tool/guard-protected-paths.mjs +54 -34
- package/hooks/session-start/ensure-default-config.mjs +34 -42
- package/package.json +1 -1
- package/scripts/lib/config-files.mjs +145 -0
- package/scripts/lib/cost-ceiling.mjs +29 -22
- package/scripts/lib/cost-defaults.mjs +2 -0
- package/scripts/lib/escalation-facts.mjs +146 -0
- package/scripts/lib/escalation.mjs +129 -0
- package/scripts/lib/findings-ledger.mjs +241 -0
- package/scripts/lib/install-text.mjs +97 -0
- package/scripts/lib/loop-caps.mjs +140 -0
- package/scripts/lib/loop-diff.mjs +12 -70
- package/scripts/lib/loop-engine.mjs +226 -0
- package/scripts/lib/loop-escalate.mjs +49 -0
- package/scripts/lib/loop-exit.mjs +47 -0
- package/scripts/lib/loop-notes-compact.mjs +72 -0
- package/scripts/lib/loop-notes.mjs +278 -0
- package/scripts/lib/loop-review.mjs +355 -12
- package/scripts/lib/loop-state.mjs +44 -0
- package/scripts/lib/loop-step-close.mjs +75 -0
- package/scripts/lib/loop-step-kit.mjs +179 -0
- package/scripts/lib/loop-step-review.mjs +140 -0
- package/scripts/lib/loop-step-tool.mjs +89 -0
- package/scripts/lib/loop-step.mjs +301 -0
- package/scripts/lib/mcp-project-root.mjs +18 -7
- package/scripts/lib/path-facts.mjs +187 -0
- package/scripts/lib/path-safety.mjs +171 -0
- package/scripts/lib/run-card.mjs +73 -0
- package/scripts/size-budget-overrides.json +5 -13
- package/scripts/somi-card.mjs +39 -0
- package/scripts/somi-check.mjs +4 -3
- package/scripts/somi-config.mjs +113 -50
- package/scripts/somi-findings.mjs +56 -271
- package/scripts/somi-loop.mjs +77 -446
- package/scripts/somi-mcp.mjs +27 -96
- package/scripts/validate.sh +92 -54
- package/skills/flow-adopt/SKILL.md +92 -0
- package/skills/flow-architecture-review/SKILL.md +94 -0
- package/skills/flow-atlas/SKILL.md +34 -0
- package/skills/flow-code/SKILL.md +167 -0
- package/skills/flow-code-loop/SKILL.md +263 -0
- package/skills/flow-code-parallel/SKILL.md +160 -0
- package/skills/flow-debug/SKILL.md +141 -0
- package/skills/flow-design/SKILL.md +170 -0
- package/skills/flow-discover/SKILL.md +204 -0
- package/skills/flow-impact/SKILL.md +35 -0
- package/skills/flow-incident/SKILL.md +49 -0
- package/skills/flow-plan/SKILL.md +254 -0
- package/skills/flow-plan-loop/SKILL.md +254 -0
- package/skills/flow-pr/SKILL.md +34 -0
- package/skills/flow-refactor/SKILL.md +58 -0
- package/skills/flow-refactor-design/SKILL.md +97 -0
- package/skills/flow-release-readiness/SKILL.md +82 -0
- package/skills/flow-review/SKILL.md +193 -0
- package/skills/flow-review-panel/SKILL.md +154 -0
- package/skills/flow-security-review/SKILL.md +83 -0
- package/skills/flow-ship/SKILL.md +125 -0
- package/skills/flow-ship-loop/SKILL.md +274 -0
- package/skills/flow-somi-config/SKILL.md +142 -0
- package/skills/flow-status/SKILL.md +43 -0
- package/skills/flow-test-strategy/SKILL.md +83 -0
- package/skills/flow-upgrade/SKILL.md +82 -0
- package/skills/role-coder/SKILL.md +247 -0
- package/skills/role-designer/SKILL.md +172 -0
- package/skills/role-discovery-analyst/SKILL.md +288 -0
- package/skills/role-planner/SKILL.md +353 -0
- package/skills/role-reviewer/SKILL.md +218 -0
- package/skills/somi-checkpoint/SKILL.md +95 -0
- package/skills/somi-dispatch/SKILL.md +14 -14
- package/skills/somi-routing/SKILL.md +6 -2
- package/tests/hooks/cases/block-secret-writes.json +6 -1
- package/tests/hooks/cases/guard-protected-paths.json +44 -2
- package/tests/hooks/run.sh +21 -0
- package/tests/scripts/checkpoint-gate.sh +2 -2
- package/tests/scripts/cost-defaults.sh +2 -0
- package/tests/scripts/cost-hardcap.sh +26 -17
- package/tests/scripts/dispatch-line-gate.sh +4 -4
- package/tests/scripts/dispatch-reference-gate.sh +14 -14
- package/tests/scripts/ensure-default-config.sh +4 -4
- package/tests/scripts/escalation.sh +409 -0
- package/tests/scripts/eval-runner.sh +8 -7
- package/tests/scripts/fact-sheet.sh +296 -0
- package/tests/scripts/global-config.sh +167 -0
- package/tests/scripts/goldens/somi-loop.json +2 -2
- package/tests/scripts/lib/dispatch-reference-gate.mjs +14 -5
- package/tests/scripts/lib/escalation-facts-tests.mjs +140 -0
- package/tests/scripts/lib/escalation-tests.mjs +154 -0
- package/tests/scripts/lib/findings-ledger-tests.mjs +118 -0
- package/tests/scripts/lib/loop-engine-tests.mjs +287 -0
- package/tests/scripts/lib/loop-escalate-tests.mjs +356 -0
- package/tests/scripts/lib/loop-flow-gate.mjs +173 -0
- package/tests/scripts/lib/loop-notes-tests.mjs +371 -0
- package/tests/scripts/lib/loop-step-cli-tests.mjs +141 -0
- package/tests/scripts/lib/loop-step-close-tests.mjs +351 -0
- package/tests/scripts/lib/loop-step-lenient-tests.mjs +114 -0
- package/tests/scripts/lib/loop-step-state-tests.mjs +127 -0
- package/tests/scripts/lib/loop-step-tests.mjs +499 -0
- package/tests/scripts/lib/loop-step-unwritten-tests.mjs +55 -0
- package/tests/scripts/lib/path-facts-tests.mjs +198 -0
- package/tests/scripts/lib/path-safety-tests.mjs +201 -0
- package/tests/scripts/lib/run-suites.mjs +139 -0
- package/tests/scripts/lib/site-roadmap-gate.mjs +64 -0
- package/tests/scripts/lib/sizing-score-tests.mjs +210 -0
- package/tests/scripts/lib/sizing-set-tests.mjs +131 -0
- package/tests/scripts/lib/somi-mcp-loop-tests.mjs +226 -0
- package/tests/scripts/lib/somi-mcp-tests.mjs +21 -1
- package/tests/scripts/loop-engine.sh +22 -0
- package/tests/scripts/loop-flow-gate.sh +11 -0
- package/tests/scripts/review-panel-seats.sh +4 -4
- package/tests/scripts/run-card.sh +57 -0
- package/tests/scripts/run-suites.sh +74 -0
- package/tests/scripts/run.sh +11 -0
- package/tests/scripts/site-roadmap-gate.sh +76 -0
- package/tests/scripts/size-tier.sh +3 -3
- package/tests/scripts/somi-agent-dispatch-contract.sh +23 -3
- package/tests/scripts/somi-config.sh +9 -4
- package/tests/scripts/somi-mcp.sh +1 -0
- package/tests/scripts/suite-plan.json +20 -0
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Tests of scripts/lib/escalation-facts.mjs. Risk: a diff whose facts come out lower than the diff warrants (a class not
|
|
3
|
+
// mapped, a status ignored, a denied name lost to a prefix, a degraded read returning fewer facts), or a path leaving in
|
|
4
|
+
// the result. Real classifier and real escalation(), no mocks. Usage: node escalation-facts-tests.mjs <module path>;
|
|
5
|
+
// tests/scripts/escalation.sh runs it on the module and on scratch mutants of it, and each mutant must turn the test
|
|
6
|
+
// named there red. Hermetic: no model, no network; the config check writes two files in a temp directory.
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path';
|
|
9
|
+
import { isDeepStrictEqual } from 'node:util'; import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
10
|
+
|
|
11
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
12
|
+
const lib = (name) => import(pathToFileURL(path.join(here, '../../../scripts/lib', name)).href);
|
|
13
|
+
const { diffFacts, MAX_ROWS } = await import(pathToFileURL(path.resolve(process.argv[2])).href);
|
|
14
|
+
const { escalation } = await lib('escalation.mjs');
|
|
15
|
+
const { loadConfig } = await lib('config-files.mjs');
|
|
16
|
+
|
|
17
|
+
let pass = 0; let fail = 0;
|
|
18
|
+
const clip = (v) => JSON.stringify(v).slice(0, 160);
|
|
19
|
+
const check = (name, got, want) => {
|
|
20
|
+
if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${clip(want)}, got ${clip(got)})`); }
|
|
21
|
+
};
|
|
22
|
+
const row = (file, added = 1, deleted = 0, status = 'M') => ({ file, added, deleted, status });
|
|
23
|
+
const diff = (rows, options) => { try { return diffFacts(rows, options); } catch { return { threw: true }; } };
|
|
24
|
+
const esc = (rows, options) => escalation(diff(rows, options).facts);
|
|
25
|
+
const ids = (rows, options) => { const e = esc(rows, options); return [e.review_min, e.reasons, e.hard_surface]; };
|
|
26
|
+
|
|
27
|
+
console.log('== escalation facts: rows to facts ==');
|
|
28
|
+
check('a new 40-line file sizes nothing and raises nothing; auth code raises security as a sensitive name and a routes directory as a boundary one', [ids([row('src/new.mjs', 40, 0, 'A')]), ids([row('src/auth/token.mjs')]).slice(0, 2), ids([row('src/routes/u.mjs')]).slice(0, 2)],
|
|
29
|
+
[[null, [], []], ['security', ['sensitive:auth']], ['security', ['boundary:routes']]]);
|
|
30
|
+
check('a deleted .env, a renamed id_rsa (delete plus add) and a secret under a non-ASCII directory set denied and the deny_list id', [
|
|
31
|
+
[row('.env', 0, 2, 'D')], [row('id_rsa', 0, 3, 'D'), row('keys/id_rsa', 3, 0, 'A')], [row('é/a.pem')],
|
|
32
|
+
].map((r) => [diff(r).facts.denied, ids(r)]), Array(3).fill([true, ['security', ['deny_list'], ['deny_list']]]));
|
|
33
|
+
check('a git-quoted name is an unusable row that floors, never a clean one', [diff([row('"\\303\\251/a.pem"')]).notes, ids([row('"\\303\\251/a.pem"')])[0]], [['row_unusable'], 'security']);
|
|
34
|
+
const HARD = [['package.json', 'manifest'], ['package-lock.json', 'lockfile'], ['db/migrations/001.sql', 'migration'], ['openapi.yaml', 'schema'], ['.github/workflows/ci.yml', 'ci'], ['.env', 'deny_list']];
|
|
35
|
+
check('each hard-surface id comes from its path', HARD.map(([f, id]) => ids([row(f)])[2].includes(id)), HARD.map(() => true));
|
|
36
|
+
check('CI paths raise security as a sensitive name and carry the ci id: .github also hits infra, a bare .circleci only ci', [ids([row('.github/workflows/ci.yml')]), ids([row('.circleci/config.yml')]), diff([row('Jenkinsfile')]).facts.classes],
|
|
37
|
+
[['security', ['sensitive:ci', 'sensitive:infra'], ['ci']], ['security', ['sensitive:ci'], ['ci']], { sensitive: ['ci'], boundary: [], contract: [], ci: ['ci'] }]);
|
|
38
|
+
check('151 production lines flag the size mark and 150 do not; neither raises a lens, and test rows never count as production', [
|
|
39
|
+
esc([row('src/a.mjs', 100, 51)]).size_flag, esc([row('src/a.mjs', 100, 50)]).size_flag, esc([row('src/a.mjs', 10), row('tests/a.test.mjs', 500, 0)]).size_flag, diff([row('src/a.mjs', 5, 3), row('tests/a.test.mjs', 500, 9)]).facts.production_lines,
|
|
40
|
+
], [true, false, false, 8]);
|
|
41
|
+
const weak = (rows) => esc(rows).tests_weakened;
|
|
42
|
+
check('tests_weakened: a moved test (delete plus add) is not, a deleted test file with nothing added is, a modified one losing 10 lines is not', [
|
|
43
|
+
weak([row('tests/a.test.mjs', 0, 40, 'D'), row('tests/b.test.mjs', 40, 0, 'A')]), weak([row('tests/a.test.mjs', 0, 40, 'D')]), weak([row('tests/a.test.mjs', 0, 10, 'D')]), weak([row('tests/a.test.mjs', 0, 10, 'M')]),
|
|
44
|
+
], [false, true, true, false]);
|
|
45
|
+
check('test rows are counted apart: files changed, lines added and deleted, files deleted', (({ facts: f }) => [f.test_files_changed, f.test_lines_added, f.test_lines_deleted, f.test_files_deleted, f.production_files])(diff([row('tests/a.test.mjs', 7, 2, 'D'), row('src/b.mjs', 3, 1, 'M'), row('lib/c_test.go', 1, 1, 'M')])), [2, 8, 3, 1, 1]);
|
|
46
|
+
const tops = (...r) => diff(r).facts.new_top_dirs;
|
|
47
|
+
check('a top directory is new only when every row under it is an add; a root file is none; modules count distinct module keys', [
|
|
48
|
+
tops(row('a/x', 1, 0, 'A'), row('a/y', 1, 0, 'A')), tops(row('a/x', 1, 0, 'A'), row('a/y')), tops(row('README.md', 1, 0, 'A')), tops(row('a/x', 1, 0, 'A'), row('b/x', 1, 0, 'A')),
|
|
49
|
+
diff([row('a/x'), row('a/y'), row('packages/p/z'), row('packages/q/z'), row('README.md')]).facts.modules,
|
|
50
|
+
], [1, 0, 0, 2, 4]);
|
|
51
|
+
check('planning churn under .somi is ignored and a denied name there still floors', [diff([row('.somi/plans/x/spec.md', 900)]).facts, diff([row('.somi/reviews/r.md', 900)]).facts, diff([row('.somi/x/.env')]).facts.denied, ids([row('.somi/plans/x.md')])[0]],
|
|
52
|
+
[diff([]).facts, diff([]).facts, true, null]);
|
|
53
|
+
const GUARDED = ['.Claude/settings.json', '.CLAUDE/hooks/x', '.somi/Config.json', '.SOMI/config.json', '.claude', '.somi', '.claude/plugins/somi/x', '.claude\\settings.json', '.claude/a/b/c/d', '.claude./x', '.somi/config.json.', '.claude\uff0fsettings.json', '\uff0e\uff43laude/x',
|
|
54
|
+
'.claude\uff3csettings.json', '.claude\ufe68x', 'packages/app/.claude/settings.json', 'examples/x/.claude/hooks/h', 'a/.claude', '.somi/rules/99-overrides.md', '.SOMI/Rules/x', 'AGENTS.md', 'docs/CLAUDE.md', 'CLAUDE.local.md', 'docs/Claude.Local.md', 'a/agents.md', 'a/AGENTS.md.', 'a\\Claude.MD',
|
|
55
|
+
'.mcp.json', 'packages/a/.mcp.json', '.vscode/mcp.json', '.MCP.JSON', '.vscode/MCP.json', 'a\\.mcp.json.', 'packages/a/.vscode\\mcp.json', '.mcp\uff0ejson'];
|
|
56
|
+
check('the guard raises sensitive config on every row, hidden or not: any case, either separator, bare names, any depth, no plugins exemption', GUARDED.map((f) => ids([row(f)]).slice(0, 2)), GUARDED.map(() => ['security', ['sensitive:config']]));
|
|
57
|
+
// `mcp.json` without the dot is no host's project-level file, so it is quiet (a Cursor-style `.cursor/mcp.json` and plugin manifests are recorded residuals).
|
|
58
|
+
const QUIET = ['docs/agents-guide.md', '.somi/plans/x.md', 'docs/claude-md.txt', 'src/claude.mdx', 'src/claude.local.mdx', 'claude.local', '.somi/rules2/x', 'a/.claudes/x',
|
|
59
|
+
'mcp.json', 'src/mcp.json', '.mcp.json.bak', 'docs/mcp-notes.md', '.vscode/settings.json', '.vscode/x/mcp.json', 'vscode/mcp.json', '.vscode.bak/mcp.json', 'a.mcp.json'];
|
|
60
|
+
check('the guard is not wider than its names: a longer name, planning churn and a neighbouring directory raise nothing', QUIET.map((f) => ids([row(f)])[0]), QUIET.map(() => null));
|
|
61
|
+
check('the guard raises on a row among ordinary ones, and a guarded row is also classified when it is not an exact ignored prefix', [ids([row('src/a.mjs'), row('.Somi')])[1], diff([row('.Claude/evil.mjs', 9)]).facts.production_lines], [['sensitive:config'], 9]);
|
|
62
|
+
const late = Array.from({ length: 25 }, (_, i) => row(`src/m${i % 3}/f${i}.mjs`)); late[10] = row('.env'); late[21] = row('.circleci/c.yml'); late[24] = row('tests/t.test.mjs', 0, 9, 'D');
|
|
63
|
+
check('rows past the first chunk are read: a denied name, a ci row and a deleted test after row 10 all count', (({ facts: f }) => [f.production_files, f.test_files_deleted, f.denied, f.classes.ci])(diff(late)), [24, 1, true, ['ci']]);
|
|
64
|
+
check('an ignored prefix is exact: .somi2/ and a name with a backslash are classified like any other', [diff([row('.somi2/a.mjs', 9)]).facts.production_lines, diff([row('.claude\\evil.mjs', 9)]).facts.production_lines, ids([row('.somi2/a.mjs')])[0]], [9, 9, null]);
|
|
65
|
+
|
|
66
|
+
console.log('== escalation facts: config, plan inputs and what is returned ==');
|
|
67
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'escalation-facts-')); process.on('exit', () => fs.rmSync(tmp, { recursive: true, force: true }));
|
|
68
|
+
fs.mkdirSync(path.join(tmp, '.somi')); fs.writeFileSync(path.join(tmp, '.somi', 'config.json'), JSON.stringify({ sizing: { sensitive_paths: [] } })); fs.writeFileSync(path.join(tmp, 'global.json'), JSON.stringify({ sizing: { sensitive_paths: ['zed'] } }));
|
|
69
|
+
const loaded = loadConfig(tmp, { SOMI_GLOBAL_CONFIG: path.join(tmp, 'global.json') });
|
|
70
|
+
check('through the real loadConfig, a project list of [] keeps the global glob; the merged .config is refused (it would erase the glob) and raises config on its own; config cannot remove ci', [
|
|
71
|
+
diff([row('zed/x.mjs')], { config: loaded }).facts.classes.sensitive, diff([row('zed/x.mjs')], { config: loaded.config }).facts.classes.sensitive, diff([row('.circleci/c.yml')], { config: loaded }).facts.classes.ci,
|
|
72
|
+
], [['config'], ['config'], ['ci']]);
|
|
73
|
+
const REFUSED = { global: { config: { sizing: { sensitive_paths: ['*.'] } } }, project: { config: {} } };
|
|
74
|
+
const cfgOnly = (rows, config) => { const d = diff(rows, { config }); return [d.notes, d.facts.classes.sensitive]; };
|
|
75
|
+
check('a refused sensitive_paths key is noted, adds sensitive config, and does so with no row, or only an ignored row, reaching the classifier', [
|
|
76
|
+
cfgOnly([row('a/x')], REFUSED), cfgOnly([], REFUSED), cfgOnly([row('.somi/plans/x.md')], REFUSED), cfgOnly([row('a/x')], loaded), cfgOnly([row('a/x')]),
|
|
77
|
+
], [[['config_refused'], ['config']], [['config_refused'], ['config']], [['config_refused'], ['config']], [[], []], [[], []]]);
|
|
78
|
+
const sizing = (list) => ({ global: { config: { sizing: { sensitive_paths: list } } }, project: { config: {} } });
|
|
79
|
+
const globs = (n) => Array.from({ length: n }, (_, i) => `zz${i}`);
|
|
80
|
+
check('a glob list with a hole or past the cap is refused and raises config; a list at the cap is read', [cfgOnly([row('a/x')], sizing(['zz0', , 'zz2'])), cfgOnly([row('a/x')], sizing(globs(33))), cfgOnly([row('a/x')], sizing(globs(32)))],
|
|
81
|
+
[[['config_refused'], ['config']], [['config_refused'], ['config']], [[], []]]);
|
|
82
|
+
check('only undefined or the loadConfig shape is read: a merged .config, a layer list, one layer, null and a shape without its config are noted, raise sensitive config, and only the built-in lists apply', [
|
|
83
|
+
loaded.config, [loaded.global.config, loaded.project.config], loaded.global.config, null, { global: {}, project: {} }, { global: { config: {} }, project: { config: [] } }, 'x',
|
|
84
|
+
].map((config) => cfgOnly([row('zed/x.mjs')], config)), Array(7).fill([['config_refused'], ['config']]));
|
|
85
|
+
check('a refused config shape raises sensitive config with no row at all', [diff([], { config: loaded.config }).notes, ids([], { config: loaded.config })], [['config_refused'], ['security', ['sensitive:config'], []]]);
|
|
86
|
+
// A getter that answers differently on a later read: the layers are read once, so the first answer holds for every chunk.
|
|
87
|
+
let reads = 0;
|
|
88
|
+
const flipTop = { get global() { return reads++ === 0 ? { config: { sizing: { sensitive_paths: ['zed'] } } } : { config: {} }; }, project: { config: {} } };
|
|
89
|
+
const flipDeep = { global: { config: { sizing: { get sensitive_paths() { return reads++ === 0 ? ['zed'] : []; } } } }, project: { config: {} } };
|
|
90
|
+
const once25 = Array.from({ length: 25 }, (_, i) => row(i === 24 ? 'zed/x.mjs' : `src/m${i}/f.mjs`));
|
|
91
|
+
reads = 0; const topSeen = diff(once25, { config: flipTop }).facts.classes.sensitive; const topReads = reads;
|
|
92
|
+
reads = 0; const deepSeen = diff(once25, { config: flipDeep }).facts.classes.sensitive;
|
|
93
|
+
check('the config layers are read once: a getter that flips after its first read, at the top or in a list, cannot change the layers for a later chunk, and a top-level accessor is read one time', [topSeen, topReads, deepSeen], [['config'], 1, ['config']]);
|
|
94
|
+
const plan = (o) => { const d = diff([], o); return [d.facts.plan_target, d.facts.plan_paths, d.facts.slug_given, d.facts.work_item_paths, d.source]; };
|
|
95
|
+
check('plan inputs: a plan directory, a brief and an ADR path name a plan target, other paths and nothing do not, and a bad target raises', [
|
|
96
|
+
['.somi/plans/s/', 'x/brief.md', 'docs/adr/0001-x.md', 'docs\\decisions\\a.md'].map((target) => plan({ target })[0]), ['src/a.mjs', undefined, ''].map((target) => plan({ target })[0]), plan({ target: 5 })[0], plan({ target: 'a'.repeat(300) })[0],
|
|
97
|
+
], [[true, true, true, true], [false, false, false], true, true]);
|
|
98
|
+
check('plan and sdlc sources: paths and slug are named, empty lists are nothing, a bad value raises', [plan({ planPaths: ['p'], slug: 's' }), plan({ workItemPaths: ['w'], planPaths: [], target: '.somi/plans/s' }), plan({ planPaths: 5 })[1]],
|
|
99
|
+
[[false, true, true, false, { plan: ['paths'], sdlc: ['slug'] }], [true, false, false, true, { plan: ['target'], sdlc: ['paths'] }], true]);
|
|
100
|
+
const FILES = ['zzsecret-token.mjs', 'qédir/kk.pem', 'src/auth/zzlogin.mjs', 'zzpkg/package.json'];
|
|
101
|
+
const serial = JSON.stringify(diff(FILES.map((f) => row(f)), { slug: 'zzslug-name', target: 'zzplans/brief.md' }));
|
|
102
|
+
check('the result carries no input path, no slug and no target, and is pure ASCII', [FILES.filter((f) => serial.includes(f)), serial.includes('zzslug'), serial.includes('zzplans'), /^[\x20-\x7e]*$/.test(serial)], [[], false, false, true]);
|
|
103
|
+
check('every result is a grammar escalation() reads: none comes back as facts_unreadable', [[row('src/a.mjs')], [row('.env')], [row('"x"')], [], [row('t/a.test.js', 0, 30, 'D')], [row('docs/adr-0001.md')], [row('.claude/settings.json')], [null]].filter((r) => esc(r, { slug: 's' }).reasons.some((x) => ['facts_unreadable', 'internal_error'].includes(x))).length, 0);
|
|
104
|
+
|
|
105
|
+
console.log('== escalation facts: hostile and degraded input ==');
|
|
106
|
+
const raising = (rows, options) => { const d = diff(rows, options); return [d.threw === true, esc(rows, options).review_min, d.notes]; };
|
|
107
|
+
check('a path over the length cap, a control character, a bad count and a bad status are each handled: a raising result for the unusable ones, a note, no throw', [
|
|
108
|
+
raising([row('a/'.repeat(121))]), raising([row('e\u0301'.repeat(130))]), raising([row('.e\u200cnv')]), raising([row('src/a.mjs', -1)]), raising([row('src/a.mjs', '5')]), raising([row('src/a.mjs', 1, 0, 'AM')]), raising([null]), raising([{ file: 5, added: 1, deleted: 0, status: 'M' }]),
|
|
109
|
+
], Array(8).fill([false, 'security', ['row_unusable']]));
|
|
110
|
+
// U+FDFA is 18 characters once folded: 14 of them are 14 raw characters and 252 folded, over the cap. Three of them sit in three chunks of one module.
|
|
111
|
+
const GROWN = '\ufdfa'.repeat(14); const grown = Array.from({ length: 30 }, (_, i) => row(i % 10 === 0 ? GROWN : `src/a/f${i}.mjs`));
|
|
112
|
+
check('a name that only passes the length cap once folded is an unusable row in any chunk: three of them in three chunks floor and seat architecture', [diff(grown).notes, escalation(diff(grown).facts).seats['somi-architecture-reviewer'].seat], [['row_unusable'], true]);
|
|
113
|
+
const UNPLAIN = ['../x', './a.mjs', 'a//b', 'a/./b', 'a/../b', '/a', 'a/', 'a/.. /b', '\uff0e\uff0e/x', 'a\\..\\b', 'a\uff0f/b'];
|
|
114
|
+
check('a name with an empty, dot or dot-dot segment, or a leading ./, is an unusable row', UNPLAIN.map((f) => raising([row(f)])), UNPLAIN.map(() => [false, 'security', ['row_unusable']]));
|
|
115
|
+
const HUGE = Number.MAX_SAFE_INTEGER;
|
|
116
|
+
check('a summed count past the safe integers is the floor with rows_unusable, never a count that wrapped', [
|
|
117
|
+
[row('src/a.mjs', HUGE, 1)], [row('tests/a.test.mjs', HUGE, 0), row('tests/b.test.mjs', 1, 0)], [row('tests/a.test.mjs', 0, HUGE, 'D'), row('tests/b.test.mjs', 0, 1, 'D')],
|
|
118
|
+
].map((r) => [raising(r), diff(r).facts.production_lines]), Array(3).fill([[false, 'security', ['rows_unusable']], 1e9]));
|
|
119
|
+
const started = Date.now(); const many = raising(Array(10000).fill(row('src/a.mjs')));
|
|
120
|
+
check('10,000 rows, a non-list and MAX_ROWS + 1 rows are the raising result with the rows_unusable note, quickly; MAX_ROWS rows are read', [many, raising('x'), raising(Array(MAX_ROWS + 1).fill(row('a.mjs'))), raising(Array(MAX_ROWS).fill(row('a.mjs')))[2], Date.now() - started < 2000],
|
|
121
|
+
[[false, 'security', ['rows_unusable']], [false, 'security', ['rows_unusable']], [false, 'security', ['rows_unusable']], [], true]);
|
|
122
|
+
const timed = diff([row('src/a.mjs'), row('.env')], { budgetMs: 0 });
|
|
123
|
+
// A fake clock that the config getter moves 10 s while the rows are being prepared: the box counts that time.
|
|
124
|
+
const slowPrep = () => { const real = Date.now; let t = 0; Date.now = () => t; try { return diff([row('src/a.mjs')], { config: { get global() { t += 10000; return { config: {} }; }, project: { config: {} } } }).notes; } finally { Date.now = real; } };
|
|
125
|
+
check('the time box starts before the config and rows are prepared: preparation that outruns the budget floors', slowPrep(), ['time_box']);
|
|
126
|
+
check('the clock is read once whatever the kept count: a budget of 0 floors when every row is ignored, and with no row at all', [diff([row('.somi/plans/x.md')], { budgetMs: 0 }).notes, diff([], { budgetMs: 0 }).notes], [['time_box'], ['time_box']]);
|
|
127
|
+
check('a time box that runs out returns the floor, never the partial facts; a budget that is not a finite number is no time box', [timed.notes, escalation(timed.facts).seats['somi-architecture-reviewer'].seat, [null, 'x', NaN].map((budgetMs) => diff([row('src/a.mjs')], { budgetMs }).notes)], [['time_box'], true, [[], [], []]]);
|
|
128
|
+
const FULL = [row('src/auth/a.mjs', 900), row('src/routes/r.mjs'), row('db/migrations/1.sql'), row('package-lock.json'), row('openapi.yaml'), row('.github/w.yml'), row('src/new/x.mjs', 5, 0, 'A'), row('tests/t.test.mjs', 0, 80, 'D')];
|
|
129
|
+
const OPT = { slug: 's', target: '.somi/plans/s', planPaths: ['p'], workItemPaths: ['w'] }; const sup = (a, b) => b.every((x) => a.includes(x));
|
|
130
|
+
// A second full read: no test file at all, a new top directory and production lines past the untested mark, which FULL does not hold.
|
|
131
|
+
const NO_TEST = [row('src/new/x.mjs', 70, 0, 'A')];
|
|
132
|
+
const covers = (hi, full) => sup(hi.reasons, full.reasons) && sup(hi.hard_surface, full.hard_surface) && (!full.tests_weakened || hi.tests_weakened) && (!full.size_flag || hi.size_flag) && hi.review_min === 'security' && Object.keys(full.seats).every((l) => sup(hi.seats[l].reasons, full.seats[l].reasons));
|
|
133
|
+
const DEGRADED = [['time_box', FULL, { budgetMs: 0 }], ['rows_unusable', Array(MAX_ROWS + 1).fill(FULL[0]), {}], ['row_unusable', [...FULL, null], {}], ['internal_error', [...FULL, { get file() { throw new Error('x'); } }], {}]];
|
|
134
|
+
const READS = [FULL, NO_TEST].map((rows) => esc(rows, OPT));
|
|
135
|
+
check('every degraded result covers a full read of a diff holding every class, a deleted test and a lockfile, and of a diff with no test and a new top directory: every seat, reason, hard-surface id and flag', DEGRADED.map(([, rows, o]) => { const d = diff(rows, { ...OPT, ...o }); return [d.notes[0], READS.map((full) => covers(escalation(d.facts), full))]; }), DEGRADED.map(([n]) => [n, [true, true]]));
|
|
136
|
+
const broken = diff([row('src/a.mjs')], { get config() { throw new Error('boom'); } });
|
|
137
|
+
check('an unexpected error is the floor with its own note, every plan seat kept, and never a throw', [broken.notes, escalation(broken.facts).review_min, diff([], { get slug() { throw new Error('boom'); } }).facts.plan_target], [['internal_error'], 'security', true]);
|
|
138
|
+
|
|
139
|
+
console.log(`SUMMARY ${pass + fail} ${fail}`);
|
|
140
|
+
process.exit(fail ? 1 : 0);
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Tests of scripts/lib/escalation.mjs. Risk: a floor that goes DOWN (a class dropped from the raise, an edge moved, a
|
|
3
|
+
// fact added that removes a seat) or an unreadable input that reads as quiet. Pure numbers and names, no mocks.
|
|
4
|
+
// Usage: node escalation-tests.mjs <module path>; tests/scripts/escalation.sh runs it on the module and on scratch
|
|
5
|
+
// mutants of it, and each mutant must turn the test named there red. Hermetic: no model, no network.
|
|
6
|
+
//
|
|
7
|
+
// Monotonicity domain (finite, no random generator), asserted as the loop's own count so a shrunk domain turns the suite red:
|
|
8
|
+
// eight boolean facts, ordered false < true: a sensitive class name, a boundary class name, a contract class name, a ci
|
|
9
|
+
// class name, a denied name, a plan target, a slug given, a deleted test file; crossed with production_lines {0, 150, 151},
|
|
10
|
+
// production_files {0, 5, 6}, modules {0, 2, 3}, new_top_dirs {0, 1} and net test lines {+30, 0, -19, -20} (lower is more
|
|
11
|
+
// alarming). 2^8 x 3 x 3 x 3 x 2 x 4 = 55,296 evaluations. Moving one fact one step up must never turn off a seat, a seat
|
|
12
|
+
// reason, a reason, review_min, a hard-surface id or size_flag. Net test lines are the ordered fact, not their sum (the
|
|
13
|
+
// large-test-change seat reads the sum, out of range here). Outside it: more test lines added alone (`tests_weakened` reads
|
|
14
|
+
// net lines, so padding tests switches it off) and a test file changed (drops `untested_production`); that one stays 0 here.
|
|
15
|
+
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
18
|
+
import { pathToFileURL } from 'node:url';
|
|
19
|
+
|
|
20
|
+
const M = await import(pathToFileURL(path.resolve(process.argv[2])).href);
|
|
21
|
+
const { escalation, HARD_SURFACE_IDS, SEAT_REASONS, CLASS_NAMES, REFUSED_REASON, INTERNAL_REASON } = M;
|
|
22
|
+
|
|
23
|
+
let pass = 0; let fail = 0;
|
|
24
|
+
const clip = (v) => JSON.stringify(v).slice(0, 160);
|
|
25
|
+
const check = (name, got, want) => {
|
|
26
|
+
if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${clip(want)}, got ${clip(got)})`); }
|
|
27
|
+
};
|
|
28
|
+
const LENSES = Object.keys(SEAT_REASONS);
|
|
29
|
+
const facts = (o = {}, classes = {}) => ({
|
|
30
|
+
production_lines: 0, production_files: 0, test_lines_added: 0, test_lines_deleted: 0, test_files_deleted: 0, test_files_changed: 0,
|
|
31
|
+
modules: 0, new_top_dirs: 0, denied: false, plan_target: false, plan_paths: false, slug_given: false, work_item_paths: false,
|
|
32
|
+
...o, classes: { sensitive: [], boundary: [], contract: [], ci: [], ...classes },
|
|
33
|
+
});
|
|
34
|
+
const run = (o, classes) => { try { return escalation(facts(o, classes)); } catch { return { threw: true }; } };
|
|
35
|
+
const seated = (r) => LENSES.filter((l) => r.seats?.[l]?.seat);
|
|
36
|
+
|
|
37
|
+
console.log('== escalation: edges ==');
|
|
38
|
+
check('an empty fact set seats only the reviewer, raises nothing and flags nothing', (({ review_min, reasons, tests_weakened, size_flag, hard_surface, seats }) => [review_min, reasons, tests_weakened, size_flag, hard_surface, seats['somi-reviewer'], seated({ seats })])(run()),
|
|
39
|
+
[null, [], false, false, [], { seat: true, reasons: ['always'] }, ['somi-reviewer']]);
|
|
40
|
+
check('size_flag at the line and file edges, and it raises nothing', [150, 151].map((n) => run({ production_lines: n, test_files_changed: 1 })).concat([5, 6].map((n) => run({ production_files: n }))).map((r) => [r.size_flag, r.review_min, seated(r).length]),
|
|
41
|
+
[[false, null, 1], [true, null, 1], [false, null, 1], [true, null, 1]]);
|
|
42
|
+
const weak = (added, deleted, gone) => run({ test_lines_added: added, test_lines_deleted: deleted, test_files_deleted: gone }).tests_weakened;
|
|
43
|
+
check('tests_weakened at net -19 and -20, with and without a deleted test file', [weak(0, 19, 0), weak(0, 20, 0), weak(0, 19, 1), weak(0, 1, 1), weak(5, 25, 0), weak(5, 24, 0)], [false, true, true, true, true, false]);
|
|
44
|
+
check('a moved test (a delete plus an add of the same lines) does not weaken tests, and a deletion with nothing added does', [weak(40, 40, 1), weak(0, 40, 1)], [false, true]);
|
|
45
|
+
check('tests_weakened raises security and seats the test strategist', (({ review_min, reasons, seats }) => [review_min, reasons, seats['somi-test-strategist']])(run({ test_lines_deleted: 20 })),
|
|
46
|
+
['security', ['tests_weakened'], { seat: true, reasons: ['tests_weakened'] }]);
|
|
47
|
+
check('modules at 2 and 3, and one new top directory, seat the architecture lens', [run({ modules: 2 }), run({ modules: 3 }), run({ new_top_dirs: 1 })].map((r) => r.seats['somi-architecture-reviewer'].reasons), [[], ['modules'], ['new_top_dirs']]);
|
|
48
|
+
check('the test strategist: a large test change at 99 and 100, 60 production lines with and without a changed test', [
|
|
49
|
+
run({ test_lines_added: 99 }), run({ test_lines_added: 60, test_lines_deleted: 40 }), run({ production_lines: 59 }), run({ production_lines: 60 }), run({ production_lines: 60, test_files_changed: 1 }),
|
|
50
|
+
].map((r) => r.seats['somi-test-strategist'].reasons), [[], ['large_test_change'], [], ['untested_production'], []]);
|
|
51
|
+
check('the plan and sdlc lenses follow their flags', [run({ plan_target: true }), run({ plan_paths: true }), run({ slug_given: true }), run({ work_item_paths: true })].map((r) => seated(r).slice(1)),
|
|
52
|
+
[['somi-plan-reviewer'], ['somi-plan-reviewer'], ['somi-sdlc-reviewer'], ['somi-sdlc-reviewer']]);
|
|
53
|
+
|
|
54
|
+
console.log('== escalation: classes and hard surface ==');
|
|
55
|
+
const each = (cls, rest = {}) => CLASS_NAMES[cls].map((n) => run(rest, { [cls]: [n] }));
|
|
56
|
+
check('every sensitive class name raises security with its reason', each('sensitive').map((r) => [r.review_min, r.reasons]).filter(([, rs]) => rs[0] !== 'deny_list'),
|
|
57
|
+
CLASS_NAMES.sensitive.filter((n) => n !== 'deny_list').map((n) => ['security', [`sensitive:${n}`]]));
|
|
58
|
+
check('every boundary class name raises security with its reason', each('boundary').map((r) => [r.review_min, r.reasons]).filter(([, rs]) => rs[0] !== 'deny_list'),
|
|
59
|
+
CLASS_NAMES.boundary.filter((n) => n !== 'deny_list').map((n) => ['security', [`boundary:${n}`]]));
|
|
60
|
+
check('a contract or ci class name raises no lens, and a contract name seats architecture', [...each('contract'), ...each('ci')].map((r) => [r.review_min, seated(r).length]), [...CLASS_NAMES.contract.map(() => [null, 2]), [null, 1]]);
|
|
61
|
+
check('a denied flag, or the deny_list class name, raises security as one deny_list reason', [run({ denied: true }), run({}, { sensitive: ['deny_list'], boundary: ['deny_list'] })].map((r) => [r.review_min, r.reasons, r.hard_surface]), [['security', ['deny_list'], ['deny_list']], ['security', ['deny_list'], ['deny_list']]]);
|
|
62
|
+
check('hard-surface ids: manifest, lockfile and schema from contract names, migration from migrations, ci from a ci name or the sensitive ci name, deny_list from denied', [
|
|
63
|
+
...CLASS_NAMES.contract.map((n) => run({}, { contract: [n] }).hard_surface), run({}, { sensitive: ['migrations'] }).hard_surface, run({}, { ci: ['ci'] }).hard_surface, run({}, { sensitive: ['ci'] }).hard_surface, run({ denied: true }).hard_surface,
|
|
64
|
+
], [['lockfile'], ['manifest'], ['schema'], ['migration'], ['ci'], ['ci'], ['deny_list']]);
|
|
65
|
+
check('hard-surface ids are sorted, unique and drawn from the closed set', run({ denied: true }, { contract: ['schema', 'schema', 'lockfile'], sensitive: ['migrations', 'ci'], ci: ['ci'] }).hard_surface, ['ci', 'deny_list', 'lockfile', 'migration', 'schema']);
|
|
66
|
+
check('the raising classes and reasons name security in the one security lens', (({ seats }) => seats['somi-security-reviewer'])(run({ denied: true, test_lines_deleted: 30 }, { boundary: ['routes', 'routes'] })),
|
|
67
|
+
{ seat: true, reasons: ['boundary:routes', 'deny_list', 'tests_weakened'] });
|
|
68
|
+
|
|
69
|
+
console.log('== escalation: refused input ==');
|
|
70
|
+
const good = facts();
|
|
71
|
+
const accessor = { ...good }; Object.defineProperty(accessor, 'modules', { get: () => 0, enumerable: true });
|
|
72
|
+
const badClass = (k, v) => ({ ...good, classes: { ...good.classes, [k]: v } });
|
|
73
|
+
const hole = []; hole.length = 1;
|
|
74
|
+
const proxy = new Proxy(good, { ownKeys() { throw new Error('trap'); } });
|
|
75
|
+
const REFUSALS = {
|
|
76
|
+
'an unknown key': { ...good, extra: 1 }, 'a missing key': (({ modules, ...r }) => r)(good), 'a string for a count': { ...good, modules: '3' }, 'a negative count': { ...good, modules: -1 },
|
|
77
|
+
'a fractional count': { ...good, modules: 1.5 }, 'an unsafe integer': { ...good, modules: 2 ** 60 }, 'infinity': { ...good, production_lines: Infinity }, 'a number for a flag': { ...good, denied: 1 },
|
|
78
|
+
'an accessor': accessor, 'an array': [], 'null': null, 'a string': 'facts', 'undefined': undefined, 'a class instance': Object.assign(new (class X {})(), good),
|
|
79
|
+
'an unknown class name': badClass('sensitive', ['/etc/passwd']), 'an unknown class key': { ...good, classes: { ...good.classes, extra: [] } }, 'a missing class key': { ...good, classes: { sensitive: [] } },
|
|
80
|
+
'a class list that is not an array': badClass('boundary', 'routes'), 'a sparse class list': badClass('boundary', hole), 'an over-long class list': badClass('boundary', Array(17).fill('data')), 'a throwing proxy': proxy,
|
|
81
|
+
};
|
|
82
|
+
check('refused input returns the raising result and never throws', Object.fromEntries(Object.entries(REFUSALS).map(([k, v]) => [k, (() => { try { const r = escalation(v); return [r.review_min, r.reasons]; } catch { return 'threw'; } })()])),
|
|
83
|
+
Object.fromEntries(Object.keys(REFUSALS).map((k) => [k, ['security', [REFUSED_REASON]]])));
|
|
84
|
+
check('the refused result seats every lens, flags size and carries every hard-surface id', (({ seats, size_flag, tests_weakened, hard_surface }) => [seated({ seats }), size_flag, tests_weakened, hard_surface])(escalation(null)), [LENSES, true, false, [...HARD_SURFACE_IDS]]);
|
|
85
|
+
// Array.prototype.filter is called by the rules and not by the input reader, so a throwing one is a bug in the rules, not bad input.
|
|
86
|
+
// `reached` counts the calls: when the rules stop calling it, the next check says so instead of failing on its values.
|
|
87
|
+
let reached = 0;
|
|
88
|
+
const whileBroken = (fn) => { const keep = Array.prototype.filter; Array.prototype.filter = () => { reached++; throw new Error('bug'); }; try { return fn(); } finally { Array.prototype.filter = keep; } };
|
|
89
|
+
const broken = whileBroken(() => { try { return escalation(facts()); } catch { return { threw: true }; } });
|
|
90
|
+
check('the internal-error test breaks the rules where it means to: Array.prototype.filter is reached (if not, patch whichever method the rules call now)', reached > 0, true);
|
|
91
|
+
check('an unexpected error in the rules is the raising result under its own reason id, not the unreadable-input one; bad input keeps its id', [
|
|
92
|
+
broken.threw ?? [broken.review_min, broken.reasons, broken.hard_surface, seated(broken), LENSES.map((l) => broken.seats[l].reasons)], escalation(null).reasons, INTERNAL_REASON !== REFUSED_REASON,
|
|
93
|
+
], [['security', [INTERNAL_REASON], [...HARD_SURFACE_IDS], LENSES, LENSES.map(() => [INTERNAL_REASON])], [REFUSED_REASON], true]);
|
|
94
|
+
check('a plain object with a null prototype and a frozen input are read', [escalation(Object.assign(Object.create(null), facts())).review_min, escalation(Object.freeze(facts())).review_min], [null, null]);
|
|
95
|
+
|
|
96
|
+
console.log('== escalation: output ==');
|
|
97
|
+
const sample = [run(), run({ denied: true, test_lines_deleted: 40, modules: 3 }, { sensitive: ['auth'], contract: ['manifest'] }), escalation(null)];
|
|
98
|
+
check('the output is deterministic, pure ASCII and has the same keys always', [escalation(facts()), JSON.stringify(sample).length > 0 && /^[\x20-\x7e]*$/.test(JSON.stringify(sample)), sample.map((r) => Object.keys(r).join())],
|
|
99
|
+
[run(), true, sample.map(() => 'review_min,reasons,tests_weakened,size_flag,hard_surface,seats')]);
|
|
100
|
+
const SHAPE = ['always', 'facts_unreadable', 'internal_error', 'review_min', ...Object.values(SEAT_REASONS).flat(), 'security'];
|
|
101
|
+
const strings = (v) => (typeof v === 'string' ? [v] : v && typeof v === 'object' ? Object.entries(v).flatMap(([k, x]) => [...(Array.isArray(v) ? [] : [k]), ...strings(x)]) : []);
|
|
102
|
+
const ids = new Set(strings(sample).concat(strings(run({ denied: true }, { sensitive: ['auth'], boundary: ['data'], contract: ['schema'] }))));
|
|
103
|
+
const known = new Set([...SHAPE, 'seat', 'reasons', 'tests_weakened', 'size_flag', 'hard_surface', 'seats', ...LENSES, ...HARD_SURFACE_IDS, ...CLASS_NAMES.sensitive.map((n) => `sensitive:${n}`), ...CLASS_NAMES.boundary.map((n) => `boundary:${n}`), ...CLASS_NAMES.contract.map((n) => `contract:${n}`)]);
|
|
104
|
+
check('a result holds ids, booleans and counts only: every string is a fixed id and no input name is echoed', [[...ids].filter((s) => !known.has(s)), JSON.stringify(escalation({ ...good, '/home/u/secret.pem': 1 }))], [[], JSON.stringify(escalation(null))]);
|
|
105
|
+
const ALL = run({ denied: true, test_lines_deleted: 100, production_lines: 60, new_top_dirs: 1, modules: 3, plan_target: true, plan_paths: true, slug_given: true, work_item_paths: true },
|
|
106
|
+
{ sensitive: [...CLASS_NAMES.sensitive], boundary: [...CLASS_NAMES.boundary], contract: [...CLASS_NAMES.contract], ci: ['ci'] });
|
|
107
|
+
check('the registries and constants are frozen and, with every fact on, a lens emits exactly the reason ids its registry lists', [
|
|
108
|
+
Object.isFrozen(HARD_SURFACE_IDS), Object.isFrozen(SEAT_REASONS), Object.isFrozen(SEAT_REASONS['somi-reviewer']), Object.isFrozen(CLASS_NAMES.sensitive),
|
|
109
|
+
LENSES.map((l) => [...new Set(ALL.seats[l].reasons.map((id) => id.split(':')[0]))].sort()),
|
|
110
|
+
], [true, true, true, true, LENSES.map((l) => [...SEAT_REASONS[l]].sort())]);
|
|
111
|
+
|
|
112
|
+
console.log('== escalation: exhaustive monotonicity ==');
|
|
113
|
+
// escalation.sh sets SKIP_DOMAIN=mutant-run for the scratch mutants that do not name one of these checks. Only that exact value skips.
|
|
114
|
+
if (process.env.SKIP_DOMAIN === 'mutant-run') console.log(' skip the exhaustive monotonicity checks (SKIP_DOMAIN=mutant-run)');
|
|
115
|
+
else {
|
|
116
|
+
// Each flag fact is [fact overrides, class overrides] when set.
|
|
117
|
+
const FLAG_FACTS = [
|
|
118
|
+
[{}, { sensitive: ['auth'] }], [{}, { boundary: ['routes'] }], [{}, { contract: ['manifest'] }], [{}, { ci: ['ci'] }],
|
|
119
|
+
[{ denied: true }, {}], [{ plan_target: true }, {}], [{ slug_given: true }, {}], [{ test_files_deleted: 1 }, {}],
|
|
120
|
+
];
|
|
121
|
+
const AXES = [[0, 150, 151], [0, 5, 6], [0, 2, 3], [0, 1], [30, 0, -19, -20]];
|
|
122
|
+
const point = (bits, ax) => {
|
|
123
|
+
const net = AXES[4][ax[4]];
|
|
124
|
+
const o = { production_lines: AXES[0][ax[0]], production_files: AXES[1][ax[1]], modules: AXES[2][ax[2]], new_top_dirs: AXES[3][ax[3]], test_lines_added: Math.max(net, 0), test_lines_deleted: Math.max(-net, 0) };
|
|
125
|
+
const classes = {};
|
|
126
|
+
FLAG_FACTS.forEach(([over, cls], i) => { if (bits >> i & 1) { Object.assign(o, over); Object.assign(classes, cls); } });
|
|
127
|
+
return facts(o, classes);
|
|
128
|
+
};
|
|
129
|
+
const SIZES = AXES.map((a) => a.length);
|
|
130
|
+
const results = new Map(); let evaluations = 0;
|
|
131
|
+
for (let bits = 0; bits < 256; bits++) for (let a = 0; a < SIZES[0]; a++) for (let b = 0; b < SIZES[1]; b++) for (let c = 0; c < SIZES[2]; c++) for (let d = 0; d < SIZES[3]; d++) for (let e = 0; e < SIZES[4]; e++) {
|
|
132
|
+
results.set([bits, a, b, c, d, e].join(), escalation(point(bits, [a, b, c, d, e]))); evaluations++;
|
|
133
|
+
}
|
|
134
|
+
// Every decision a result makes, as strings: `lo` is covered by `hi` when its set is inside hi's. The reason ids count too,
|
|
135
|
+
// except against the refused result, whose one reason is its own.
|
|
136
|
+
const decisions = (r, reasons) => new Set([...(r.review_min ? ['review_min'] : []), ...(r.size_flag ? ['size_flag'] : []), ...r.hard_surface.map((h) => `hard:${h}`),
|
|
137
|
+
...LENSES.flatMap((l) => [...(r.seats[l].seat ? [l] : []), ...(reasons ? r.seats[l].reasons.map((x) => `${l}/${x}`) : [])]), ...(reasons ? r.reasons : [])]);
|
|
138
|
+
const inside = (lo, hi) => { for (const x of lo) if (!hi.has(x)) return false; return true; };
|
|
139
|
+
const full = new Map([...results].map(([k, r]) => [k, decisions(r, true)]));
|
|
140
|
+
let edges = 0; const broken = [];
|
|
141
|
+
for (const key of results.keys()) {
|
|
142
|
+
const [bits, ...ax] = key.split(',').map(Number);
|
|
143
|
+
const ups = [...FLAG_FACTS.map((_, i) => (bits >> i & 1 ? null : [bits | 1 << i, ...ax])), ...ax.map((v, i) => (v + 1 < SIZES[i] ? [bits, ...ax.map((x, j) => (j === i ? x + 1 : x))] : null))];
|
|
144
|
+
for (const up of ups.filter(Boolean)) { edges++; if (!inside(full.get(key), full.get(up.join()))) broken.push(`${key} -> ${up.join()}`); }
|
|
145
|
+
}
|
|
146
|
+
// Flag edges 8 x 128 x 216, ordinal edges 110,592 + 27,648 + 41,472.
|
|
147
|
+
check('the monotonicity domain has 55,296 evaluations and 400,896 one-step edges', [evaluations, results.size, edges], [55296, 55296, 400896]);
|
|
148
|
+
check('a fact moved one step up never turns off a seat, a seat reason, a reason, review_min, a hard-surface id or size_flag', broken.slice(0, 3), []);
|
|
149
|
+
check('review_min is null or security over the whole domain, and a quiet point exists', [[...new Set([...results.values()].map((r) => r.review_min))].sort(), results.get('0,0,0,0,0,0').review_min], [[null, 'security'], null]);
|
|
150
|
+
check('the refused result dominates every result in the domain', (() => { const top = decisions(escalation(null)); return [...results.values()].filter((r) => !inside(decisions(r), top)).length; })(), 0);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
console.log(`SUMMARY ${pass + fail} ${fail}`);
|
|
154
|
+
process.exit(fail ? 1 : 0);
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// In-process tests of scripts/lib/findings-ledger.mjs: locus identity, the consecutive-pass breaker, the
|
|
3
|
+
// no-write guarantee on bad input and on an empty batch, the resolve/reopen/open/get lifecycle, and that the
|
|
4
|
+
// library never reads the process environment.
|
|
5
|
+
// Invoked from tests/scripts/loop-engine.sh. The CLI's bytes are pinned by tests/scripts/run.sh and its goldens.
|
|
6
|
+
|
|
7
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { tmpdir } from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
12
|
+
import { getFinding, ledgerPaths, normalizeTitle, openFindings, recordFindings, reopenFinding, resolveFinding } from '../../../scripts/lib/findings-ledger.mjs';
|
|
13
|
+
|
|
14
|
+
const LIB = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'scripts', 'lib');
|
|
15
|
+
let pass = 0; let fail = 0;
|
|
16
|
+
// Strict deep equality: undefined, null and a missing key are three different answers.
|
|
17
|
+
const check = (name, got, want) => {
|
|
18
|
+
if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const root = mkdtempSync(path.join(tmpdir(), 'findings-ledger-'));
|
|
22
|
+
const decoy = mkdtempSync(path.join(tmpdir(), 'findings-decoy-'));
|
|
23
|
+
const now = () => '2026-01-01';
|
|
24
|
+
const rec = (slug, input, extra = {}) => recordFindings({ root, slug, review: 'r.md', run: 'R1', pass: 1, input, now, ...extra });
|
|
25
|
+
const ledgerOf = (slug) => JSON.parse(readFileSync(ledgerPaths(root, slug).file, 'utf8'));
|
|
26
|
+
const F = { file: 'src/a.txt', symbol: 'HandleWebhook', title: 'Missing rate limit on retry path', severity: 'Major', confidence: 'High' };
|
|
27
|
+
|
|
28
|
+
console.log('== findings ledger: the environment is not an input ==');
|
|
29
|
+
const envBefore = JSON.stringify(process.env);
|
|
30
|
+
process.env.CLAUDE_PROJECT_DIR = decoy;
|
|
31
|
+
process.env.SOMI_LOOP_STATE_DIR = decoy;
|
|
32
|
+
const sentinel = rec('sentinel', [F]);
|
|
33
|
+
check('a CLAUDE_PROJECT_DIR in process.env does not redirect the ledger away from the root it was given', [sentinel.code, existsSync(ledgerPaths(root, 'sentinel').file), existsSync(path.join(decoy, '.somi'))], [0, true, false]);
|
|
34
|
+
delete process.env.CLAUDE_PROJECT_DIR;
|
|
35
|
+
delete process.env.SOMI_LOOP_STATE_DIR;
|
|
36
|
+
const source = readFileSync(path.join(LIB, 'findings-ledger.mjs'), 'utf8');
|
|
37
|
+
const code = source.split('\n').filter((l) => !l.trimStart().startsWith('//')).join('\n');
|
|
38
|
+
// Any use of `process` or `globalThis` in code (comments excluded) is a way to the environment: `process.env`,
|
|
39
|
+
// `process['env']`, `const { env } = process`, `globalThis.process.env`. The library needs none of them.
|
|
40
|
+
check('findings-ledger.mjs names neither process nor globalThis outside comments', /\b(process|globalThis)\b/.test(code), false);
|
|
41
|
+
|
|
42
|
+
console.log('== findings ledger: normalizeTitle ==');
|
|
43
|
+
const titles = [['', ''], ['Bug', 'bug'], ['one two three four five six seven eight nine ten', 'one two three four five six seven eight'], [' Missing rate limit ', 'missing rate limit'], ['Missing rate limit', 'missing rate limit'], ['Missing rate-limit! (on retry) path?', 'missing rate limit on retry path']];
|
|
44
|
+
for (const [t, want] of titles) check(`normalizeTitle(${JSON.stringify(t)})`, normalizeTitle(t), want);
|
|
45
|
+
check('İstanbul lowercases byte-wise (ASCII only): the dotted capital is dropped, not turned into an "i"', normalizeTitle('İstanbul'), 'stanbul');
|
|
46
|
+
check('café loses its accented letter instead of keeping it', normalizeTitle('café'), 'caf');
|
|
47
|
+
|
|
48
|
+
console.log('== findings ledger: locus identity ==');
|
|
49
|
+
const first = rec('id', [F]);
|
|
50
|
+
check('a first sighting is new F-1 and prints one JSON line', first, { lines: [JSON.stringify({ id: 'F-1', state: 'new', recurring_consecutive: false, recurring_cross_run: false })], code: 0, message: '' });
|
|
51
|
+
check('the stored finding has the documented shape', ledgerOf('id'), { next_id: 2, findings: [{ id: 'F-1', key: 'src/a.txt|handlewebhook|missing rate limit on retry path', locus: { file: 'src/a.txt', symbol: 'HandleWebhook' }, title: F.title, severity: 'Major', confidence: 'High', status: 'open', introduced_by: 'r.md', resolved_by: null, seen: [{ review: 'r.md', run: 'R1', pass: 1, date: '2026-01-01' }] }] });
|
|
52
|
+
const variant = rec('id', [{ file: 'src/a.txt', symbol: 'handlewebhook', title: 'MISSING rate-limit on retry path!' }], { pass: 3 });
|
|
53
|
+
check('the same locus in another case and punctuation is the same finding (known, not new)', JSON.parse(variant.lines[0]).id + JSON.parse(variant.lines[0]).state, 'F-1known');
|
|
54
|
+
const other = rec('id', [{ file: 'src/b.txt', title: 'Other' }]);
|
|
55
|
+
check('a different file is a new finding with the next id and the defaults', [JSON.parse(other.lines[0]).id, ledgerOf('id').findings[1].severity, ledgerOf('id').findings[1].confidence, ledgerOf('id').findings[1].locus.symbol], ['F-2', 'Minor', 'Medium', '']);
|
|
56
|
+
|
|
57
|
+
console.log('== findings ledger: the consecutive-pass breaker ==');
|
|
58
|
+
const p1 = rec('brk', [F], { pass: 1 });
|
|
59
|
+
const p2 = rec('brk', [F], { pass: 2 });
|
|
60
|
+
check('pass 1 then pass 2 of the same run is a consecutive recurrence: code 5', [p1.code, p2.code, JSON.parse(p2.lines[0]).recurring_consecutive, JSON.parse(p2.lines[0]).recurring_cross_run], [0, 5, true, false]);
|
|
61
|
+
const g1 = rec('gap', [F], { pass: 1 });
|
|
62
|
+
const g3 = rec('gap', [F], { pass: 3 });
|
|
63
|
+
check('pass 1 then pass 3 is not consecutive and not cross-run: code 0', [g1.code, g3.code, JSON.parse(g3.lines[0]).recurring_consecutive, JSON.parse(g3.lines[0]).recurring_cross_run], [0, 0, false, false]);
|
|
64
|
+
const x2 = rec('gap', [F], { run: 'R2', pass: 4 });
|
|
65
|
+
check('another run seeing an open finding is cross-run, not consecutive: code 0', [x2.code, JSON.parse(x2.lines[0]).recurring_consecutive, JSON.parse(x2.lines[0]).recurring_cross_run], [0, false, true]);
|
|
66
|
+
const batch = rec('batch', [F, { file: 'src/c.txt', title: 'Fresh' }], { pass: 1 });
|
|
67
|
+
const batch2 = rec('batch', [{ file: 'src/c.txt', title: 'Fresh' }, F], { pass: 2 });
|
|
68
|
+
check('the breaker is judged after every finding is processed: every line comes back, in input order, then code 5', [batch.code, batch2.lines.map((l) => JSON.parse(l).id), batch2.code], [0, ['F-2', 'F-1'], 5]);
|
|
69
|
+
const empty = rec('empty', []);
|
|
70
|
+
check('an empty batch prints nothing and exits 0', empty, { lines: [], code: 0, message: '' });
|
|
71
|
+
|
|
72
|
+
console.log('== findings ledger: bad input writes nothing ==');
|
|
73
|
+
const missing = rec('bad1', [{ file: 'src/a.txt' }]);
|
|
74
|
+
check('a finding with no title returns 64 and the exact stderr line, with no stdout', missing, { lines: [], code: 64, message: 'somi-findings: finding 0 needs at least {file, title}' });
|
|
75
|
+
check('and the ledger was not even created', existsSync(ledgerPaths(root, 'bad1').dir), false);
|
|
76
|
+
const later = rec('bad2', [F, { title: 'no file' }]);
|
|
77
|
+
check('a bad element after a good one is named by index and the good one is not recorded either', [later.code, later.message, existsSync(ledgerPaths(root, 'bad2').file)], [64, 'somi-findings: finding 1 needs at least {file, title}', false]);
|
|
78
|
+
check('a null element is malformed, not a crash', rec('bad3', [null]).code, 64);
|
|
79
|
+
const before = readFileSync(ledgerPaths(root, 'id').file, 'utf8');
|
|
80
|
+
rec('id', [F, { file: 'x' }]);
|
|
81
|
+
check('a refused batch leaves an existing ledger byte for byte as it was', readFileSync(ledgerPaths(root, 'id').file, 'utf8'), before);
|
|
82
|
+
|
|
83
|
+
console.log('== findings ledger: an empty batch leaves the ledger as it is ==');
|
|
84
|
+
const seed = '{"next_id": 1, "findings": []}\n';
|
|
85
|
+
check('record [] on a fresh slug leaves the seed literal, not the pretty form', readFileSync(ledgerPaths(root, 'empty').file, 'utf8'), seed);
|
|
86
|
+
const handMade = ledgerPaths(root, 'hand');
|
|
87
|
+
mkdirSync(handMade.dir, { recursive: true });
|
|
88
|
+
const handBytes = '{"next_id":7,"findings":[]}';
|
|
89
|
+
writeFileSync(handMade.file, handBytes);
|
|
90
|
+
rec('hand', []);
|
|
91
|
+
check('record [] on an existing ledger does not rewrite it', readFileSync(handMade.file, 'utf8'), handBytes);
|
|
92
|
+
|
|
93
|
+
console.log('== findings ledger: resolve, reopen, open, get ==');
|
|
94
|
+
const life = { root, slug: 'life' };
|
|
95
|
+
rec('life', [F, { file: 'src/b.txt', symbol: 'S', title: 'Second' }]);
|
|
96
|
+
check('resolve prints id, status and resolved_by', resolveFinding({ ...life, id: 'F-1', status: 'fixed', by: 'r2.md' }), { lines: [JSON.stringify({ id: 'F-1', status: 'fixed', resolved_by: 'r2.md' })], code: 0, message: '' });
|
|
97
|
+
check('and the ledger holds the new state', [ledgerOf('life').findings[0].status, ledgerOf('life').findings[0].resolved_by], ['fixed', 'r2.md']);
|
|
98
|
+
check('open lists only the open findings, with exactly these fields in this order', openFindings(life), { lines: [JSON.stringify([{ id: 'F-2', locus: { file: 'src/b.txt', symbol: 'S' }, title: 'Second', severity: 'Minor', confidence: 'Medium', introduced_by: 'r.md' }], null, 2)], code: 0, message: '' });
|
|
99
|
+
check('the open finding keys come out in the documented order', Object.keys(JSON.parse(openFindings(life).lines[0])[0]), ['id', 'locus', 'title', 'severity', 'confidence', 'introduced_by']);
|
|
100
|
+
check('get prints the whole stored finding, pretty', getFinding({ ...life, id: 'F-1' }), { lines: [JSON.stringify(ledgerOf('life').findings[0], null, 2)], code: 0, message: '' });
|
|
101
|
+
check('reopen prints id and status', reopenFinding({ ...life, id: 'F-1', by: 'r3.md' }), { lines: [JSON.stringify({ id: 'F-1', status: 'open' })], code: 0, message: '' });
|
|
102
|
+
check('and clears resolved_by and records reopened_by', [ledgerOf('life').findings[0].status, ledgerOf('life').findings[0].resolved_by, ledgerOf('life').findings[0].reopened_by], ['open', null, 'r3.md']);
|
|
103
|
+
const lifeBytes = readFileSync(ledgerPaths(root, 'life').file, 'utf8');
|
|
104
|
+
check('resolve of an unknown id prints nothing, exits 0 and writes nothing', [resolveFinding({ ...life, id: 'F-99', status: 'fixed', by: 'x' }), readFileSync(ledgerPaths(root, 'life').file, 'utf8')], [{ lines: [], code: 0, message: '' }, lifeBytes]);
|
|
105
|
+
check('reopen of an unknown id prints nothing and exits 0', reopenFinding({ ...life, id: 'F-99', by: 'x' }), { lines: [], code: 0, message: '' });
|
|
106
|
+
check('get of an unknown id prints nothing and exits 0', getFinding({ ...life, id: 'F-99' }), { lines: [], code: 0, message: '' });
|
|
107
|
+
check('resolve without an id or a status is refused with 64', [resolveFinding({ ...life, status: 'fixed' }), resolveFinding({ ...life, id: 'F-1' })], [{ lines: [], code: 64, message: 'somi-findings: resolve requires --id and --status' }, { lines: [], code: 64, message: 'somi-findings: resolve requires --id and --status' }]);
|
|
108
|
+
check('resolve with an unknown status is refused with 64 and writes nothing', [resolveFinding({ ...life, id: 'F-1', status: 'closed', by: 'x' }), readFileSync(ledgerPaths(root, 'life').file, 'utf8')], [{ lines: [], code: 64, message: 'somi-findings: --status must be fixed|accepted|wontfix' }, lifeBytes]);
|
|
109
|
+
check('reopen and get without an id are refused with 64', [reopenFinding({ ...life }).message, getFinding({ ...life }).message], ['somi-findings: reopen requires --id', 'somi-findings: get requires --id']);
|
|
110
|
+
check('open on a slug with no ledger seeds it and prints an empty array', [openFindings({ root, slug: 'fresh' }), readFileSync(ledgerPaths(root, 'fresh').file, 'utf8')], [{ lines: ['[]'], code: 0, message: '' }, seed]);
|
|
111
|
+
check('a refused lifecycle call still seeds the ledger, as the bash original did', [getFinding({ root, slug: 'refused' }).code, readFileSync(ledgerPaths(root, 'refused').file, 'utf8')], [64, seed]);
|
|
112
|
+
|
|
113
|
+
check('none of the calls touched process.env', JSON.stringify(process.env), envBefore);
|
|
114
|
+
|
|
115
|
+
rmSync(root, { recursive: true, force: true });
|
|
116
|
+
rmSync(decoy, { recursive: true, force: true });
|
|
117
|
+
console.log(`findings ledger tests: ${pass} ok, ${fail} failed`);
|
|
118
|
+
process.exit(fail === 0 ? 0 : 1);
|