@skathio/somi 4.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/.claude/settings.json +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.copilot-extension/extension.json +1 -1
  5. package/.copilot-extension/marketplace.json +1 -1
  6. package/README.md +11 -5
  7. package/VERSION +1 -1
  8. package/agents/somi-coder.md +4 -228
  9. package/agents/somi-designer.md +4 -160
  10. package/agents/somi-discovery-analyst.md +4 -276
  11. package/agents/somi-flow.md +47 -0
  12. package/agents/somi-general.md +36 -0
  13. package/agents/somi-planner.md +4 -341
  14. package/agents/somi-reviewer.md +4 -199
  15. package/agents/somi.md +81 -253
  16. package/commands/adopt.md +6 -84
  17. package/commands/architecture-review.md +11 -86
  18. package/commands/atlas.md +10 -25
  19. package/commands/code-loop.md +10 -221
  20. package/commands/code-parallel.md +10 -151
  21. package/commands/code.md +9 -157
  22. package/commands/debug.md +9 -131
  23. package/commands/design.md +9 -160
  24. package/commands/discover.md +9 -194
  25. package/commands/impact.md +9 -25
  26. package/commands/incident.md +9 -39
  27. package/commands/plan-loop.md +9 -181
  28. package/commands/plan.md +9 -244
  29. package/commands/pr.md +10 -25
  30. package/commands/refactor-design.md +11 -89
  31. package/commands/refactor.md +11 -50
  32. package/commands/release-readiness.md +11 -70
  33. package/commands/review-panel.md +10 -141
  34. package/commands/review.md +11 -181
  35. package/commands/security-review.md +11 -75
  36. package/commands/ship-loop.md +9 -260
  37. package/commands/ship.md +9 -115
  38. package/commands/somi-config.md +12 -124
  39. package/commands/test-strategy.md +11 -75
  40. package/commands/upgrade.md +9 -72
  41. package/hooks/hooks.json +1 -1
  42. package/hooks/lib/common.mjs +15 -13
  43. package/hooks/pre-tool/block-dangerous-bash.mjs +1 -1
  44. package/hooks/pre-tool/block-secret-writes.mjs +5 -7
  45. package/hooks/pre-tool/guard-cost-lowering.mjs +26 -11
  46. package/hooks/pre-tool/guard-protected-paths.mjs +54 -34
  47. package/hooks/session-start/ensure-default-config.mjs +34 -42
  48. package/package.json +1 -1
  49. package/scripts/lib/config-files.mjs +145 -0
  50. package/scripts/lib/cost-ceiling.mjs +29 -22
  51. package/scripts/lib/cost-defaults.mjs +2 -0
  52. package/scripts/lib/escalation-facts.mjs +146 -0
  53. package/scripts/lib/escalation.mjs +129 -0
  54. package/scripts/lib/findings-ledger.mjs +241 -0
  55. package/scripts/lib/install-text.mjs +97 -0
  56. package/scripts/lib/loop-caps.mjs +140 -0
  57. package/scripts/lib/loop-diff.mjs +12 -70
  58. package/scripts/lib/loop-engine.mjs +226 -0
  59. package/scripts/lib/loop-escalate.mjs +49 -0
  60. package/scripts/lib/loop-exit.mjs +47 -0
  61. package/scripts/lib/loop-notes-compact.mjs +72 -0
  62. package/scripts/lib/loop-notes.mjs +278 -0
  63. package/scripts/lib/loop-review.mjs +355 -12
  64. package/scripts/lib/loop-state.mjs +44 -0
  65. package/scripts/lib/loop-step-close.mjs +75 -0
  66. package/scripts/lib/loop-step-kit.mjs +179 -0
  67. package/scripts/lib/loop-step-review.mjs +140 -0
  68. package/scripts/lib/loop-step-tool.mjs +89 -0
  69. package/scripts/lib/loop-step.mjs +301 -0
  70. package/scripts/lib/mcp-project-root.mjs +18 -7
  71. package/scripts/lib/path-facts.mjs +187 -0
  72. package/scripts/lib/path-safety.mjs +171 -0
  73. package/scripts/lib/run-card.mjs +73 -0
  74. package/scripts/size-budget-overrides.json +5 -13
  75. package/scripts/somi-card.mjs +39 -0
  76. package/scripts/somi-check.mjs +4 -3
  77. package/scripts/somi-config.mjs +113 -50
  78. package/scripts/somi-findings.mjs +56 -271
  79. package/scripts/somi-loop.mjs +77 -446
  80. package/scripts/somi-mcp.mjs +27 -96
  81. package/scripts/validate.sh +92 -54
  82. package/skills/flow-adopt/SKILL.md +92 -0
  83. package/skills/flow-architecture-review/SKILL.md +94 -0
  84. package/skills/flow-atlas/SKILL.md +34 -0
  85. package/skills/flow-code/SKILL.md +167 -0
  86. package/skills/flow-code-loop/SKILL.md +263 -0
  87. package/skills/flow-code-parallel/SKILL.md +160 -0
  88. package/skills/flow-debug/SKILL.md +141 -0
  89. package/skills/flow-design/SKILL.md +170 -0
  90. package/skills/flow-discover/SKILL.md +204 -0
  91. package/skills/flow-impact/SKILL.md +35 -0
  92. package/skills/flow-incident/SKILL.md +49 -0
  93. package/skills/flow-plan/SKILL.md +254 -0
  94. package/skills/flow-plan-loop/SKILL.md +254 -0
  95. package/skills/flow-pr/SKILL.md +34 -0
  96. package/skills/flow-refactor/SKILL.md +58 -0
  97. package/skills/flow-refactor-design/SKILL.md +97 -0
  98. package/skills/flow-release-readiness/SKILL.md +82 -0
  99. package/skills/flow-review/SKILL.md +193 -0
  100. package/skills/flow-review-panel/SKILL.md +154 -0
  101. package/skills/flow-security-review/SKILL.md +83 -0
  102. package/skills/flow-ship/SKILL.md +125 -0
  103. package/skills/flow-ship-loop/SKILL.md +274 -0
  104. package/skills/flow-somi-config/SKILL.md +142 -0
  105. package/skills/flow-status/SKILL.md +43 -0
  106. package/skills/flow-test-strategy/SKILL.md +83 -0
  107. package/skills/flow-upgrade/SKILL.md +82 -0
  108. package/skills/role-coder/SKILL.md +247 -0
  109. package/skills/role-designer/SKILL.md +172 -0
  110. package/skills/role-discovery-analyst/SKILL.md +288 -0
  111. package/skills/role-planner/SKILL.md +353 -0
  112. package/skills/role-reviewer/SKILL.md +218 -0
  113. package/skills/somi-checkpoint/SKILL.md +95 -0
  114. package/skills/somi-dispatch/SKILL.md +14 -14
  115. package/skills/somi-routing/SKILL.md +6 -2
  116. package/tests/hooks/cases/block-secret-writes.json +6 -1
  117. package/tests/hooks/cases/guard-protected-paths.json +44 -2
  118. package/tests/hooks/run.sh +21 -0
  119. package/tests/scripts/checkpoint-gate.sh +2 -2
  120. package/tests/scripts/cost-defaults.sh +2 -0
  121. package/tests/scripts/cost-hardcap.sh +26 -17
  122. package/tests/scripts/dispatch-line-gate.sh +4 -4
  123. package/tests/scripts/dispatch-reference-gate.sh +14 -14
  124. package/tests/scripts/ensure-default-config.sh +4 -4
  125. package/tests/scripts/escalation.sh +409 -0
  126. package/tests/scripts/eval-runner.sh +8 -7
  127. package/tests/scripts/fact-sheet.sh +296 -0
  128. package/tests/scripts/global-config.sh +167 -0
  129. package/tests/scripts/goldens/somi-loop.json +2 -2
  130. package/tests/scripts/lib/dispatch-reference-gate.mjs +14 -5
  131. package/tests/scripts/lib/escalation-facts-tests.mjs +140 -0
  132. package/tests/scripts/lib/escalation-tests.mjs +154 -0
  133. package/tests/scripts/lib/findings-ledger-tests.mjs +118 -0
  134. package/tests/scripts/lib/loop-engine-tests.mjs +287 -0
  135. package/tests/scripts/lib/loop-escalate-tests.mjs +356 -0
  136. package/tests/scripts/lib/loop-flow-gate.mjs +173 -0
  137. package/tests/scripts/lib/loop-notes-tests.mjs +371 -0
  138. package/tests/scripts/lib/loop-step-cli-tests.mjs +141 -0
  139. package/tests/scripts/lib/loop-step-close-tests.mjs +351 -0
  140. package/tests/scripts/lib/loop-step-lenient-tests.mjs +114 -0
  141. package/tests/scripts/lib/loop-step-state-tests.mjs +127 -0
  142. package/tests/scripts/lib/loop-step-tests.mjs +499 -0
  143. package/tests/scripts/lib/loop-step-unwritten-tests.mjs +55 -0
  144. package/tests/scripts/lib/path-facts-tests.mjs +198 -0
  145. package/tests/scripts/lib/path-safety-tests.mjs +201 -0
  146. package/tests/scripts/lib/run-suites.mjs +139 -0
  147. package/tests/scripts/lib/site-roadmap-gate.mjs +64 -0
  148. package/tests/scripts/lib/sizing-score-tests.mjs +210 -0
  149. package/tests/scripts/lib/sizing-set-tests.mjs +131 -0
  150. package/tests/scripts/lib/somi-mcp-loop-tests.mjs +226 -0
  151. package/tests/scripts/lib/somi-mcp-tests.mjs +21 -1
  152. package/tests/scripts/loop-engine.sh +22 -0
  153. package/tests/scripts/loop-flow-gate.sh +11 -0
  154. package/tests/scripts/review-panel-seats.sh +4 -4
  155. package/tests/scripts/run-card.sh +57 -0
  156. package/tests/scripts/run-suites.sh +74 -0
  157. package/tests/scripts/run.sh +11 -0
  158. package/tests/scripts/site-roadmap-gate.sh +76 -0
  159. package/tests/scripts/size-tier.sh +3 -3
  160. package/tests/scripts/somi-agent-dispatch-contract.sh +23 -3
  161. package/tests/scripts/somi-config.sh +9 -4
  162. package/tests/scripts/somi-mcp.sh +1 -0
  163. package/tests/scripts/suite-plan.json +20 -0
