@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,371 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Tests of the diary and progress writers (loop-notes.mjs, loop-notes-compact.mjs). The risk is the write path, so the
|
|
3
|
+
// threat cases list every file under the temp tree, links included, before and after. Run by tests/scripts/loop-engine.sh.
|
|
4
|
+
|
|
5
|
+
import fs, { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, symlinkSync, truncateSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { spawnSync } from 'node:child_process';
|
|
8
|
+
import { tmpdir } from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
11
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
12
|
+
import { appendDiary, findIterationRow, markIteration, setLastActivity } from '../../../scripts/lib/loop-notes.mjs';
|
|
13
|
+
import { LoopExit } from '../../../scripts/lib/loop-exit.mjs';
|
|
14
|
+
|
|
15
|
+
const LIB = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'scripts', 'lib');
|
|
16
|
+
let pass = 0; let fail = 0; let n = 0;
|
|
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
|
+
const exitOf = (fn) => { try { fn(); } catch (e) { return [e instanceof LoopExit, e.code]; } return 'no throw'; };
|
|
21
|
+
|
|
22
|
+
const base = mkdtempSync(path.join(tmpdir(), 'loop-notes-'));
|
|
23
|
+
// On every exit, a failed check or a throw included: modes are restored first, or a chmod'd directory would outlive the run.
|
|
24
|
+
process.on('exit', () => { spawnSync('chmod', ['-R', 'u+rwx', base]); rmSync(base, { recursive: true, force: true }); });
|
|
25
|
+
const NOW = '2026-10-29T09:30:00Z';
|
|
26
|
+
const PRE = '# Diary — p1\n\n> Spec: x\n\nPreamble.\n\n---\n\n';
|
|
27
|
+
const entry = (n, cat = 'note') => `## 2026-01-${String((n % 28) + 1).padStart(2, '0')} 10:00 — ${n === 27 ? 'Compacted: earlier' : `entry ${n}`}\n\n${cat === null ? 'no category line\n' : `**Category**: \`${cat}\`\n**Phase**: 1\n`}\nbody ${n}\n\n---\n\n`;
|
|
28
|
+
const diaryOf = (n, special = {}) => PRE + Array.from({ length: n }, (_, i) => entry(i + 1, special[i + 1])).join('');
|
|
29
|
+
const PROGRESS = '# Progress — p1\n\n## Status\n\n`in-progress`\n\n**Started**: 2026-10-28\n**Last activity**: 2026-10-28 — start\n\n## Iteration progress\n\n| Iteration | Title | Status | Reviewed | Last activity |\n|-----------|---------|-------------|----------|---------------|\n| 1.1 | First | done | approve | 2026-10-28 |\n| 2.1 | Writers | in-progress | — | — |\n\n## Follow-ups\n\n- [ ] a | b\n';
|
|
30
|
+
// A fresh root with .somi/plans/p1/{diary.md,progress.md}.
|
|
31
|
+
function fresh({ diary = diaryOf(2), progress = PROGRESS } = {}) {
|
|
32
|
+
const root = path.join(base, `case${n++}`); const dir = path.join(root, '.somi', 'plans', 'p1');
|
|
33
|
+
mkdirSync(dir, { recursive: true });
|
|
34
|
+
if (diary !== null) writeFileSync(path.join(dir, 'diary.md'), diary);
|
|
35
|
+
if (progress !== null) writeFileSync(path.join(dir, 'progress.md'), progress);
|
|
36
|
+
return { root, dir, plan: { root, slug: 'p1' } };
|
|
37
|
+
}
|
|
38
|
+
const read = (f) => readFileSync(f, 'utf8');
|
|
39
|
+
const headings = (t) => t.split('\n').filter((l) => l.startsWith('## ')).length;
|
|
40
|
+
// Every path under `dir` with its content hash (or link target): the "nothing else was written" oracle.
|
|
41
|
+
const snap = (dir) => Object.fromEntries(readdirSync(dir, { recursive: true }).sort().map((rel) => {
|
|
42
|
+
const f = path.join(dir, rel); const st = lstatSync(f);
|
|
43
|
+
return [rel, st.isSymbolicLink() ? `link->${readlinkSync(f)}` : st.isDirectory() ? 'dir' : !st.isFile() ? 'special' : createHash('sha256').update(readFileSync(f)).digest('hex')];
|
|
44
|
+
}));
|
|
45
|
+
// Bidi override, zero-width space, soft hyphen, tag characters (spelling "AB"), variation selectors, fillers: built from code points.
|
|
46
|
+
const INVISIBLE = String.fromCodePoint(0x202e, 0x200b, 0xad, 0x34f, 0xe0041, 0xe0042, 0xfe0f, 0xe0100, 0x3164, 0xffa0, 0x180e);
|
|
47
|
+
const note = (over = {}) => ({ category: 'note', phase: '2', title: 'Writers done', body: 'two writers', now: NOW, ...over });
|
|
48
|
+
|
|
49
|
+
console.log('== loop notes: no environment, no process ==');
|
|
50
|
+
for (const f of ['loop-notes.mjs', 'loop-notes-compact.mjs']) {
|
|
51
|
+
const code = read(path.join(LIB, f)).split('\n').filter((l) => !l.trimStart().startsWith('//')).join('\n');
|
|
52
|
+
check(`${f} names neither process nor globalThis outside comments`, /\b(process|globalThis)\b/.test(code), false);
|
|
53
|
+
}
|
|
54
|
+
const { plan: p0 } = fresh();
|
|
55
|
+
check('a missing or malformed now is refused with 64 before any read', [exitOf(() => appendDiary(p0, note({ now: undefined }))), exitOf(() => appendDiary(p0, note({ now: 'yesterday' })))], [[true, 64], [true, 64]]);
|
|
56
|
+
check('a now that is not a real instant in 2000..2099 is refused with 64 by every writer', ['9999-99-99T99:99', '2026-02-30T10:00', '2026-10-29T24:00', '1999-12-31T23:59', '2100-01-01T00:00'].flatMap((now) => [exitOf(() => appendDiary(p0, note({ now }))), exitOf(() => setLastActivity(p0, { activity: 'x', now }))]), Array(10).fill([true, 64]));
|
|
57
|
+
console.log('== appendDiary: the entry and its place ==');
|
|
58
|
+
{
|
|
59
|
+
const { plan, dir } = fresh();
|
|
60
|
+
const before = read(path.join(dir, 'diary.md'));
|
|
61
|
+
const r = appendDiary(plan, note());
|
|
62
|
+
const after = read(path.join(dir, 'diary.md'));
|
|
63
|
+
const want = `## 2026-10-29 09:30 — Writers done\n\n**Category**: \`note\`\n**Phase**: 2\n\ntwo writers\n\nWritten by the loop step engine; every field comes from stored loop state.\n\n---\n\n`;
|
|
64
|
+
check('the entry lands newest first, right after the preamble, in template shape', after, PRE + want + before.slice(PRE.length));
|
|
65
|
+
check('it reports the one path it wrote and nothing unwritten', r, { wrote: ['.somi/plans/p1/diary.md'], unwritten: [] });
|
|
66
|
+
check('a category outside the closed list, an empty title and a title with no letter or digit are refused with 64', [exitOf(() => appendDiary(plan, note({ category: 'chat' }))), exitOf(() => appendDiary(plan, note({ title: '###' }))), exitOf(() => appendDiary(plan, note({ title: `!! ${INVISIBLE} --` })))], [[true, 64], [true, 64], [true, 64]]);
|
|
67
|
+
check('the writer authors neither decision-change nor plan-change (64, nothing written), and an entry with no body still ends with the provenance line', [exitOf(() => appendDiary(plan, note({ category: 'decision-change' }))), exitOf(() => appendDiary(plan, note({ category: 'plan-change' }))), read(path.join(dir, 'diary.md')).includes('decision-change'), appendDiary(plan, note({ title: 'No body', body: '' })).wrote.length, /\*\*Phase\*\*: 2\n\nWritten by the loop step engine; [^\n]*\n\n---\n\n## 2026-10-29 09:30 — Writers done/.test(read(path.join(dir, 'diary.md')))], [[true, 64], [true, 64], false, 1, true]);
|
|
68
|
+
check('a title that reads as the compaction summary is refused with 64; one that merely contains the word is not', [exitOf(() => appendDiary(plan, note({ title: 'Compacted: 2026-01-01 .. 2026-01-02' }))), exitOf(() => appendDiary(plan, note({ title: ' ### compacted : x' }))), exitOf(() => appendDiary(plan, note({ title: 'Re: Compacted: x' })))], [[true, 64], [true, 64], 'no throw']);
|
|
69
|
+
}
|
|
70
|
+
console.log('== appendDiary: a replayed entry is written once ==');
|
|
71
|
+
{
|
|
72
|
+
const { plan, dir } = fresh();
|
|
73
|
+
const f = path.join(dir, 'diary.md');
|
|
74
|
+
appendDiary(plan, note());
|
|
75
|
+
const once = read(f);
|
|
76
|
+
const again = appendDiary(plan, note());
|
|
77
|
+
check('an entry identical to the newest one writes nothing and says so: wrote [], no unwritten, skipped replay', [again, read(f)], [{ wrote: [], unwritten: [], skipped: 'replay' }, once]);
|
|
78
|
+
appendDiary(plan, note({ category: 'discovery' }));
|
|
79
|
+
appendDiary(plan, note({ title: 'Other title' }));
|
|
80
|
+
appendDiary(plan, note({ now: '2026-10-29T09:31:00Z' }));
|
|
81
|
+
appendDiary(plan, note({ body: 'other body, same stamp, title, category and phase' }));
|
|
82
|
+
appendDiary(plan, note({ body: 'other body, same stamp, title, category and phase', phase: '3' }));
|
|
83
|
+
check('a different category, title, minute, body or phase is a new entry', headings(read(f)) - headings(once), 5);
|
|
84
|
+
appendDiary(plan, note({ title: 'Writers done' }));
|
|
85
|
+
appendDiary(plan, note({ title: 'Writers done' }));
|
|
86
|
+
check('only the newest entry counts: an older entry repeated is written once more, then its immediate repeat is not', headings(read(f)) - headings(once), 6);
|
|
87
|
+
}
|
|
88
|
+
console.log('== appendDiary: the 40/15 compaction ==');
|
|
89
|
+
{
|
|
90
|
+
const { plan, dir } = fresh({ diary: diaryOf(41, { 20: 'decision-change', 30: 'plan-change', 25: 'review-feedback', 35: null }) });
|
|
91
|
+
const before = read(path.join(dir, 'diary.md'));
|
|
92
|
+
const r = appendDiary(plan, note({ title: 'N' }));
|
|
93
|
+
const diary = read(path.join(dir, 'diary.md')); const archive = read(path.join(dir, 'diary-archive.md'));
|
|
94
|
+
const moved = [];
|
|
95
|
+
for (let k = 15; k <= 41; k++) if (![20, 27, 30, 35].includes(k)) moved.push(entry(k, k === 25 ? 'review-feedback' : 'note'));
|
|
96
|
+
check('41 entries gain one (42) and compact to 15 newest + 3 that must stay + an earlier Compacted entry + the new one', headings(diary), 20);
|
|
97
|
+
check('the moved entries are the movable ones older than the newest 15, verbatim, newest first, at the end of the archive', archive.endsWith(moved.join('')), true);
|
|
98
|
+
check('decision-change, plan-change, an earlier Compacted entry and an entry with no readable category stay in diary.md', [20, 30, 35, 27].map((k) => diary.includes(entry(k, k === 20 ? 'decision-change' : k === 30 ? 'plan-change' : k === 27 ? 'note' : null))), [true, true, true, true]);
|
|
99
|
+
check('one Compacted entry names the span and the count, in place of the newest moved entry', /## 2026-10-29 09:30 — Compacted: 2026-01-\d\d \.\. 2026-01-\d\d\n/.test(diary) && diary.includes('23 older entries moved verbatim') && diary.indexOf('entry 14\n') < diary.indexOf('Compacted:') && diary.indexOf('Compacted:') < diary.indexOf('entry 20\n'), true);
|
|
100
|
+
check('both files are reported as written; the archive got a head', [r.wrote, archive.startsWith('# Diary archive — p1\n\n')], [['.somi/plans/p1/diary-archive.md', '.somi/plans/p1/diary.md'], true]);
|
|
101
|
+
check('every original entry survives, in the diary or the archive', [...before.matchAll(/body (\d+)/g)].every((m) => (diary + archive).includes(`body ${m[1]}\n`)), true);
|
|
102
|
+
}
|
|
103
|
+
{
|
|
104
|
+
const old = '# Diary archive — p1\n\n## 2025-12-01 10:00 — old\n\n**Category**: `note`\n\nold body\n\n---\n\n';
|
|
105
|
+
const { plan, dir } = fresh({ diary: diaryOf(40) });
|
|
106
|
+
writeFileSync(path.join(dir, 'diary-archive.md'), old);
|
|
107
|
+
appendDiary(plan, note());
|
|
108
|
+
const archive = read(path.join(dir, 'diary-archive.md'));
|
|
109
|
+
check('an existing archive keeps its entries and gains the moved ones after them (40 + 1 compacts)', [archive.startsWith(old), headings(archive), headings(read(path.join(dir, 'diary.md')))], [true, 1 + 25, 17]);
|
|
110
|
+
const small = fresh({ diary: diaryOf(39) });
|
|
111
|
+
appendDiary(small.plan, note());
|
|
112
|
+
check('39 + 1 = 40 entries do not compact: no archive file', [headings(read(path.join(small.dir, 'diary.md'))), existsSync(path.join(small.dir, 'diary-archive.md'))], [40, false]);
|
|
113
|
+
}
|
|
114
|
+
// The Compacted entries in a diary as [title, count]; the fixture's hand-made 'Compacted: earlier' is not one of ours.
|
|
115
|
+
const SUMMARY = /^## [\d-]+ [\d:]+ — (Compacted: \d{4}-\d\d-\d\d \.\. \d{4}-\d\d-\d\d)\n\n\*\*Category\*\*: `note`\n\*\*Phase\*\*: work-item-wide\n\n(\d+) older entries moved verbatim/gm;
|
|
116
|
+
const summaries = (diary) => [...diary.matchAll(SUMMARY)].map((m) => [m[1], Number(m[2])]);
|
|
117
|
+
const running = (count, extra = '') => `## 2026-01-04 10:00 — Compacted: 2025-12-01 .. 2025-12-31\n\n**Category**: \`note\`\n**Phase**: work-item-wide\n\n${count} older entries moved verbatim to [\`diary-archive.md\`](./diary-archive.md); decision-change and plan-change entries stay here.\n${extra}\n---\n\n`;
|
|
118
|
+
{
|
|
119
|
+
// 30 decision-change entries never move, so notes appended one after another are compacted several times.
|
|
120
|
+
const dc = {}; for (let k = 12; k <= 41; k++) dc[k] = 'decision-change';
|
|
121
|
+
const { plan, dir } = fresh({ diary: diaryOf(41, dc) });
|
|
122
|
+
const rs = Array.from({ length: 8 }, (_, i) => appendDiary(plan, note({ title: `append ${i}`, now: `2026-10-29T09:${String(10 + i)}:00Z` })));
|
|
123
|
+
const diary = read(path.join(dir, 'diary.md')); const archive = existsSync(path.join(dir, 'diary-archive.md')) ? read(path.join(dir, 'diary-archive.md')) : '';
|
|
124
|
+
const ours = summaries(diary);
|
|
125
|
+
check('8 appends compacted more than once, and the diary holds exactly one Compacted entry whose count is the number archived', [rs.filter((r) => r.wrote.length === 2).length > 1, ours.length, ours[0]?.[1] === headings(archive), ours[0]?.[1] > 0], [true, 1, true, true]);
|
|
126
|
+
}
|
|
127
|
+
{
|
|
128
|
+
const { plan, dir } = fresh({ diary: diaryOf(41).replace(entry(3), running(7)) });
|
|
129
|
+
appendDiary(plan, note({ title: 'N' }));
|
|
130
|
+
const diary = read(path.join(dir, 'diary.md'));
|
|
131
|
+
check('an earlier Compacted entry is replaced in place: span widened, count summed (7 + 26), still one', [summaries(diary), diary.indexOf('entry 2\n') < diary.indexOf('Compacted:') && diary.indexOf('Compacted:') < diary.indexOf('entry 4\n')], [[['Compacted: 2025-12-01 .. 2026-01-27', 33]], true]);
|
|
132
|
+
}
|
|
133
|
+
{
|
|
134
|
+
const { plan, dir } = fresh({ diary: diaryOf(41).replace(entry(20), running(7)) });
|
|
135
|
+
appendDiary(plan, note({ title: 'N' }));
|
|
136
|
+
const diary = read(path.join(dir, 'diary.md'));
|
|
137
|
+
check('a prior summary in the older region merges too: one summary, 7 + 25, and the archive holds the 25 moved entries', [summaries(diary), headings(read(path.join(dir, 'diary-archive.md')))], [[['Compacted: 2025-12-01 .. 2026-01-27', 32]], 25]);
|
|
138
|
+
}
|
|
139
|
+
{
|
|
140
|
+
// Entries that only look like our summary are not ours: they stay byte for byte, and never become the running summary.
|
|
141
|
+
const forged = running(7).replace('`note`', '`decision-change`');
|
|
142
|
+
const huge = running('99999999999999999999');
|
|
143
|
+
const extra = running(7, '\nand an extra line\n');
|
|
144
|
+
const otherPhase = running(7).replace('work-item-wide', '2');
|
|
145
|
+
for (const [name, planted] of Object.entries({ 'a decision-change entry titled Compacted': forged, 'a summary with a 20-digit count': huge, 'a summary with an extra line': extra, 'a summary in another phase': otherPhase, 'a summary with text after its closing rule': `${running(7)}trailing text\n\n` })) {
|
|
146
|
+
const { plan, dir } = fresh({ diary: diaryOf(41).replace(entry(3), planted) });
|
|
147
|
+
appendDiary(plan, note({ title: 'N' }));
|
|
148
|
+
const diary = read(path.join(dir, 'diary.md'));
|
|
149
|
+
check(`${name} is left byte for byte in diary.md; our summary counts only the 26 moved entries and sits elsewhere`, [diary.includes(planted), summaries(diary).filter(([t]) => !t.endsWith('2025-12-31')), headings(read(path.join(dir, 'diary-archive.md')))], [true, [['Compacted: 2026-01-01 .. 2026-01-27', 26]], 26]);
|
|
150
|
+
}
|
|
151
|
+
const dc = {}; for (let k = 12; k <= 41; k++) dc[k] = 'decision-change';
|
|
152
|
+
const { plan, dir } = fresh({ diary: diaryOf(41, dc).replace(entry(3), huge) });
|
|
153
|
+
for (let i = 0; i < 8; i++) appendDiary(plan, note({ title: `append ${i}`, now: `2026-10-29T09:${String(10 + i)}:00Z` }));
|
|
154
|
+
const diary = read(path.join(dir, 'diary.md'));
|
|
155
|
+
check('an oversized count does not breed a second summary: later compactions keep merging into one of ours', [diary.includes(huge), summaries(diary).filter(([t]) => !t.endsWith('2025-12-31')).length], [true, 1]);
|
|
156
|
+
}
|
|
157
|
+
{
|
|
158
|
+
// Movable entries with no date in their heading do not enter the summary's span (a '?' would break the next merge).
|
|
159
|
+
const undated = diaryOf(41).replace(/## 2026-01-(\d\d) 10:00 — entry (1[5-9]|2[0-9])\n/g, '## undated — entry $2\n');
|
|
160
|
+
const { plan, dir } = fresh({ diary: undated });
|
|
161
|
+
appendDiary(plan, note({ title: 'N' }));
|
|
162
|
+
const first = summaries(read(path.join(dir, 'diary.md')));
|
|
163
|
+
check('moved entries with undated headings leave a summary with a real date span', first.length === 1 && /^Compacted: \d{4}-\d\d-\d\d \.\. \d{4}-\d\d-\d\d$/.test(first[0][0]), true);
|
|
164
|
+
}
|
|
165
|
+
console.log('== size caps: an oversized diary or archive is reported, never read ==');
|
|
166
|
+
{
|
|
167
|
+
const cap = 4 * 1024 * 1024 + 1;
|
|
168
|
+
const big = fresh();
|
|
169
|
+
const bigDiary = path.join(big.dir, 'diary.md'); truncateSync(bigDiary, cap);
|
|
170
|
+
const b = snap(big.root);
|
|
171
|
+
const r = appendDiary(big.plan, note());
|
|
172
|
+
check('a diary over 4 MiB is left alone and reported too-large with its summary: category, title and body', [r.wrote, r.unwritten.map((u) => [u.file, u.reason, u.line]), snap(big.root)], [[], [['diary.md', 'too-large', 'note — Writers done — two writers']], b]);
|
|
173
|
+
const { plan, dir } = fresh({ diary: diaryOf(41) });
|
|
174
|
+
const archiveFile = path.join(dir, 'diary-archive.md'); writeFileSync(archiveFile, ''); truncateSync(archiveFile, cap);
|
|
175
|
+
const first = appendDiary(plan, note({ title: 'one' }));
|
|
176
|
+
const second = appendDiary(plan, note({ title: 'two' }));
|
|
177
|
+
check('an archive over 4 MiB: the entry is still written uncompacted, archive-too-large comes back on every call, the archive is untouched', [first.wrote, second.wrote, [first, second].map((x) => x.unwritten.map((u) => [u.file, u.reason, u.kind])), headings(read(path.join(dir, 'diary.md'))), statSync(archiveFile).size], [['.somi/plans/p1/diary.md'], ['.somi/plans/p1/diary.md'], Array(2).fill([['diary-archive.md', 'archive-too-large', 'notice']]), 43, cap]);
|
|
178
|
+
}
|
|
179
|
+
console.log('== progress writers: the row and the line, nothing else ==');
|
|
180
|
+
{
|
|
181
|
+
const { plan, dir } = fresh();
|
|
182
|
+
const f = path.join(dir, 'progress.md');
|
|
183
|
+
markIteration(plan, '2.1', { status: 'done', reviewed: 'approve', activity: 'writers', now: NOW });
|
|
184
|
+
check('only the 2.1 row changes: title kept, columns padded as before', read(f), PROGRESS.replace('| 2.1 | Writers | in-progress | — | — |', '| 2.1 | Writers | done | approve | 2026-10-29 — writers |'));
|
|
185
|
+
setLastActivity(plan, { activity: 'iteration 2.1 done', now: NOW });
|
|
186
|
+
check('setLastActivity changes only the Last activity line', read(f), PROGRESS.replace('| 2.1 | Writers | in-progress | — | — |', '| 2.1 | Writers | done | approve | 2026-10-29 — writers |').replace('**Last activity**: 2026-10-28 — start', '**Last activity**: 2026-10-29 — iteration 2.1 done'));
|
|
187
|
+
check('a status outside the closed list, an empty patch and a bad iteration are refused with 64', [exitOf(() => markIteration(plan, '2.1', { status: 'finished', now: NOW })), exitOf(() => markIteration(plan, '2.1', { status: 'done', now: undefined })), exitOf(() => markIteration(plan, '2', { status: 'done', now: NOW }))], [[true, 64], [true, 64], [true, 64]]);
|
|
188
|
+
}
|
|
189
|
+
{
|
|
190
|
+
const bad = {
|
|
191
|
+
'a missing row': [PROGRESS.replace(/\| 2\.1 .*\n/, ''), 'row-missing'],
|
|
192
|
+
'a row with an extra column': [PROGRESS.replace('| in-progress | — | — |', '| in-progress | — | — | extra |'), 'row-not-template-shape'],
|
|
193
|
+
'a duplicated row': [PROGRESS.replace('| 1.1 | First', '| 2.1 | Dup | done | x | y |\n| 1.1 | First'), 'row-ambiguous'],
|
|
194
|
+
'a table whose first column is not Iteration': [PROGRESS.replace('| Iteration |', '| Number |'), 'not-template-shape'],
|
|
195
|
+
};
|
|
196
|
+
for (const [name, [text, reason]] of Object.entries(bad)) {
|
|
197
|
+
const { plan, root } = fresh({ progress: text });
|
|
198
|
+
const before = snap(root);
|
|
199
|
+
const r = markIteration(plan, '2.1', { status: 'done', reviewed: 'approve', now: NOW });
|
|
200
|
+
check(`${name}: nothing is written and the row text comes back (${reason})`, [snap(root), r.wrote, r.unwritten.map((u) => [u.file, u.reason, u.line])], [before, [], [['progress.md', reason, 'iteration 2.1: Status=done, Reviewed=approve, Last activity=2026-10-29']]]);
|
|
201
|
+
}
|
|
202
|
+
const four = '# Progress — p1\n\n## Iteration progress\n\n| Iteration | Title | Status | Reviewed |\n|-----------|-------|--------|----------|\n| 2.1 | Writers | not-started | — |\n';
|
|
203
|
+
const lenient = (progress, status = 'in-progress') => { const { plan, dir } = fresh({ progress }); const r = markIteration(plan, '2.1', { status, reviewed: 'approve', activity: 'x', now: NOW }); return [r.wrote, r.unwritten, read(path.join(dir, 'progress.md')).split('\n').find((l) => l.startsWith('| 2.1'))]; };
|
|
204
|
+
check('a four-column table (no Last activity) has its Status and Reviewed cells set and nothing else', lenient(four), [['.somi/plans/p1/progress.md'], [], '| 2.1 | Writers | in-progress | approve |']);
|
|
205
|
+
check('a table without a Reviewed column has its Status set; the Reviewed value is skipped, not refused', lenient(four.replace('| Reviewed |', '| Verdict |')), [['.somi/plans/p1/progress.md'], [], '| 2.1 | Writers | in-progress | — |']);
|
|
206
|
+
check('a table with its columns in another order is read by the names of its header', lenient('# Progress — p1\n\n## Iteration progress\n\n| Iteration | Reviewed | Status |\n|---|---|---|\n| 2.1 | — | not-started |\n'), [['.somi/plans/p1/progress.md'], [], '| 2.1 | approve | in-progress |']);
|
|
207
|
+
check('a table with no Status column, or with a row of another width, is still handed back', [lenient(four.replace('| Status |', '| State |'))[1].map((u) => u.reason), lenient(four.replace('| — |', '| — | x |'))[1].map((u) => u.reason)], [['not-template-shape'], ['row-not-template-shape']]);
|
|
208
|
+
const noLine = fresh({ progress: PROGRESS.replace(/\*\*Last activity\*\*.*\n/, '').replace('## Status', '## State') });
|
|
209
|
+
const before = snap(noLine.root);
|
|
210
|
+
const r = setLastActivity(noLine.plan, { activity: 'x', now: NOW });
|
|
211
|
+
check('a progress file with no Status section and no Last activity line is left alone and the line comes back as line-missing', [snap(noLine.root), r.unwritten], [before, [{ file: 'progress.md', reason: 'line-missing', line: '**Last activity**: 2026-10-29 — x', kind: 'last-activity' }]]);
|
|
212
|
+
}
|
|
213
|
+
{
|
|
214
|
+
const NO_LINE = PROGRESS.replace(/\*\*Last activity\*\*.*\n/, '');
|
|
215
|
+
const last = (progress) => { const { plan, dir, root } = fresh({ progress }); const b = snap(root); const r = setLastActivity(plan, { activity: 'x', now: NOW }); return [read(path.join(dir, 'progress.md')), r.wrote.length, r.unwritten.map((u) => u.reason), isDeepStrictEqual(b, snap(root))]; };
|
|
216
|
+
check('a missing Last activity line is inserted straight after a **key**: line that ends the Status section', last(NO_LINE).slice(0, 3), [PROGRESS.replace('2026-10-28 — start', '2026-10-29 — x'), 1, []]);
|
|
217
|
+
const plain = '# Progress — p1\n\n## Status\n\n`in-progress`\n\n## Iteration progress\n';
|
|
218
|
+
check('after a plain line it gets a blank line before it, and the blank line before the next heading stays', last(plain).slice(0, 3), ['# Progress — p1\n\n## Status\n\n`in-progress`\n\n**Last activity**: 2026-10-29 — x\n\n## Iteration progress\n', 1, []]);
|
|
219
|
+
check('a Status section that ends the file takes the line at the end', last('# P\n\n## Status\n\n`done`\n').slice(0, 2), ['# P\n\n## Status\n\n`done`\n\n**Last activity**: 2026-10-29 — x\n', 1]);
|
|
220
|
+
check('two Last activity lines are still refused as row-ambiguous, nothing written', [PROGRESS.replace('\n## Iteration progress', '**Last activity**: again\n\n## Iteration progress')].map((t) => last(t)).map(([, w, why, same]) => [w, why, same]), [[0, ['row-ambiguous'], true]]);
|
|
221
|
+
const spelled = { 'a bold line with the colon inside': '**Last activity:** 2026-10-28 — start', 'a plain line': 'Last activity: 2026-10-28 — start', 'a bold line with no space after the colon': '**Last activity**:2026-10-28', 'underscore emphasis': '_Last activity_: 2026-10-28 — start' };
|
|
222
|
+
check('a Last activity line in another spelling is not duplicated: handed back as row-ambiguous, nothing written', Object.values(spelled).map((l) => last(NO_LINE.replace('**Started**: 2026-10-28', `**Started**: 2026-10-28\n${l}`)).slice(1)), Object.keys(spelled).map(() => [0, ['row-ambiguous'], true]));
|
|
223
|
+
const refused = { 'no Status heading': NO_LINE.replace('## Status', '## State'), 'two Status headings': `${NO_LINE}\n## Status\n\ntext\n`, 'a fence in the Status section': NO_LINE.replace('**Started**: 2026-10-28', '```\nx\n```'), 'a comment in the Status section': NO_LINE.replace('**Started**: 2026-10-28', '<!-- x -->'), 'a CR in the file': NO_LINE.replace('Started', 'Sta\rrted') };
|
|
224
|
+
check('no single clean Status section, or a file not in template shape: handed back unchanged', Object.values(refused).map((t) => last(t).slice(1)), Object.keys(refused).map((k) => [0, [k === 'a CR in the file' ? 'not-template-shape' : 'line-missing'], true]));
|
|
225
|
+
}
|
|
226
|
+
{
|
|
227
|
+
const PHASES = '## Phase progress\n\n| # | Phase | Status | Iterations done / total |\n|---|---|---|---|\n| 1 | A | done | 1/1 |\n| 2 | B | in-progress | 0/3 |\n\n## Iteration progress';
|
|
228
|
+
const PHASED = PROGRESS.replace('## Iteration progress', PHASES).replace('| 2.1 | Writers | in-progress | — | — |\n', '| 2.1 | Writers | in-progress | — | — |\n| 2.2 | More | done | approve | 2026-10-28 |\n| 2.3 | Last | not-started | — | — |\n');
|
|
229
|
+
const DONE = '| 2.1 | Writers | done | approve | 2026-10-29 — w |';
|
|
230
|
+
const mark = (progress) => { const { plan, dir, root } = fresh({ progress }); const b = snap(root); const r = markIteration(plan, '2.1', { status: 'done', reviewed: 'approve', activity: 'w', now: NOW }); return { text: read(path.join(dir, 'progress.md')), wrote: r.wrote.length, unwritten: r.unwritten, same: isDeepStrictEqual(b, snap(root)) }; };
|
|
231
|
+
const m = mark(PHASED);
|
|
232
|
+
check('marking 2.1 done sets phase 2 to the count of its done rows (2.1 and 2.2, not 1.1) and keeps the total, the cell width and the Status cells', [m.text, m.wrote, m.unwritten], [PHASED.replace('| 2.1 | Writers | in-progress | — | — |', DONE).replace('0/3 ', '2/3 '), 1, []]);
|
|
233
|
+
const high = mark(PHASED.replace('0/3 ', '1/1 '));
|
|
234
|
+
check('a count above the total leaves the cell as it was, still writes the row, and comes back as a notice', [high.text.includes(DONE), high.text.includes('| 1/1 |'), high.wrote, high.unwritten.map((u) => [u.file, u.reason, u.kind])], [true, true, 1, [['progress.md', 'count-above-total', 'notice']]]);
|
|
235
|
+
const skips = { 'no Phase progress table': PROGRESS, 'no done-count column': PHASED.replace('Iterations done / total', 'Done'), 'no row for the phase': PHASED.replace(/\| 2 \| B.*\n/, ''), 'a done count that is not a/b': PHASED.replace('0/3', 'zero'), 'a fence in the section': PHASED.replace('0/3 |\n', '0/3 |\n```\n```\n'), 'the heading twice': `${PHASED}\n## Phase progress\n` };
|
|
236
|
+
check('a phase table that cannot be read is skipped with no hand-back: the row is written, the rest is as it was', Object.values(skips).map((t) => { const x = mark(t); return [x.wrote, x.unwritten, x.text.replace(DONE, '| 2.1 | Writers | in-progress | — | — |') === t]; }), Object.keys(skips).map(() => [1, [], true]));
|
|
237
|
+
const phaseTable = (t) => t.slice(t.indexOf('## Phase progress'), t.indexOf('## Iteration progress'));
|
|
238
|
+
const right = PHASED.replace('0/3 ', '2/3 ').replace('| 2.1 | Writers | in-progress', '| 2.1 | Writers | done ');
|
|
239
|
+
check('a phase table that already shows the right count comes out as it went in, whole', phaseTable(mark(right).text), phaseTable(right));
|
|
240
|
+
const phaseOf = (t) => t.match(/\| 2 \| B .*\n/)[0];
|
|
241
|
+
const twoTables = PHASED.replace(/\| 2 \| B .*\n/, '').replace('\n\n## Iteration progress', '\n\n| # | Phase | Status | Iterations done / total |\n|---|---|---|---|\n| 2 | B | in-progress | 0/3 |\n\n## Iteration progress');
|
|
242
|
+
const tt = mark(twoTables);
|
|
243
|
+
check('a second table in the Phase progress section is not read as the phase table: nothing in it is rewritten', [tt.text.includes('| 2 | B | in-progress | 0/3 |'), tt.wrote, tt.unwritten], [true, 1, []]);
|
|
244
|
+
const noSep = mark(PHASED.replace('|---|---|---|---|\n', ''));
|
|
245
|
+
check('a phase table with no separator row after its header is skipped', [noSep.text.includes('| 2 | B | in-progress | 0/3 |'), noSep.wrote], [true, 1]);
|
|
246
|
+
const dup = mark(PHASED.replace('| 2.3 | Last | not-started | — | — |', '| 2.2 | More | done | approve | 2026-10-28 |'));
|
|
247
|
+
check('a repeated done row counts once: 2.1 and a twice-listed 2.2 make 2, not 3', phaseOf(dup.text).includes('| 2/3 |'), true);
|
|
248
|
+
const wide = mark(PHASED.replace('| 2.3 | Last | not-started | — | — |', '| 2.3 | Last | done | approve | 2026-10-28 | x |'));
|
|
249
|
+
check('a row of another width than the iteration header is not counted: 2.1 and 2.2 make 2, not 3', phaseOf(wide.text).includes('| 2/3 |'), true);
|
|
250
|
+
const long = { total: ['0/99999', '0/99999'], done: ['99999/3', '99999/3'] };
|
|
251
|
+
check('an a/b cell with more than 4 digits, on either side, is read as absent: skipped, the row is written, nothing comes back', Object.values(long).map(([cell]) => { const x = mark(PHASED.replace('0/3 ', cell)); return [phaseOf(x.text).includes(cell), x.wrote, x.unwritten]; }), [[true, 1, []], [true, 1, []]]);
|
|
252
|
+
// a blank line between the header and the rows makes the first line of the run a data row, not the header
|
|
253
|
+
const gap = PHASED.replace('|---------------|\n| 1.1', '|---------------|\n\n| 1.1');
|
|
254
|
+
const firstRow = (t) => { try { const x = mark(t); return [phaseOf(x.text).includes('| 2/3 |'), x.wrote, x.unwritten]; } catch (e) { return [e.name]; } };
|
|
255
|
+
check('a blank line after the header, the first row without a trailing |: 2.1 and 2.2 are counted, nothing throws', firstRow(gap.replace('| 2026-10-28 |\n| 2.1', '| 2026-10-28\n| 2.1')), [true, 1, []]);
|
|
256
|
+
check('a blank line after the header, the first row of another width: 2.1 and 2.2 are counted, not skipped', firstRow(gap.replace('| 2026-10-28 |\n| 2.1', '| 2026-10-28 | x |\n| 2.1')), [true, 1, []]);
|
|
257
|
+
const over = mark(PHASED.replace('0/3 ', '1/1 '));
|
|
258
|
+
check('the count-above-total notice leads with the phase text', over.unwritten[0].line.startsWith('phase 2: 2 iterations done, total 1; iteration 2.1:'), true);
|
|
259
|
+
}
|
|
260
|
+
{
|
|
261
|
+
const reasonOf = (progress, status = 'in-progress') => { const { plan, root } = fresh({ progress }); const b = snap(root); try { const r = markIteration(plan, '2.1', { status, now: NOW }); return [r.unwritten[0]?.reason ?? 'ok', r.wrote.length ? 'wrote' : isDeepStrictEqual(snap(root), b)]; } catch (e) { return [e.name]; } };
|
|
262
|
+
const row = PROGRESS.match(/\| 2\.1 .*\n/)[0];
|
|
263
|
+
check('a Status cell named like an Object.prototype member is transition-refused, not a TypeError, and nothing is written', ['constructor', '__proto__', 'toString', 'hasOwnProperty'].map((st) => reasonOf(PROGRESS.replace('| in-progress |', `| ${st} |`))), Array(4).fill(['transition-refused', true]));
|
|
264
|
+
const kinds = (progress, iteration, status) => markIteration(fresh({ progress }).plan, iteration, { status, now: NOW }).unwritten.map((u) => [u.reason, u.kind]);
|
|
265
|
+
check('a refused move is a notice, to be reported; a row that is missing is still a record to write', [kinds(PROGRESS.replace('| in-progress |', '| done |'), '2.1', 'in-progress'), kinds(PROGRESS, '9.9', 'done')], [[['transition-refused', 'notice']], [['row-missing', 'iteration-row']]]);
|
|
266
|
+
check('a move out of done, back to not-started and to superseded are each transition-refused by the writer, nothing written', [reasonOf(PROGRESS.replace('| in-progress |', '| done |')), reasonOf(PROGRESS, 'not-started'), reasonOf(PROGRESS, 'superseded')], Array(3).fill(['transition-refused', true]));
|
|
267
|
+
const shapes = { 'a second heading, as a fenced example would add': `${PROGRESS}\n\`\`\`\n## Iteration progress\n\`\`\`\n`, 'a fence in the section': PROGRESS.replace('\n## Follow-ups', '\n```\n```\n\n## Follow-ups'), 'a comment in the section': PROGRESS.replace('\n## Follow-ups', '\n<!-- x -->\n\n## Follow-ups'), 'front matter': `---\ntitle: x\n---\n${PROGRESS}`, 'a stray CR': PROGRESS.replace('Started', 'Sta\rrted') };
|
|
268
|
+
check('findIterationRow refuses a repeated heading, a fence or <!-- in the section, front matter and a stray CR as not-template-shape', Object.values(shapes).map((t) => findIterationRow(t, '2.1').reason), Array(5).fill('not-template-shape'));
|
|
269
|
+
const [heading, fence, title, header] = ['the "## Iteration progress" heading appears 2 times, not once', 'the section holds a code fence or <!--', 'the file does not start with a "# " title, or holds a carriage return', 'the table header or its separator row is not the template\'s'];
|
|
270
|
+
check('findIterationRow names the condition that failed: the heading count, a fence or comment, the title or a CR, the table header', [...Object.values(shapes), PROGRESS.replace('| Iteration |', '| Number |')].map((t) => findIterationRow(t, '2.1').why), [heading, fence, fence, title, title, header]);
|
|
271
|
+
check('the section ends at a heading of any level: a row under a ### heading is missing, not found', reasonOf(PROGRESS.replace(row, '').replace('\n## Follow-ups', `\n### Later\n\n${row}\n## Follow-ups`)), ['row-missing', true]);
|
|
272
|
+
const inv = fresh(); const iv = 'x\u2800y';
|
|
273
|
+
appendDiary(inv.plan, note({ title: `a${iv}`, body: `c${iv}` })); markIteration(inv.plan, '2.1', { status: 'done', reviewed: iv, activity: iv, now: NOW });
|
|
274
|
+
check('the blank braille cell U+2800 is removed from a diary title and body and from the cells of a row', [read(path.join(inv.dir, 'diary.md')).includes('— axy\n'), read(path.join(inv.dir, 'diary.md')).includes('\ncxy\n'), read(path.join(inv.dir, 'progress.md')).includes('| xy '), /\u2800/.test(read(path.join(inv.dir, 'diary.md')) + read(path.join(inv.dir, 'progress.md')))], [true, true, true, false]);
|
|
275
|
+
}
|
|
276
|
+
console.log('== free text cannot forge a heading, a row or a control sequence ==');
|
|
277
|
+
{
|
|
278
|
+
const { plan, dir } = fresh();
|
|
279
|
+
const headingsBefore = headings(read(path.join(dir, 'diary.md')));
|
|
280
|
+
appendDiary(plan, note({ title: `## fake${INVISIBLE} title`, body: `## injected\nline2\r\n### h3\t${INVISIBLE}\u0007end` }));
|
|
281
|
+
const diary = read(path.join(dir, 'diary.md'));
|
|
282
|
+
check('a note "## injected\\nline2" adds exactly one heading and no line of its own', [headings(diary), diary.includes('\n## injected'), diary.includes('injected line2 ### h3 end\n')], [headingsBefore + 1, false, true]);
|
|
283
|
+
check('control, bidi, zero-width, tag and other default-ignorable characters never reach the file; the visible title does', [/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(diary) || [...INVISIBLE].some((c) => diary.includes(c)), diary.includes('— fake title\n')], [false, true]);
|
|
284
|
+
appendDiary(plan, note({ body: 'x'.repeat(500) }));
|
|
285
|
+
check('free text is capped at 300 characters', read(path.join(dir, 'diary.md')).split('\n').includes('x'.repeat(300)), true);
|
|
286
|
+
markIteration(plan, '2.1', { status: 'done', reviewed: 'a | b\n| 9.9 | x', activity: '| z |\n## h', now: NOW });
|
|
287
|
+
const lines = read(path.join(dir, 'progress.md')).split('\n');
|
|
288
|
+
check('pipes and newlines in a cell add neither a column nor a row, and no heading line', [lines.find((l) => l.startsWith('| 2.1')).split('|').length, lines.filter((l) => l.startsWith('|')).length, lines.some((l) => l.startsWith('## h'))], [7, 4, false]);
|
|
289
|
+
}
|
|
290
|
+
console.log('== confinement: closed set of paths, nothing outside, links refused ==');
|
|
291
|
+
{
|
|
292
|
+
const outside = path.join(base, 'outside');
|
|
293
|
+
mkdirSync(outside);
|
|
294
|
+
writeFileSync(path.join(outside, 'diary.md'), diaryOf(2)); writeFileSync(path.join(outside, 'progress.md'), PROGRESS);
|
|
295
|
+
// The three writers as thunks; `unchanged` runs fn and says whether every file under `dir` is byte-identical after.
|
|
296
|
+
const calls = (p) => [() => appendDiary(p, note()), () => markIteration(p, '2.1', { status: 'done', now: NOW }), () => setLastActivity(p, { activity: 'x', now: NOW })];
|
|
297
|
+
const unchanged = (dir, fn) => { const b = snap(dir); const r = fn(); return [r, isDeepStrictEqual(b, snap(dir))]; };
|
|
298
|
+
const refusals = (p) => calls(p).map((f) => f()).map((r) => [r.wrote, r.unwritten[0].reason]);
|
|
299
|
+
const { root, plan } = fresh();
|
|
300
|
+
const bad = ['../x', '..', 'a/b', '', 'A', '-a', 'a'.repeat(65), 'a\n', undefined, 'p1/../p1'];
|
|
301
|
+
check('a traversal or malformed slug is refused with 64 by every writer and nothing in the tree changes', unchanged(base, () => bad.flatMap((slug) => calls({ root, slug }).map(exitOf))), [bad.flatMap(() => Array(3).fill([true, 64])), true]);
|
|
302
|
+
check('an iteration that is not N.M or N.Mx is refused with 64', ['1.2.3', '../1', '1.2\n', '', 'a.b', undefined, '1.2/../x', '../1.2', '1.2b.3', '1.2bc', '1.2B', '1.2.b'].map((it) => exitOf(() => markIteration(plan, it, { status: 'done', now: NOW }))), Array(12).fill([true, 64]));
|
|
303
|
+
const split = fresh({ progress: PROGRESS.replace('| 2.1 | Writers', '| 2.1b | Writers') });
|
|
304
|
+
markIteration(split.plan, '2.1b', { status: 'done', now: NOW });
|
|
305
|
+
check('a split iteration such as 2.1b can be marked', read(path.join(split.dir, 'progress.md')).includes('| 2.1b | Writers | done'), true);
|
|
306
|
+
mkdirSync(path.join(base, 'linked', '.somi', 'plans'), { recursive: true }); symlinkSync(outside, path.join(base, 'linked', '.somi', 'plans', 'p1'));
|
|
307
|
+
check('a plan directory that is a symlink: all three writers write nothing, and the target is untouched', unchanged(base, () => refusals({ root: path.join(base, 'linked'), slug: 'p1' })), [Array(3).fill([[], 'plan-dir-not-a-plain-directory']), true]);
|
|
308
|
+
mkdirSync(path.join(base, 'linked2')); symlinkSync(outside, path.join(base, 'linked2', '.somi'));
|
|
309
|
+
check('a symlinked .somi above the plan directory is refused too', unchanged(base, () => refusals({ root: path.join(base, 'linked2'), slug: 'p1' })), [Array(3).fill([[], 'plan-dir-not-a-plain-directory']), true]);
|
|
310
|
+
const f = fresh({ diary: null, progress: null });
|
|
311
|
+
symlinkSync(path.join(outside, 'diary.md'), path.join(f.dir, 'diary.md')); symlinkSync(path.join(outside, 'progress.md'), path.join(f.dir, 'progress.md'));
|
|
312
|
+
check('diary.md and progress.md that are symlinks are not followed, written or replaced', unchanged(base, () => refusals(f.plan)), [Array(3).fill([[], 'symlink']), true]);
|
|
313
|
+
const g = fresh({ diary: diaryOf(41) });
|
|
314
|
+
writeFileSync(path.join(outside, 'archive.md'), '# keep\n'); symlinkSync(path.join(outside, 'archive.md'), path.join(g.dir, 'diary-archive.md'));
|
|
315
|
+
const [gr, outsideSame] = unchanged(outside, () => appendDiary(g.plan, note()));
|
|
316
|
+
check('a symlinked diary-archive.md is never written: the entry lands, uncompacted, and the skipped compaction is reported', [outsideSame, headings(read(path.join(g.dir, 'diary.md'))), gr.wrote, gr.unwritten.map((u) => u.reason)], [true, 42, ['.somi/plans/p1/diary.md'], ['symlink']]);
|
|
317
|
+
const q = fresh(); const fifo = path.join(q.dir, 'diary.md'); rmSync(fifo);
|
|
318
|
+
if (spawnSync('mkfifo', [fifo]).status !== 0) console.log(' skip (no mkfifo)');
|
|
319
|
+
else { // a child with a timeout: a regression would block in open(), and must fail instead of hanging the suite
|
|
320
|
+
const code = `import { appendDiary } from ${JSON.stringify(pathToFileURL(path.join(LIB, 'loop-notes.mjs')).href)}; console.log(JSON.stringify(appendDiary(${JSON.stringify(q.plan)}, ${JSON.stringify(note())}).unwritten.map((u) => u.reason)));`;
|
|
321
|
+
const b = snap(q.root); const r = spawnSync(process.execPath, ['--input-type=module', '-e', code], { timeout: 5000, encoding: 'utf8' });
|
|
322
|
+
check('a FIFO at diary.md is refused as not-a-regular-file without blocking, and the tree is unchanged', [r.stdout.trim(), snap(q.root)], ['["not-a-regular-file"]', b]);
|
|
323
|
+
}
|
|
324
|
+
const bare = fresh({ diary: '# Diary — p1\n\n> Newest entries at the top.\n' });
|
|
325
|
+
const bw = appendDiary(bare.plan, note());
|
|
326
|
+
check('a diary with only its title and quoted preamble is template shape: the entry is written below the preamble', [bw.wrote, bw.unwritten, read(path.join(bare.dir, 'diary.md')).startsWith('# Diary — p1\n\n> Newest entries at the top.\n\n## 2026-10-29 09:30 — Writers done\n'), headings(read(path.join(bare.dir, 'diary.md')))], [['.somi/plans/p1/diary.md'], [], true, 1]);
|
|
327
|
+
const bare2 = fresh({ diary: '# Diary — p1\n' }); appendDiary(bare2.plan, note()); appendDiary(bare2.plan, note({ title: 'Next' }));
|
|
328
|
+
check('a title-only diary takes an entry, and the next goes above it', read(path.join(bare2.dir, 'diary.md')).split('\n').filter((l) => l.startsWith('## ')).map((l) => l.split(' — ')[1]), ['Next', 'Writers done']);
|
|
329
|
+
const d = fresh({ diary: '# Diary\n\nno entries here\n' });
|
|
330
|
+
check('a diary with no entry headings is left byte-identical and the summary of the entry (category, title, body) comes back', unchanged(base, () => appendDiary(d.plan, note()).unwritten.map((u) => [u.reason, u.line])), [[['not-template-shape', 'note — Writers done — two writers']], true]);
|
|
331
|
+
}
|
|
332
|
+
console.log('== atomic write: a failed archive write must not drop the entries it was to hold ==');
|
|
333
|
+
{
|
|
334
|
+
const { plan, dir } = fresh({ diary: diaryOf(41) });
|
|
335
|
+
const before = read(path.join(dir, 'diary.md'));
|
|
336
|
+
const realRename = fs.renameSync;
|
|
337
|
+
fs.renameSync = (from, to) => { if (path.basename(to) === 'diary-archive.md') throw Object.assign(new Error('no space'), { code: 'ENOSPC' }); return realRename(from, to); };
|
|
338
|
+
let r;
|
|
339
|
+
try { r = appendDiary(plan, note({ title: 'N' })); } finally { fs.renameSync = realRename; }
|
|
340
|
+
const diary = read(path.join(dir, 'diary.md'));
|
|
341
|
+
check('the archive write fails: the diary is written uncompacted (every entry kept), one write-failed item for the archive, no temp or archive file', [headings(diary), diary.includes(before.slice(PRE.length)), r.wrote, r.unwritten.map((u) => [u.file, u.reason, u.code]), readdirSync(dir).sort()], [42, true, ['.somi/plans/p1/diary.md'], [['diary-archive.md', 'write-failed', 'ENOSPC']], ['diary.md', 'progress.md']]);
|
|
342
|
+
}
|
|
343
|
+
console.log('== atomic write: a failed write is reported, leaves the old file and no temp ==');
|
|
344
|
+
if (typeof process.getuid === 'function' && process.getuid() !== 0) {
|
|
345
|
+
const { plan, dir } = fresh();
|
|
346
|
+
const before = snap(dir);
|
|
347
|
+
chmodSync(dir, 0o555);
|
|
348
|
+
let r; let threw = false;
|
|
349
|
+
try { r = [appendDiary(plan, note()), markIteration(plan, '2.1', { status: 'done', now: NOW }), setLastActivity(plan, { activity: 'x', now: NOW })]; } catch { threw = true; }
|
|
350
|
+
chmodSync(dir, 0o755);
|
|
351
|
+
check('with the plan directory unwritable no writer throws: each returns write-failed with the errno code and its line, and the tree is as before', [threw, (r ?? []).map((x) => [x.wrote, x.unwritten.map((u) => [u.file, u.reason, u.code, u.line.length > 0, u.line.includes('EACCES')])]), snap(dir)], [false, [[[], [['diary.md', 'write-failed', 'EACCES', true, false]]], [[], [['progress.md', 'write-failed', 'EACCES', true, false]]], [[], [['progress.md', 'write-failed', 'EACCES', true, false]]]], before]);
|
|
352
|
+
const big = fresh({ diary: diaryOf(41) });
|
|
353
|
+
const bigBefore = snap(big.dir);
|
|
354
|
+
chmodSync(big.dir, 0o555);
|
|
355
|
+
let br; let bthrew = false;
|
|
356
|
+
try { br = appendDiary(big.plan, note()); } catch { bthrew = true; }
|
|
357
|
+
chmodSync(big.dir, 0o755);
|
|
358
|
+
check('a compacting append in an unwritable directory reports both the archive and the diary as write-failed, throws nothing, leaves no temp file', [bthrew, br?.wrote, br?.unwritten.map((u) => [u.file, u.reason, u.code]), snap(big.dir)], [false, [], [['diary-archive.md', 'write-failed', 'EACCES'], ['diary.md', 'write-failed', 'EACCES']], bigBefore]);
|
|
359
|
+
} else console.log(' skip (running as root: a mode bit does not stop the write)');
|
|
360
|
+
|
|
361
|
+
console.log('== the writers in sequence on a progress.md a plan opened: Last activity under Status, the phase done count ==');
|
|
362
|
+
{
|
|
363
|
+
const fixture = read(path.join(LIB, '..', '..', 'tests', 'evals', 'fixtures', 'task02-code', '_somi', 'plans', 'expired-token', 'progress.md'));
|
|
364
|
+
const { plan, dir } = fresh({ progress: fixture });
|
|
365
|
+
const results = [markIteration(plan, '1.1', { status: 'in-progress', now: NOW }), markIteration(plan, '1.1', { status: 'done', reviewed: 'approve', activity: 'loop done', now: NOW }), setLastActivity(plan, { activity: 'loop done for iteration 1.1', now: NOW })];
|
|
366
|
+
const after = read(path.join(dir, 'progress.md'));
|
|
367
|
+
check('on the fixture progress.md the writers (markIteration twice, then setLastActivity) run clean: Last activity lands under Status, 0/1 becomes 1/1, row 1.1 is done', [results.flatMap((x) => x.unwritten), after.includes('`in-progress`\n\n**Last activity**: 2026-10-29 — loop done for iteration 1.1\n\n## Phase progress'), after.includes('| in-progress | 1/1 |'), /\| 1\.1 \| Reject an expired token \| done +\| approve +\|/.test(after)], [[], true, true, true]);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
console.log(`loop notes tests: ${pass} ok, ${fail} failed`);
|
|
371
|
+
process.exit(fail === 0 ? 0 : 1);
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Tests of the CLI `step` subcommand of scripts/somi-loop.mjs, run as a process: the steps and the primitives share one
|
|
3
|
+
// state, each gate answers with its exit code and the response alone, and an internal error (70) leaves the stderr
|
|
4
|
+
// empty and goes to a log file under the state directory, not through a link.
|
|
5
|
+
// Run by tests/scripts/loop-engine.sh.
|
|
6
|
+
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
9
|
+
import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { tmpdir } from 'node:os';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
14
|
+
import { runStep } from '../../../scripts/lib/loop-step.mjs';
|
|
15
|
+
import { LOG_MAX, stepLog } from '../../../scripts/lib/loop-step-kit.mjs';
|
|
16
|
+
|
|
17
|
+
const CLI = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'scripts', 'somi-loop.mjs');
|
|
18
|
+
let pass = 0; let fail = 0;
|
|
19
|
+
const check = (name, got, want) => {
|
|
20
|
+
if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
|
|
21
|
+
};
|
|
22
|
+
const tmp = mkdtempSync(path.join(tmpdir(), 'loop-step-cli-'));
|
|
23
|
+
process.on('exit', () => rmSync(tmp, { recursive: true, force: true }));
|
|
24
|
+
|
|
25
|
+
const ROWS = '# Progress — p1\n\n## Iteration progress\n\n| Iteration | Title | Status | Reviewed | Last activity |\n|---|---|---|---|---|\n| 1.1 | one | not-started | — | — |\n\n**Last activity**: 2026-10-28 — seeded\n';
|
|
26
|
+
const DIARY = '# Diary — p1\n\n---\n\n## 2026-10-28 10:00 — Plan\n\n**Category**: `note`\n**Phase**: 1\n\nbody\n\n---\n\n';
|
|
27
|
+
const FINDING = JSON.stringify([{ file: 'f1.js', symbol: 's', title: 'finding 1 here', severity: 'Major', confidence: 'High' }]);
|
|
28
|
+
const ENV = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^(SOMI_|CLAUDE_)/.test(k)));
|
|
29
|
+
let n = 0;
|
|
30
|
+
function repo() {
|
|
31
|
+
const root = path.join(tmp, `r${n++}`); mkdirSync(root);
|
|
32
|
+
const git = (...a) => execFileSync('git', ['-C', root, '-c', 'user.name=t', '-c', 'user.email=t@t', ...a]);
|
|
33
|
+
git('init', '-q'); writeFileSync(path.join(root, 'a.js'), '1\n'); git('add', 'a.js'); git('commit', '-q', '-m', 'base');
|
|
34
|
+
mkdirSync(path.join(root, '.somi', 'plans', 'p1', 'phases'), { recursive: true });
|
|
35
|
+
writeFileSync(path.join(root, '.somi', 'plans', 'p1', 'diary.md'), DIARY); writeFileSync(path.join(root, '.somi', 'plans', 'p1', 'progress.md'), ROWS);
|
|
36
|
+
const sf = path.join(root, '.somi', 'somi-state', 'loop', 'p1.1.1.json');
|
|
37
|
+
return { root, sf, state: () => JSON.parse(readFileSync(sf, 'utf8')), file: (f, t) => writeFileSync(path.join(root, f), t) };
|
|
38
|
+
}
|
|
39
|
+
const run = (r, argv, env = {}) => { const x = spawnSync('node', [CLI, ...argv], { cwd: r.root, encoding: 'utf8', env: { ...ENV, CLAUDE_PROJECT_DIR: r.root, SOMI_GLOBAL_CONFIG: '', ...env } }); return { code: x.status, out: x.stdout, err: x.stderr, json: (() => { try { return JSON.parse(x.stdout); } catch { return null; } })() }; };
|
|
40
|
+
const slug = ['--slug', 'p1', '--iteration', '1.1'];
|
|
41
|
+
const prim = (r, cmd, ...more) => run(r, [cmd, ...slug, ...more]);
|
|
42
|
+
const step = (r, name, ...more) => run(r, ['step', name, ...slug, ...more]);
|
|
43
|
+
const tree = (root) => Object.fromEntries(readdirSync(root, { recursive: true }).filter((f) => !f.startsWith('.git')).sort().map((f) => [f, lstatSync(path.join(root, f)).isFile() ? createHash('sha256').update(readFileSync(path.join(root, f))).digest('hex') : 'dir']));
|
|
44
|
+
// What the comparison keeps of a loop state: times and tree ids dropped, the step cursor ignored; `finished` only as set.
|
|
45
|
+
const norm = (r) => { const s = r.state(); return { st: s.status, fin: typeof s.finished, loop: s.loop, files: s.iteration_files, rm: s.review_min, co: s.cap_overrides, pass: s.pass, caps: s.caps, d: (s.dispatches ?? []).map(({ at, ...d }) => d), h: s.history.map(({ at, tree: t, ...h }) => h) }; };
|
|
46
|
+
const EDIT = '1\n2\n3\n';
|
|
47
|
+
const REVIEW = ['--reviewers', 'somi-reviewer', '--verdict', 'approve', '--blockers', '0', '--majors', '0', '--review', 'r1.md'];
|
|
48
|
+
|
|
49
|
+
console.log('== the steps and the primitives share one state ==');
|
|
50
|
+
{
|
|
51
|
+
const a = repo(); prim(a, 'init', '--files', 'a.js'); prim(a, 'pass'); prim(a, 'record-dispatch', '--agent', 'somi-coder'); a.file('a.js', EDIT);
|
|
52
|
+
prim(a, 'check-diff'); prim(a, 'review-scope'); prim(a, 'record-dispatch', '--agent', 'somi-reviewer'); prim(a, 'record-pass', '--verdict', 'approve'); prim(a, 'finish', '--status', 'done');
|
|
53
|
+
const b = repo(); prim(b, 'init', '--files', 'a.js'); const bo = step(b, 'open', '--files', 'a.js'); b.file('a.js', EDIT); const ba = step(b, 'after-code', '--agent', 'somi-coder');
|
|
54
|
+
prim(b, 'record-dispatch', '--agent', 'somi-reviewer'); prim(b, 'record-pass', '--verdict', 'approve'); prim(b, 'finish', '--status', 'done');
|
|
55
|
+
const c = repo(); const co = step(c, 'open', '--files', 'a.js'); c.file('a.js', EDIT); step(c, 'after-code', '--agent', 'somi-coder');
|
|
56
|
+
prim(c, 'record-dispatch', '--agent', 'somi-reviewer'); prim(c, 'record-pass', '--verdict', 'approve'); prim(c, 'finish', '--status', 'done');
|
|
57
|
+
const d = repo(); step(d, 'open', '--files', 'a.js'); d.file('a.js', EDIT); step(d, 'after-code', '--agent', 'somi-coder'); const dr = step(d, 'after-review', ...REVIEW); const dc = step(d, 'close', '--status', 'done');
|
|
58
|
+
check('an init by the primitive, then open and after-code by the steps, then the primitives, ends in the state of a loop run by primitives alone', [norm(b), bo.code, ba.code], [norm(a), 0, 0]);
|
|
59
|
+
check('the reverse (the step opens the loop, the primitives record and finish it) ends in the same state', [norm(c), co.code], [norm(a), 0]);
|
|
60
|
+
check('all four steps run by the CLI, reviewers as a comma list, end in the same state, and each prints one JSON line', [norm(d), dr.code, dc.code, [bo, dr, dc].map((x) => x.out.trim().split('\n').length), dc.json.next], [norm(a), 0, 0, [1, 1, 1], 'summarise']);
|
|
61
|
+
const e = repo(); step(e, 'open', '--files', 'a.js'); e.file('a.js', EDIT); step(e, 'after-code', '--agent', 'somi-coder'); step(e, 'after-review', ...REVIEW.map((v) => (v === 'somi-reviewer' ? 'somi-reviewer,somi-security-reviewer' : v)));
|
|
62
|
+
check('--reviewers takes a comma-separated list, each reviewer dispatched', e.state().dispatches.map((x) => x.agent), ['somi-coder', 'somi-reviewer', 'somi-security-reviewer']);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
console.log('== the gates exit with their codes and print the response alone ==');
|
|
66
|
+
{
|
|
67
|
+
const two = repo(); prim(two, 'init', '--files', 'a.js', '--max-passes', '1'); prim(two, 'pass'); prim(two, 'record-pass', '--verdict', 'request-changes', '--majors', '1'); const x2 = step(two, 'open');
|
|
68
|
+
const three = repo(); step(three, 'open', '--files', 'a.js', '--diff-cap', '1'); three.file('a.js', '1\n'.repeat(9)); const x3 = step(three, 'after-code', '--agent', 'somi-coder');
|
|
69
|
+
const four = repo(); mkdirSync(path.join(four.root, '.somi', 'somi-state', 'run'), { recursive: true }); writeFileSync(path.join(four.root, '.somi', 'somi-state', 'run', 'p1.json'), JSON.stringify({ started: '2020-01-01T00:00:00.000Z', max_minutes: 1 })); const x4 = step(four, 'open', '--files', 'a.js');
|
|
70
|
+
const five = repo(); const round = () => { step(five, 'open', '--files', 'a.js'); five.file('a.js', `${five.state().pass}\n`.repeat(3)); step(five, 'after-code', '--agent', 'somi-coder'); return step(five, 'after-review', '--reviewers', 'somi-reviewer', '--verdict', 'request-changes', '--blockers', '0', '--majors', '1', '--review', 'r1.md', '--findings', FINDING); };
|
|
71
|
+
round(); const x5 = round();
|
|
72
|
+
const shape = (x) => [x.code, x.json?.exit, x.json?.stop_reason, x.json?.next, x.json?.close_args?.status, x.err, x.out.trim().split('\n').length];
|
|
73
|
+
check('max passes is exit 2 with the response on stdout and nothing on stderr', shape(x2), [2, 2, 'max-passes-exceeded', 'close', 'stopped-max-passes-exceeded', '', 1]);
|
|
74
|
+
check('the diff cap is exit 3', shape(x3), [3, 3, 'diff-cap-exceeded', 'close', 'stopped-diff-cap-exceeded', '', 1]);
|
|
75
|
+
check('a spent time budget is exit 4', shape(x4), [4, 4, 'time-budget', 'close', 'stopped-time-budget', '', 1]);
|
|
76
|
+
check('the circuit breaker is exit 5', shape(x5), [5, 5, 'circuit-breaker', 'close', 'stopped-circuit-breaker', '', 1]);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
console.log('== an internal error: exit 70, the fixed text and an empty stderr ==');
|
|
80
|
+
{
|
|
81
|
+
// A state directory the step cannot create a file in, as root too: /proc/self (Linux).
|
|
82
|
+
const FIXED = 'internal error: the step did not complete; retry it, and report it if it repeats';
|
|
83
|
+
const r = repo();
|
|
84
|
+
if (existsSync('/proc/self')) {
|
|
85
|
+
const y = run(r, ['step', 'open', ...slug, '--files', 'a.js'], { SOMI_LOOP_STATE_DIR: '/proc/self' });
|
|
86
|
+
check('a state file that cannot be saved is exit 70 with only the fixed response (no error name, path or stack) and nothing on stderr', [y.code, y.json?.exit, y.json?.error, y.err, /EACCES|ENOENT|stack|\.mjs|\/proc/.test(y.out)], [70, 70, FIXED, '', false]);
|
|
87
|
+
}
|
|
88
|
+
if (process.getuid?.() !== 0) { // chmod does not bind root: the log writes are covered below without it
|
|
89
|
+
const q = repo(); prim(q, 'init', '--files', 'a.js'); chmodSync(q.sf, 0o444);
|
|
90
|
+
const log = path.join(q.root, '.somi', 'somi-state', 'loop', 'step-errors.log'); const z = step(q, 'open', '--files', 'a.js');
|
|
91
|
+
const lines = existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n') : [];
|
|
92
|
+
check('the error is one JSON line in step-errors.log, naming the step and the error', [z.code, z.err, lines.length, JSON.parse(lines[0] ?? '{}').somi_loop_step, typeof JSON.parse(lines[0] ?? '{}').error], [70, '', 1, 'open', 'string']);
|
|
93
|
+
chmodSync(q.sf, 0o644);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
console.log('== the error log: confined, capped, rotated ==');
|
|
98
|
+
{
|
|
99
|
+
const home = () => { const root = path.join(tmp, `l${n++}`); mkdirSync(root); return { root, dir: path.join(root, '.somi', 'somi-state', 'loop') }; };
|
|
100
|
+
const read = (f) => readFileSync(f, 'utf8');
|
|
101
|
+
const h = home(); const w = stepLog(h.root, h.dir, false); w('{"a":1}'); w('{"b":2}');
|
|
102
|
+
check('the log lives under the default state directory, one line per error', read(path.join(h.dir, 'step-errors.log')), '{"a":1}\n{"b":2}\n');
|
|
103
|
+
|
|
104
|
+
const f = home(); mkdirSync(f.dir, { recursive: true }); execFileSync('mkfifo', [path.join(f.dir, 'step-errors.log')]);
|
|
105
|
+
const hung = spawnSync(process.execPath, ['--input-type=module', '-e', `import { stepLog } from ${JSON.stringify(path.join(path.dirname(CLI), 'lib', 'loop-step-kit.mjs'))}; stepLog(${JSON.stringify(f.root)}, ${JSON.stringify(f.dir)}, false)('{"a":1}');`], { timeout: 5000, encoding: 'utf8' });
|
|
106
|
+
check('a FIFO at the log path is left alone and does not hang the step', [hung.status, hung.signal, lstatSync(path.join(f.dir, 'step-errors.log')).isFIFO()], [0, null, true]);
|
|
107
|
+
|
|
108
|
+
const l = home(); mkdirSync(l.dir, { recursive: true }); const away = path.join(tmp, `away${n}.txt`); writeFileSync(away, 'untouched'); symlinkSync(away, path.join(l.dir, 'step-errors.log'));
|
|
109
|
+
stepLog(l.root, l.dir, false)('{"a":1}');
|
|
110
|
+
check('a link at the log path is not followed', read(away), 'untouched');
|
|
111
|
+
|
|
112
|
+
const p = home(); mkdirSync(path.join(p.root, '.somi'), { recursive: true }); const elsewhere = path.join(tmp, `elsewhere${n}`); mkdirSync(path.join(elsewhere, 'loop'), { recursive: true }); symlinkSync(elsewhere, path.join(p.root, '.somi', 'somi-state'));
|
|
113
|
+
stepLog(p.root, p.dir, false)('{"a":1}');
|
|
114
|
+
check('a link in the default state directory\'s path is not walked through: nothing is written behind it', readdirSync(path.join(elsewhere, 'loop')), []);
|
|
115
|
+
|
|
116
|
+
const x = home(); const wx = stepLog(x.root, x.dir, true); const log = path.join(x.dir, 'step-errors.log');
|
|
117
|
+
wx('{"old":1}'); writeFileSync(log, `${'x'.repeat(LOG_MAX - 20)}\n`); const target = path.join(tmp, `gen${n}.txt`); writeFileSync(target, 'untouched'); symlinkSync(target, `${log}.1`);
|
|
118
|
+
wx(`{"new":"${'y'.repeat(40)}"}`);
|
|
119
|
+
check('a line that would pass the cap moves the log to .1 (replacing a link there without following it) and starts a new log, which stays within the cap', [read(log).startsWith('{"new"'), read(`${log}.1`).startsWith('xxxx'), lstatSync(`${log}.1`).isSymbolicLink(), read(target), lstatSync(log).size <= LOG_MAX], [true, true, false, 'untouched', true]);
|
|
120
|
+
|
|
121
|
+
const seen = []; const big = { get now() { const e = new Error('x'); e.name = 'N'.repeat(1000); e.stack = 'S'.repeat(100000); throw e; }, log: (line) => seen.push(line) };
|
|
122
|
+
runStep(big, { step: 'open', slug: 'p1', iteration: '1.1', files: 'a.js' });
|
|
123
|
+
const rec = JSON.parse(seen[0] ?? '{}');
|
|
124
|
+
check('the stack and the error name are cut before the line is made, so the line is whole JSON within the cap', [seen.length, rec.stack?.length, rec.error?.length, Buffer.byteLength(seen[0] ?? '') < LOG_MAX / 8], [1, 4000, 100, true]);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
console.log('== usage errors: the same JSON refusal on stdout, 64, stderr empty, nothing written ==');
|
|
128
|
+
{
|
|
129
|
+
const r = repo(); const before = tree(r.root);
|
|
130
|
+
const bad = [['an unknown flag', ['step', 'open', '--nope', '1']], ['a flag without a value', ['step', 'open', '--slug']], ['a repeated flag', ['step', 'open', '--slug', 'p1', '--slug', 'p1']], ['findings that are not JSON', ['step', 'after-review', '--slug', 'p1', '--findings', '[x']], ['a value in place of a flag', ['step', 'open', 'p1']]];
|
|
131
|
+
check('each is refused 64 with the refusal on stdout (ok false, the step, the reason), one line, and an empty stderr', bad.map(([, argv]) => { const x = run(r, argv); return [x.code, x.json?.ok, x.json?.exit, x.json?.step, typeof x.json?.error, x.err, x.out.trim().split('\n').length]; }), bad.map(([, argv]) => [64, false, 64, argv[1], 'string', '', 1]));
|
|
132
|
+
const esc = run(r, ['step', 'open', `--\u001b[31m${'z'.repeat(500)}`, '1']);
|
|
133
|
+
check('the flag in the message is cut and cleaned: no control character, at most 40 characters of it', [esc.json?.error.includes('\u001b'), esc.json?.error.length < 120], [false, true]);
|
|
134
|
+
const gen = run(r, ['pass', '--slug', 'p1', `--\u001b[31m${'z'.repeat(500)}`]);
|
|
135
|
+
check('the same holds for the primitives\' usage error', [gen.code, gen.err.includes('\u001b'), gen.err.length < 120], [64, false, true]);
|
|
136
|
+
check('an unknown step and a missing argument are refused inside the step: 64 and the field in the response', [step(r, 'nope').json?.exit, run(r, ['step', 'open', '--slug', 'p1', '--iteration', '1.1']).json?.error?.startsWith('files:')], [64, true]);
|
|
137
|
+
check('nothing was written by any refusal', tree(r.root), before);
|
|
138
|
+
check('the header comment lists exit 70 and the step subcommand', ['70 internal error', 'step <open|after-code|after-review|close|status>'].map((t) => readFileSync(CLI, 'utf8').includes(t)), [true, true]);
|
|
139
|
+
}
|
|
140
|
+
console.log(`loop step cli tests: ${pass} ok, ${fail} failed`);
|
|
141
|
+
process.exit(fail === 0 ? 0 : 1);
|