@@ -0,0 +1,287 @@
1
+ #!/usr/bin/env node
2
+ // In-process tests of the loop engine libraries: scripts/lib/loop-caps.mjs, loop-exit.mjs, loop-state.mjs and
3
+ // loop-engine.mjs (the lifecycle, measuring and recording handlers).
4
+ // Invoked from tests/scripts/loop-engine.sh.
5
+
6
+ import { chmodSync, existsSync, linkSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs';
7
+ import { execFileSync } from 'node:child_process';
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 { applyCapOverride, configVal, firstDefined, resolveInitCap, reresolveCap, validateCap } from '../../../scripts/lib/loop-caps.mjs';
13
+ import { checkDiff, finish, init, pass as passPass, recordDispatch, recordPass, resume, reviewScope, runStart } from '../../../scripts/lib/loop-engine.mjs';
14
+ import { stateFile } from '../../../scripts/lib/loop-state.mjs';
15
+ import { measuredTree, treeNumstat } from '../../../scripts/lib/loop-review.mjs';
16
+ import { computeDiff } from '../../../scripts/lib/loop-diff.mjs';
17
+ import { LoopExit, ok, refuse, usageError } from '../../../scripts/lib/loop-exit.mjs';
18
+
19
+ const LIB = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'scripts', 'lib');
20
+ let pass = 0; let fail = 0;
21
+ // Strict deep equality: undefined, null and a missing key are three different answers (a refusal's `out` must be absent).
22
+ const check = (name, got, want) => {
23
+ if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
24
+ };
25
+ // What a call that should exit looks like: [class, code, message], or the string 'no throw'.
26
+ const exitOf = (fn) => {
27
+ try { fn(); } catch (e) { return [e instanceof LoopExit, e.code, e.message]; }
28
+ return 'no throw';
29
+ };
30
+
31
+ console.log('== loop caps: the environment is a parameter ==');
32
+ process.env.SOMI_CODE_LOOP_MAX_PASSES = '9';
33
+ process.env.SOMI_CODE_LOOP_DIFF_CAP = '999';
34
+ check('resolveInitCap({}) ignores process.env and gives the default 3', resolveInitCap({}, {}, 'code', 'max_passes', ''), 3);
35
+ check('resolveInitCap({}) ignores process.env for the diff cap too (default 400)', resolveInitCap({}, {}, 'code', 'diff_cap_lines', ''), 400);
36
+ check('the env it is handed is what counts', resolveInitCap({ SOMI_CODE_LOOP_MAX_PASSES: '5' }, {}, 'code', 'max_passes', ''), 5);
37
+ check('reresolveCap({}) ignores process.env: no override, the stored cap stands', reresolveCap({}, { loop: 'code', pass: 1, caps: { max_passes: 2 } }, 'max_passes', '', 'T'), { resolved: 2, override: null });
38
+ delete process.env.SOMI_CODE_LOOP_MAX_PASSES;
39
+ delete process.env.SOMI_CODE_LOOP_DIFF_CAP;
40
+ const sources = ['loop-caps.mjs', 'loop-exit.mjs', 'loop-state.mjs', 'loop-engine.mjs'].map((f) => [f, readFileSync(path.join(LIB, f), 'utf8')]);
41
+ for (const [f, src] of sources) {
42
+ const code = src.split('\n').filter((l) => !l.trimStart().startsWith('//')).join('\n');
43
+ check(`${f} has no process.env outside comments`, /process\s*(\.|\[)\s*['"]?env/.test(code), false);
44
+ }
45
+
46
+ console.log('== loop caps: precedence ==');
47
+ const cfg = { code_loop: { max_passes: 7 }, plan_loop: { max_passes: 6 } };
48
+ check('flag beats env, config and default', resolveInitCap({ SOMI_CODE_LOOP_MAX_PASSES: '5' }, cfg, 'code', 'max_passes', '2'), 2);
49
+ check('env beats config', resolveInitCap({ SOMI_CODE_LOOP_MAX_PASSES: '5' }, cfg, 'code', 'max_passes', ''), 5);
50
+ check('config beats the default', resolveInitCap({}, cfg, 'code', 'max_passes', ''), 7);
51
+ check('a plan loop reads its own env var and config section', [resolveInitCap({ SOMI_PLAN_LOOP_MAX_PASSES: '4' }, cfg, 'plan', 'max_passes', ''), resolveInitCap({}, cfg, 'plan', 'max_passes', '')], [4, 6]);
52
+ check('a plan loop has no diff cap, whatever is set', resolveInitCap({ SOMI_CODE_LOOP_DIFF_CAP: '50' }, {}, 'plan', 'diff_cap_lines', '80'), 0);
53
+ check('a numeric 0 counts as set (the gate off is explicit)', resolveInitCap({}, {}, 'code', 'diff_cap_lines', '0'), 0);
54
+ check('configVal walks keys and reads null as unset', [configVal(cfg, ['code_loop', 'max_passes']), configVal({ a: null }, ['a']), configVal({}, ['a', 'b'])], [7, undefined, undefined]);
55
+ check('firstDefined skips undefined, null and the empty string', firstDefined(undefined, null, '', 0, 3), 0);
56
+
57
+ console.log('== loop caps: malformed values are refused, not coerced ==');
58
+ for (const raw of ['1,000', 'unlimited', '-1', '1.5']) {
59
+ check(`validateCap(${JSON.stringify(raw)}) exits 64 with the label and the value`, exitOf(() => validateCap(raw, 'max_passes')), [true, 64, `somi-loop: max_passes: expected a non-negative integer, got "${raw}"`]);
60
+ }
61
+ check('validateCap accepts 0 and a plain integer', [validateCap('0', 'x'), validateCap(12, 'x')], [0, 12]);
62
+ check('a malformed env cap at init exits 64 naming the field', exitOf(() => resolveInitCap({ SOMI_CODE_LOOP_MAX_PASSES: 'unlimited' }, {}, 'code', 'max_passes', '')), [true, 64, 'somi-loop: max_passes: expected a non-negative integer, got "unlimited"']);
63
+ const st = (extra = {}) => ({ loop: 'code', pass: 2, caps: { max_passes: 3, diff_cap_lines: 400 }, ...extra });
64
+ check('a malformed flag on re-resolution names the flag', exitOf(() => reresolveCap({}, st(), 'max_passes', '1,000', 'T')), [true, 64, 'somi-loop: --max-passes: expected a non-negative integer, got "1,000"']);
65
+ check('a malformed env var on re-resolution names the variable', exitOf(() => reresolveCap({ SOMI_CODE_LOOP_DIFF_CAP: 'none' }, st(), 'diff_cap_lines', '', 'T')), [true, 64, 'somi-loop: SOMI_CODE_LOOP_DIFF_CAP: expected a non-negative integer, got "none"']);
66
+
67
+ console.log('== loop caps: re-resolution and the override entry ==');
68
+ const flagged = reresolveCap({ SOMI_CODE_LOOP_MAX_PASSES: '8' }, st(), 'max_passes', '5', '2026-01-01T00:00:00Z');
69
+ check('a flag beats the env var and records source cli with the caller-supplied time', flagged, { resolved: 5, override: { field: 'max_passes', from: 3, to: 5, source: 'cli', after_pass: 2, at: '2026-01-01T00:00:00Z' } });
70
+ check('an env var alone records source env', reresolveCap({ SOMI_CODE_LOOP_DIFF_CAP: '100' }, st(), 'diff_cap_lines', '', 'T').override.source, 'env');
71
+ check('an explicit value equal to the stored one is no override', reresolveCap({ SOMI_CODE_LOOP_MAX_PASSES: '3' }, st(), 'max_passes', '', 'T'), { resolved: 3, override: null });
72
+ check('a plan loop has no diff cap to re-resolve', reresolveCap({ SOMI_CODE_LOOP_DIFF_CAP: '100' }, st({ loop: 'plan' }), 'diff_cap_lines', '100', 'T'), { resolved: 0, override: null });
73
+ const live = st();
74
+ applyCapOverride(live, flagged.override);
75
+ applyCapOverride(live, { ...flagged.override, from: 5, to: 6 });
76
+ check('applyCapOverride sets the cap and appends to a lazily created trail', [live.caps.max_passes, live.cap_overrides.length, live.cap_overrides[0].to], [6, 2, 5]);
77
+ check('a state never overridden keeps its shape (no cap_overrides key)', 'cap_overrides' in st(), false);
78
+
79
+ console.log('== loop exit model ==');
80
+ const e = usageError('bad');
81
+ check('usageError is a LoopExit 64 with the program prefix', [e instanceof LoopExit, e instanceof Error, e.code, e.message], [true, true, 64, 'somi-loop: bad']);
82
+ check('ok carries the output and no message', ok({ a: 1 }), { out: { a: 1 }, code: 0, message: '' });
83
+ check('refuse carries no stdout by default', refuse(2, 'max-passes-exceeded'), { out: undefined, code: 2, message: 'max-passes-exceeded' });
84
+ check('refuse can carry stdout printed before the failure', refuse(3, 'over', { cap: 1 }), { out: { cap: 1 }, code: 3, message: 'over' });
85
+
86
+ console.log('== loop lifecycle: handlers return results, the environment is a parameter ==');
87
+ const root = mkdtempSync(path.join(tmpdir(), 'loop-engine-'));
88
+ const git = (...a) => execFileSync('git', ['-C', root, '-c', 'user.name=t', '-c', 'user.email=t@t', ...a], { encoding: 'utf8' }).trim();
89
+ git('init', '-q'); git('commit', '-q', '--allow-empty', '-m', 'base');
90
+ const stateDir = path.join(root, '.somi', 'somi-state', 'loop');
91
+ // SOMI_GLOBAL_CONFIG='' switches the developer's global config off, so no handler here reads outside the temp root.
92
+ const ctxFor = (env = {}) => ({ root, env: { SOMI_GLOBAL_CONFIG: '', ...env }, stateDir, now: () => '2026-01-01T00:00:00Z' });
93
+ const base = { slug: 's', loop: 'code', iteration: '', files: 'a.js b.js', force: false, status: '', maxPasses: '', diffCap: '', severity: '', maxMinutes: '' };
94
+ const envBefore = JSON.stringify(process.env);
95
+ process.env.SOMI_CODE_LOOP_MAX_PASSES = '9';
96
+ process.env.SOMI_CODE_LOOP_SEVERITY_FLOOR = 'Blocker';
97
+ const globalDir = mkdtempSync(path.join(tmpdir(), 'loop-global-')); // outside root, or it counts as untracked diff
98
+ const globalCfg = path.join(globalDir, 'config.json'); // a global config the process env points at; the handler's env must not follow it
99
+ writeFileSync(globalCfg, JSON.stringify({ code_loop: { max_passes: 7 } }));
100
+ const globalBefore = process.env.SOMI_GLOBAL_CONFIG;
101
+ process.env.SOMI_GLOBAL_CONFIG = globalCfg;
102
+ const sentinel = init(ctxFor(), { ...base, slug: 'sentinel' });
103
+ check('an in-process init ignores sentinels planted in process.env (caps, severity floor, global config)', [sentinel.code, sentinel.out.caps.max_passes, sentinel.out.caps.severity_floor], [0, 3, 'Major']);
104
+ delete process.env.SOMI_CODE_LOOP_MAX_PASSES;
105
+ delete process.env.SOMI_CODE_LOOP_SEVERITY_FLOOR;
106
+ if (globalBefore === undefined) delete process.env.SOMI_GLOBAL_CONFIG; else process.env.SOMI_GLOBAL_CONFIG = globalBefore;
107
+ check('a handler given a global-config path in its env does read it (the sentinel file is live)', init(ctxFor({ SOMI_GLOBAL_CONFIG: globalCfg }), { ...base, slug: 'g' }).out.caps.max_passes, 7);
108
+ const started = init(ctxFor({ SOMI_CODE_LOOP_MAX_PASSES: '2' }), base);
109
+ check('init succeeds with the golden output keys and the env-given cap', [started.code, started.message, Object.keys(started.out), started.out.caps], [0, '', ['baseline_sha', 'caps', 'state_file'], { max_passes: 2, diff_cap_lines: 400, severity_floor: 'Major' }]);
110
+ const sf = stateFile(stateDir, 's', '');
111
+ check('the state file holds the golden state shape, in order', Object.keys(JSON.parse(readFileSync(sf, 'utf8'))), ['slug', 'loop', 'iteration', 'baseline_sha', 'started', 'status', 'caps', 'iteration_files', 'pass', 'history', 'ignored_guarded']);
112
+ check('the init snapshot of the ignored files under the policy paths is empty and within its caps in a clean repository', JSON.parse(readFileSync(sf, 'utf8')).ignored_guarded, { over: false, files: {} });
113
+ const again = init(ctxFor(), base);
114
+ check('init over a running state is refused (64) with no stdout', [again.code, again.out, again.message], [64, undefined, `somi-loop: loop state already running at ${sf} — use 'resume' to continue it, or 'init --force' to discard`]);
115
+ passPass(ctxFor(), base);
116
+ const forced = init(ctxFor({ SOMI_CODE_LOOP_MAX_PASSES: '2' }), { ...base, force: true });
117
+ check('init --force discards a running state: success, and the pass counter is back to 0', [forced.code, JSON.parse(readFileSync(sf, 'utf8')).pass], [0, 0]);
118
+ mkdirSync(path.join(root, '.somi', 'plans', 'bo'), { recursive: true });
119
+ const briefOnly = init(ctxFor(), { ...base, slug: 'bo' });
120
+ check('a brief-only work item without a tier approval is refused (64) with no stdout', [briefOnly.code, briefOnly.out, briefOnly.message.startsWith('somi-loop: brief-only work item refused: ')], [64, undefined, true]);
121
+ check('pass 1 and 2 of a cap-2 loop succeed', [passPass(ctxFor({ SOMI_CODE_LOOP_MAX_PASSES: '2' }), base).out, passPass(ctxFor({ SOMI_CODE_LOOP_MAX_PASSES: '2' }), base).out], [{ pass: 1, max_passes: 2 }, { pass: 2, max_passes: 2 }]);
122
+ const third = passPass(ctxFor(), base);
123
+ check('pass 3 of a cap-2 loop comes back as code 2 with no stdout', [third.code, third.out, third.message], [2, undefined, 'max-passes-exceeded: pass 3 > cap 2']);
124
+ mkdirSync(path.join(root, '.somi', 'somi-state', 'run'), { recursive: true });
125
+ writeFileSync(path.join(root, '.somi', 'somi-state', 'run', 's.json'), JSON.stringify({ started: '2000-01-01T00:00:00Z', max_minutes: 5 }));
126
+ const late = passPass(ctxFor({ SOMI_CODE_LOOP_MAX_PASSES: '9' }), base);
127
+ check('pass over the run budget comes back as code 4 with no stdout', [late.code, late.out, late.message.startsWith('time-budget-exceeded: ')], [4, undefined, true]);
128
+ const planLoop = init(ctxFor(), { ...base, slug: 'p', loop: 'plan' });
129
+ check('a plan loop has no diff cap and no review_min', [planLoop.out.caps.diff_cap_lines, 'review_min' in planLoop.out], [0, false]);
130
+ const done = finish(ctxFor(), { ...base, status: 'approved' });
131
+ check('finish records the status, the cap raise from the env var, and the injected clock', [done.out, JSON.parse(readFileSync(sf, 'utf8')).finished], [{ status: 'approved', pass: 2, history: 0, cap_overrides: [{ field: 'max_passes', from: 2, to: 9, source: 'env', after_pass: 2, at: '2026-01-01T00:00:00Z' }] }, '2026-01-01T00:00:00Z']);
132
+ check('finish without --status is a usage error (64)', finish(ctxFor(), base).code, 64);
133
+ check('resume reads a missing state as 64', resume(ctxFor(), { ...base, slug: 'none' }).code, 64);
134
+ check('none of the lifecycle calls touched process.env', JSON.stringify(process.env), envBefore);
135
+
136
+ console.log('== loop measure and record: results carry their stdout and their code ==');
137
+ const mCtx = (env = {}) => ({ ...ctxFor(env), installRoot: path.join(LIB, '..', '..') });
138
+ const m = { ...base, slug: 'm', files: 'a.js', diffCap: '4' };
139
+ init(mCtx(), m);
140
+ writeFileSync(path.join(root, 'a.js'), '1\n2\n3\n');
141
+ writeFileSync(path.join(root, 'c.js'), '1\n2\n');
142
+ const over = checkDiff(mCtx(), m);
143
+ check('check-diff over the weighted cap returns code 3 with its JSON and the stderr line', [over.code, over.out, over.message], [3, { diff_lines: 5, weighted_lines: 7, cap: 4, out_of_scope: ['c.js'] }, 'diff-cap-exceeded: weighted 7 > cap 4 (out-of-scope counts double)']);
144
+ const raised = checkDiff(mCtx({ SOMI_CODE_LOOP_DIFF_CAP: '100' }), { ...m, diffCap: '' });
145
+ check('check-diff under a raised cap is code 0 with the same measurement', [raised.code, raised.out.weighted_lines, raised.out.cap], [0, 7, 100]);
146
+ const firstScope = reviewScope(mCtx(), m);
147
+ check('review-scope on pass 0 is the whole iteration', [firstScope.code, firstScope.out], [0, { scope: 'full', why: 'first-pass' }]);
148
+ check('review-scope honours the env setting and refuses a bad one (64)', [reviewScope(mCtx({ SOMI_CODE_LOOP_REVIEW_SCOPE: 'full' }), m).out.why, reviewScope(mCtx({ SOMI_CODE_LOOP_REVIEW_SCOPE: 'x' }), m).code], ['setting', 64]);
149
+ passPass(mCtx({ SOMI_CODE_LOOP_MAX_PASSES: '5' }), m);
150
+ const rec = recordPass(mCtx(), { ...m, verdict: 'needs-changes', blockers: '1', majors: '2' });
151
+ check('record-pass returns the history entry with the diff size and the reviewed tree', [rec.code, rec.out.pass, rec.out.verdict, rec.out.blockers, rec.out.majors, rec.out.diff_lines, typeof rec.out.tree], [0, 1, 'needs-changes', 1, 2, 5, 'string']);
152
+ check('record-pass without --verdict is a usage error (64)', recordPass(mCtx(), m).code, 64);
153
+ passPass(mCtx({ SOMI_CODE_LOOP_MAX_PASSES: '5' }), m);
154
+ writeFileSync(path.join(root, 'a.js'), '1\n2\n3\n4\n');
155
+ const delta = reviewScope(mCtx(), m);
156
+ check('review-scope on a middle pass is the delta since the reviewed tree', [delta.out.scope, delta.out.since_pass, delta.out.files], ['delta', 1, ['a.js']]);
157
+ const agent = recordDispatch(mCtx(), { ...m, agent: 'somi-coder' });
158
+ check('record-dispatch appends the resolver\'s answer for a known agent', [agent.code, agent.out.agent, agent.out.pass], [0, 'somi-coder', 2]);
159
+ const nobody = recordDispatch(mCtx(), { ...m, agent: 'no-such-agent' });
160
+ check('record-dispatch refuses an unknown agent with the resolver\'s code (65) and no stdout', [nobody.code, nobody.out, nobody.message.startsWith('somi-loop: ')], [65, undefined, true]);
161
+ check('record-dispatch without --agent is a usage error (64)', recordDispatch(mCtx(), m).code, 64);
162
+ check('run-start records the budget, keeps it on a repeat, and refuses a zero budget (64)', [runStart(mCtx(), { ...m, maxMinutes: '30' }).out.max_minutes, runStart(mCtx(), { ...m, maxMinutes: '45' }).out.resumed, runStart(mCtx(), { ...m, slug: 'z', maxMinutes: '0' }).code], [30, true, 64]);
163
+ check('none of the measure and record calls touched process.env', JSON.stringify(process.env), envBefore);
164
+ { // init creates the state directory only just before it saves, so a refused init leaves nothing behind
165
+ const bare = mkdtempSync(path.join(tmpdir(), 'loop-bare-'));
166
+ const bctx = { root: bare, env: { SOMI_GLOBAL_CONFIG: '' }, stateDir: path.join(bare, '.somi', 'somi-state', 'loop'), now: () => '2026-01-01T00:00:00Z' };
167
+ const refused = [init(bctx, { ...base, slug: 'x', severity: 'nope' }).code, init(bctx, { ...base, slug: 'x' }).code]; // a bad floor, then no HEAD to baseline on
168
+ check('a refused init (bad severity floor, unresolvable HEAD) exits 64 and creates no state directory', [refused, existsSync(path.join(bare, '.somi'))], [[64, 64], false]);
169
+ rmSync(bare, { recursive: true, force: true });
170
+ }
171
+ { // a repository the diff gate refuses is refused at init, before any coder pass; a plan loop has no diff gate
172
+ const sub = mkdtempSync(path.join(tmpdir(), 'loop-initsub-'));
173
+ const sg = (...a) => execFileSync('git', ['-C', sub, '-c', 'user.name=t', '-c', 'user.email=t@t', ...a], { encoding: 'utf8' });
174
+ sg('init', '-q'); sg('commit', '-q', '--allow-empty', '-m', 'base');
175
+ mkdirSync(path.join(sub, 'n')); execFileSync('git', ['-C', path.join(sub, 'n'), 'init', '-q']);
176
+ const sctx = { root: sub, env: { SOMI_GLOBAL_CONFIG: '' }, stateDir: path.join(sub, '.somi', 'somi-state', 'loop'), now: () => '2026-01-01T00:00:00Z' };
177
+ const code = init(sctx, { ...base, slug: 'x' });
178
+ check('init in a repository with a nested repository is refused (64), names it with the .gitignore remedy, and writes nothing',
179
+ [code.code, code.message.includes('does not support repositories with submodules (n/); if it is not a submodule, add it to .gitignore'), existsSync(path.join(sub, '.somi'))], [64, true, false]);
180
+ check('a plan loop is not refused for a nested repository', init(sctx, { ...base, slug: 'p', loop: 'plan' }).code, 0);
181
+ rmSync(sub, { recursive: true, force: true });
182
+ }
183
+ rmSync(root, { recursive: true, force: true });
184
+ rmSync(globalDir, { recursive: true, force: true });
185
+
186
+ console.log('== the snapshot tree is built from what is on disk, whatever the repository config says ==');
187
+ { // each case: a committed baseline, one change, and what the measurement says about it
188
+ const made = [];
189
+ const repo = () => { const r = mkdtempSync(path.join(tmpdir(), 'loop-snap-')); made.push(r); const g = (...a) => execFileSync('git', ['-C', r, '-c', 'user.name=t', '-c', 'user.email=t@t', ...a], { encoding: 'utf8' }).trim(); g('init', '-q'); return { r, g }; };
190
+ const put = (r, f, text, time) => { mkdirSync(path.dirname(path.join(r, f)), { recursive: true }); writeFileSync(path.join(r, f), text); if (time) utimesSync(path.join(r, f), time, time); };
191
+ const measure = (r, g) => treeNumstat(r, g('rev-parse', 'HEAD'), measuredTree(r));
192
+ const refused = (r) => { const [a, code, msg] = exitOf(() => measuredTree(r)); return [a, code, msg.startsWith('somi-loop: cannot measure the diff: ')]; };
193
+ const racy = repo(); put(racy.r, 'f', 'aaaa\n', 1700000000); racy.g('add', '.'); racy.g('commit', '-q', '-m', 'f');
194
+ utimesSync(path.join(racy.r, '.git', 'index'), 1700000000, 1700000000); put(racy.r, 'f', 'bbbb\n', 1700000000); // same size, same second as the index: git calls the entry racy
195
+ check('a same-size edit made in the second the index was written is counted (the throwaway index keeps the real index\'s times)', measure(racy.r, racy.g), [{ added: 1, deleted: 1, file: 'f' }]);
196
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1100); // git compares ctime to the second
197
+ utimesSync(path.join(racy.r, '.git', 'index'), 1800000000, 1800000000); racy.g('config', 'core.trustctime', 'false'); racy.g('config', 'core.checkStat', 'minimal'); racy.g('config', 'core.ignoreStat', 'true'); put(racy.r, 'f', 'cccc\n', 1700000000); // the old mtime put back by hand
198
+ check('a repository config that loosens the stat check does not hide a same-size edit that kept its old mtime', measure(racy.r, racy.g), [{ added: 1, deleted: 1, file: 'f' }]);
199
+ const hook = path.join(racy.r, 'hook.sh'); put(racy.r, 'hook.sh', `#!/bin/sh\ntouch ${path.join(racy.r, 'RAN')}\nprintf '\\0'\n`); chmodSync(hook, 0o755); racy.g('config', 'core.fsmonitor', hook);
200
+ check('a core.fsmonitor hook in the repository config does not run during the measurement', [measure(racy.r, racy.g).length, existsSync(path.join(racy.r, 'RAN'))], [2, false]);
201
+ const rep = repo(); rep.g('commit', '-q', '--allow-empty', '-m', '0'); put(rep.r, 'f', 'x\n'.repeat(4000)); rep.g('add', '.'); rep.g('commit', '-q', '-m', 'f'); put(rep.r, 'one', 'x\n');
202
+ rep.g('replace', rep.g('rev-parse', 'HEAD:f'), rep.g('hash-object', '-w', 'one'));
203
+ check('a git replace ref is refused with 64, so a substituted blob is never counted in place of the real one', refused(rep.r), [true, 64, true]);
204
+ check('and the diff itself ignores the replacement: the 4000 lines of the real blob, not the 1 of the substitute', treeNumstat(rep.r, rep.g('rev-parse', 'HEAD~1'), rep.g('rev-parse', 'HEAD'))[0].added, 4000);
205
+ const sp = repo(); put(sp.r, 'src/a', 'a\n'); put(sp.r, 'other/b', 'b\n'); sp.g('add', '.'); sp.g('commit', '-q', '-m', 'f'); sp.g('sparse-checkout', 'set', '--cone', 'src'); put(sp.r, 'src/a', 'a\nb\n');
206
+ check('a sparse checkout measures: files left out of the working tree are not an edit', [existsSync(path.join(sp.r, 'other')), measure(sp.r, sp.g)], [false, [{ added: 1, deleted: 0, file: 'src/a' }]]);
207
+ sp.g('sparse-checkout', 'disable'); sp.g('update-index', '--skip-worktree', 'src/a'); // a hidden flag on a file that is on disk
208
+ check('a skip-worktree file that is on disk refuses: its edit would be hidden', refused(sp.r), [true, 64, true]);
209
+ const wt = repo(); wt.g('commit', '-q', '--allow-empty', '-m', 'f'); wt.g('config', 'extensions.worktreeConfig', 'true'); put(wt.r, '.gitattributes', '*.js filter=x\n'); put(wt.r, 'f.js', 'x\n');
210
+ wt.g('config', '--worktree', 'filter.x.clean', `touch ${path.join(wt.r, 'RAN')}; cat`);
211
+ check('a clean filter in the worktree config is refused and does not run', [...refused(wt.r), existsSync(path.join(wt.r, 'RAN'))], [true, 64, true, false]);
212
+ const ign = repo(); put(ign.r, 'a', 'a\n'); ign.g('add', '.'); ign.g('commit', '-q', '-m', 'f'); put(ign.r, '.gitignore', '.somi\n'); put(ign.r, '.somi/n', 'x\n'.repeat(50)); put(ign.r, 'z', 'x\n');
213
+ check('a .gitignore that ignores .somi does not stop the measurement, and .somi stays out of it', measure(ign.r, ign.g).map((x) => x.file).sort(), ['.gitignore', 'z']);
214
+ const bin = repo(); bin.g('commit', '-q', '--allow-empty', '-m', 'f'); put(bin.r, 'b.bin', Buffer.alloc(4999));
215
+ check('a binary with no newline counts one line per 50 bytes (100), not one', measure(bin.r, bin.g), [{ added: 100, deleted: 0, file: 'b.bin' }]);
216
+ const wtr = repo(); put(wtr.r, 'f', 'a\n'); wtr.g('add', '.'); wtr.g('commit', '-q', '-m', 'f'); put(wtr.r, 'f', 'a\nb\nc\n');
217
+ const empty = mkdtempSync(path.join(tmpdir(), 'loop-snap-')); made.push(empty); wtr.g('config', 'core.worktree', empty);
218
+ check('a core.worktree that points elsewhere does not hide the real tree', measure(wtr.r, wtr.g), [{ added: 2, deleted: 0, file: 'f' }]);
219
+ const decoy = repo(); const head = wtr.g('rev-parse', 'HEAD'); process.env.GIT_DIR = path.join(decoy.r, '.git'); process.env.GIT_INDEX_FILE = path.join(decoy.r, 'nope'); process.env.GIT_OBJECT_DIRECTORY = empty; process.env.GIT_LITERAL_PATHSPECS = '1';
220
+ const viaEnv = treeNumstat(wtr.r, head, measuredTree(wtr.r)); delete process.env.GIT_DIR; delete process.env.GIT_INDEX_FILE; delete process.env.GIT_OBJECT_DIRECTORY; delete process.env.GIT_LITERAL_PATHSPECS;
221
+ check('a GIT_DIR, GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY and GIT_LITERAL_PATHSPECS in the caller\'s environment do not redirect the measurement', viaEnv, [{ added: 2, deleted: 0, file: 'f' }]);
222
+ const sm = repo(); sm.g('commit', '-q', '--allow-empty', '-m', 'f'); put(sm.r, 'n/a', 'x\n'.repeat(50)); execFileSync('git', ['-C', path.join(sm.r, 'n'), 'init', '-q']); execFileSync('git', ['-C', path.join(sm.r, 'n'), '-c', 'user.name=t', '-c', 'user.email=t@t', 'add', '.']); execFileSync('git', ['-C', path.join(sm.r, 'n'), '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '-m', 'n']);
223
+ put(sm.r, '.gitmodules', '[submodule "n"]\n\tpath = n\n\turl = ./n\n\tignore = all\n');
224
+ check('a nested repository hidden by .gitmodules ignore = all is refused like any other', exitOf(() => measure(sm.r, sm.g)).slice(0, 2), [true, 64]);
225
+ const hk = repo(); hk.g('commit', '-q', '--allow-empty', '-m', 'f'); put(hk.r, 'f', 'x\n'); put(hk.r, '.git/hooks/post-index-change', `#!/bin/sh\ntouch ${path.join(hk.r, 'RAN')}\n`); chmodSync(path.join(hk.r, '.git/hooks/post-index-change'), 0o755);
226
+ check('a post-index-change hook does not run during the measurement', [measure(hk.r, hk.g).length, existsSync(path.join(hk.r, 'RAN'))], [1, false]);
227
+ const sq = repo(); put(sq.r, 'src/a', 'a\n'); put(sq.r, 'other/b', 'b\n'); sq.g('add', '.'); sq.g('commit', '-q', '-m', 'f'); sq.g('sparse-checkout', 'set', '--cone', 'src'); put(sq.r, 'other/new', 'n\nn\n');
228
+ check('an untracked file outside the sparse checkout is counted, not refused', measure(sq.r, sq.g), [{ added: 2, deleted: 0, file: 'other/new' }]);
229
+ const sub = repo(); put(sub.r, 'pkg/a', 'a\nb\n'); put(sub.r, 'big', 'x\n'.repeat(2000)); sub.g('add', '.'); sub.g('commit', '-q', '-m', 'f'); put(sub.r, 'pkg/a', 'a\nB\n'); put(sub.r, 'big', 'y\n'.repeat(2000));
230
+ const subRoot = path.join(sub.r, 'pkg'); const subDiff = computeDiff(subRoot, sub.g('rev-parse', 'HEAD'), ['a']);
231
+ check('a project directory below the repository top level counts its own subtree: a one-line edit is 2 lines, none out of scope', [subDiff.total, subDiff.weighted, subDiff.outOfScope], [2, 2, []]);
232
+ const lk = repo(); put(lk.r, 'f', 'a\n'); lk.g('add', '.'); lk.g('commit', '-q', '-m', 'f'); const lkDir = path.join(lk.r, '..', path.basename(lk.r) + '-wt'); made.push(lkDir); lk.g('worktree', 'add', '-q', lkDir, '-b', 'x'); put(lkDir, 'f', 'a\nb\n');
233
+ check('a linked worktree measures its own files', measure(lkDir, lk.g), [{ added: 1, deleted: 0, file: 'f' }]);
234
+ const ic = repo(); put(ic.r, 'foo.txt', 'a\n'); ic.g('add', '.'); ic.g('commit', '-q', '-m', 'f'); ic.g('config', 'core.ignoreCase', 'true'); put(ic.r, 'Foo.txt', 'x\n'.repeat(3000));
235
+ check('core.ignoreCase true in the repository config does not hide a new file whose name differs from a tracked one only by case', measure(ic.r, ic.g), [{ added: 3000, deleted: 0, file: 'Foo.txt' }]);
236
+ symlinkSync('.git', path.join(ic.r, '.GIT'));
237
+ check('and a .GIT symlink to .git does not either: git refuses the path, so the measurement refuses rather than count less', refused(ic.r), [true, 64, true]);
238
+ const initAt = (r) => init({ root: r, env: { SOMI_GLOBAL_CONFIG: '' }, stateDir: path.join(r, '.somi', 'somi-state', 'loop'), now: () => 'T' }, { ...base, slug: 'i' });
239
+ const nameInvalid = exitOf(() => measuredTree(ic.r))[2];
240
+ check('git\'s invalid path is named in the refusal, bounded and without control characters', [nameInvalid.includes('"/.GIT"') || nameInvalid.includes('".GIT"'), nameInvalid.includes("'")], [true, false]);
241
+ const hl = repo(); put(hl.r, 'f', 'a\n'); hl.g('add', '.'); hl.g('commit', '-q', '-m', 'f'); const hlDir = path.join(hl.r, '..', path.basename(hl.r) + '-wt'); made.push(hlDir); hl.g('worktree', 'add', '-q', hlDir, '-b', 'x'); put(hlDir, 'f', 'a\nb\n'); linkSync(path.join(hlDir, '.git'), path.join(hlDir, '.GIT'));
242
+ check('a hard-linked gitfile .GIT in a linked worktree is refused (64), never counted as no change', refused(hlDir), [true, 64, true]);
243
+ const sg = (r, ...a) => execFileSync('git', ['-C', r, '-c', 'user.name=t', '-c', 'user.email=t@t', '-c', 'protocol.file.allow=always', ...a], { encoding: 'utf8' }).trim();
244
+ for (const [what, plant] of [['an empty .git directory', (d) => mkdirSync(path.join(d, '.git'))], ['a gitfile that is not a gitdir line', (d) => writeFileSync(path.join(d, '.git'), 'hello\n')], ['a gitfile pointing at a directory that is no repository', (d) => writeFileSync(path.join(d, '.git'), `gitdir: ${tmpdir()}\n`)]]) {
245
+ const pl = repo(); pl.g('commit', '-q', '--allow-empty', '-m', 'f'); put(pl.r, 'pkg/f', 'x\n'); plant(path.join(pl.r, 'pkg'));
246
+ check(`${what} between the project and the top is refused (64) with the .git cause, not walked past`, [refused(path.join(pl.r, 'pkg')), exitOf(() => measuredTree(path.join(pl.r, 'pkg')))[2].includes('.git" is neither a git directory nor'), initAt(path.join(pl.r, 'pkg')).code], [[true, 64, true], true, 64]);
247
+ }
248
+ const home = repo(); put(home.r, 'pkg/f', 'a\n'); home.g('add', '.'); home.g('commit', '-q', '-m', 'f'); const link = path.join(path.dirname(home.r), path.basename(home.r) + '-link'); made.push(link); symlinkSync(path.join(home.r, 'pkg'), link); put(home.r, 'pkg/f', 'a\nb\n');
249
+ check('a project directory reached through a symlink to a subdirectory is measured like the real path', [treeNumstat(link, home.g('rev-parse', 'HEAD'), measuredTree(link)), computeDiff(link, home.g('rev-parse', 'HEAD'), ['f']).weighted], [[{ added: 1, deleted: 0, file: 'f' }], 1]);
250
+ const decoy2 = repo(); decoy2.g('commit', '-q', '--allow-empty', '-m', 'other'); process.env.GIT_DIR = path.join(decoy2.r, '.git'); process.env.GIT_WORK_TREE = decoy2.r;
251
+ const atInit = initAt(home.r).out?.baseline_sha; delete process.env.GIT_DIR; delete process.env.GIT_WORK_TREE;
252
+ check('the init baseline is the project\'s HEAD whatever GIT_DIR the caller\'s environment holds', atInit, home.g('rev-parse', 'HEAD'));
253
+ const noHead = repo(); const refusedInit = initAt(noHead.r);
254
+ check('init in a repository with no commit is a refusal (64) that names HEAD, with no state written', [refusedInit.code, refusedInit.message.startsWith('somi-loop: cannot resolve HEAD') && refusedInit.message.includes('no commit'), existsSync(path.join(noHead.r, '.somi'))], [64, true, false]);
255
+ const deep = repo(); deep.g('commit', '-q', '--allow-empty', '-m', 'f'); const deepDir = path.join(deep.r, 'a'.repeat(40), 'b'.repeat(40), 'c'.repeat(40)); mkdirSync(path.join(deepDir, '.git'), { recursive: true });
256
+ check('a long path keeps its .git tail in the refusal', exitOf(() => measuredTree(deepDir))[2].includes('.git" is neither'), true);
257
+ const gitfile = readFileSync(path.join(lkDir, '.git'), 'utf8').trim().slice('gitdir: '.length);
258
+ writeFileSync(path.join(lkDir, '.git'), `gitdir: ${gitfile}\r\n\r\n`);
259
+ check('a gitfile ending in CRLF and a blank line, as git reads it, is accepted', measure(lkDir, lk.g), [{ added: 1, deleted: 0, file: 'f' }]);
260
+ const gf = repo(); gf.g('commit', '-q', '--allow-empty', '-m', 'f'); put(gf.r, 'pkg/f', 'x\n'); symlinkSync(path.join(lkDir, '.git'), path.join(gf.r, 'pkg', '.git'));
261
+ check('a gitfile reached through a symlink is refused, not read', refused(path.join(gf.r, 'pkg')), [true, 64, true]);
262
+ const fk = repo(); fk.g('commit', '-q', '--allow-empty', '-m', 'f'); put(fk.r, "x invalid path 'FAKE'", 'x\n'); chmodSync(path.join(fk.r, "x invalid path 'FAKE'"), 0);
263
+ const fakeMsg = exitOf(() => measuredTree(fk.r))[2];
264
+ check('a file name that contains git\'s invalid-path wording is not mistaken for it', [fakeMsg.startsWith('somi-loop: cannot measure the diff: '), fakeMsg.includes('refuses the path')], [true, false]);
265
+ const nest = (r, rel) => { sg(r, 'init', '-q', rel); put(r, `${rel}/a`, 'x\n'); sg(path.join(r, rel), 'add', '.'); sg(path.join(r, rel), 'commit', '-q', '-m', 'n'); }; // a repository at r/rel
266
+ const withSub = () => { const o = repo(); nest(o.r, '.'); const t = repo(); sg(t.r, 'submodule', 'add', '-q', o.r, 'n'); sg(t.r, 'commit', '-q', '-m', 't'); return t; }; // a committed submodule n
267
+ const refusedAs = (r, where) => { const [a, code, msg] = exitOf(() => measuredTree(r)); return [a, code, msg.includes(`does not support repositories with submodules (${where})`)]; };
268
+ const tmps = () => readdirSync(tmpdir()).filter((f) => f.startsWith('somi-tree-')).length;
269
+ const indexOf = (r) => readFileSync(path.join(r, '.git', 'index')).toString('hex');
270
+ const gl = repo(); gl.g('commit', '-q', '--allow-empty', '-m', 'f'); nest(gl.r, 'n'); sg(gl.r, 'add', 'n');
271
+ check('a gitlink in the index is refused (64) with one message naming it', refusedAs(gl.r, 'n'), [true, 64, true]);
272
+ const hd = withSub(); sg(hd.r, 'rm', '-q', '--cached', 'n'); rmSync(path.join(hd.r, 'n'), { recursive: true, force: true });
273
+ check('a gitlink only in HEAD (git rm --cached, directory gone) is refused', refusedAs(hd.r, 'n'), [true, 64, true]);
274
+ const ut = repo(); ut.g('commit', '-q', '--allow-empty', '-m', 'f'); nest(ut.r, 'd/e/inner');
275
+ check('an untracked directory that holds a .git is refused, named with its path', refusedAs(ut.r, 'd/e/inner/'), [true, 64, true]);
276
+ check('a gitlink refusal does not suggest .gitignore (only an untracked directory may be ignored)', [exitOf(() => measuredTree(gl.r))[2].includes('.gitignore'), exitOf(() => measuredTree(ut.r))[2].includes('add it to .gitignore')], [false, true]);
277
+ const co = withSub(); put(co.r, 'n/a', 'x\ny\n'); put(co.r, 'f', 'z\n'); const idx = indexOf(co.r); const before = tmps();
278
+ check('a checked-out submodule is refused whatever it holds, and the refusal writes nothing (index and temp directories as they were)', [refusedAs(co.r, 'n'), indexOf(co.r), tmps()], [[true, 64, true], idx, before]);
279
+ const ig = repo(); ig.g('commit', '-q', '--allow-empty', '-m', 'f'); nest(ig.r, 'vendor'); put(ig.r, '.gitignore', 'vendor/\n'); put(ig.r, 'f', 'a\n');
280
+ check('a nested repository that .gitignore lists is not a submodule: the rest is measured', measure(ig.r, ig.g).map((x) => x.file).sort(), ['.gitignore', 'f']);
281
+ const so = repo(); so.g('commit', '-q', '--allow-empty', '-m', 'f'); nest(so.r, '.somi/x'); put(so.r, 'f', 'a\n');
282
+ check('a repository under .somi is outside the measurement, not a submodule', measure(so.r, so.g), [{ added: 1, deleted: 0, file: 'f' }]);
283
+ for (const r of made) rmSync(r, { recursive: true, force: true });
284
+ }
285
+
286
+ console.log(`loop engine tests: ${pass} ok, ${fail} failed`);
287
+ process.exit(fail === 0 ? 0 : 1);