Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/test-plugin-install.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ jobs:
- name: Test reference-link validator
run: node --test scripts/validate-reference-links-test.js

- name: Test floor-guard reference
run: node --test scripts/floor-guard-reference-test.js

- name: Test session-start hook payload
run: bash hooks/session-start-test.sh

Expand Down
210 changes: 210 additions & 0 deletions scripts/floor-guard-reference-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
#!/usr/bin/env node

'use strict';

// Contract test for skills/constraint-driven-development/references/floor-guard.md.
// The fenced `js` block is extracted unchanged and run, with real git, against fourteen
// small fixtures: each is a fresh repository with one source file, one test file and a
// CONSTRAINTS.md carrying a floor bullet, a coverage minimum, a bundle maximum and an
// Exceptions table. Loosening moves must exit 1, tightening and no-op moves must exit 0.

const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const { after, before, test } = require('node:test');

const REFERENCE = path.join(
__dirname, '..', 'skills', 'constraint-driven-development', 'references', 'floor-guard.md',
);
const CONSTRAINTS = [
'# Constraints',
'',
'Last reviewed: 2026-08-08 by @owner',
'',
'## Floor',
'- No skipped tests.',
'- Latency: p95 under 200 ms and p99 under 900 ms.',
'',
'| Dimension | Rule |',
'|---|---|',
'| Coverage | >= 80% |',
'| Bundle | <= 200 KB |',
'',
'## Exceptions',
'',
'| ID | Rule | Owner | Expires |',
'|---|---|---|---|',
'| W1 | no-explicit-any | @owner | 2026-11-01 |',
'',
].join('\n');

let scratch;
let guard;
const sandboxes = [];

before(() => {
scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-skills-floor-guard-test-'));
const source = fs.readFileSync(REFERENCE, 'utf8');
const match = source.match(/```js\n([\s\S]*?)\n```/);
assert.ok(match, 'floor-guard.md must contain one fenced js block');
guard = path.join(scratch, 'floor-guard.mjs');
fs.writeFileSync(guard, match[1] + '\n');
});

after(() => {
for (const dir of sandboxes) fs.rmSync(dir, { recursive: true, force: true });
if (scratch) fs.rmSync(scratch, { recursive: true, force: true });
});

function git(cwd, ...args) {
const result = spawnSync('git', args, {
cwd,
encoding: 'utf8',
env: {
...process.env,
GIT_AUTHOR_NAME: 'Floor Guard Test',
GIT_AUTHOR_EMAIL: 'floor-guard@example.invalid',
GIT_COMMITTER_NAME: 'Floor Guard Test',
GIT_COMMITTER_EMAIL: 'floor-guard@example.invalid',
GIT_CONFIG_GLOBAL: '/dev/null',
},
});
assert.equal(result.status, 0, `git ${args.join(' ')} failed: ${result.stderr}`);
return result.stdout;
}

function makeRepo() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-skills-floor-guard-fixture-'));
sandboxes.push(root);
git(root, 'init', '-q');
fs.writeFileSync(path.join(root, 'app.js'), 'module.exports = 1;\n');
fs.writeFileSync(
path.join(root, 'app.test.js'),
"const assert = require('assert');\nassert.equal(require('./app'), 1);\n",
);
fs.writeFileSync(path.join(root, 'CONSTRAINTS.md'), CONSTRAINTS);
git(root, 'add', '.');
git(root, 'commit', '-qm', 'baseline');
return root;
}

function editConstraints(root, from, to) {
const file = path.join(root, 'CONSTRAINTS.md');
const text = fs.readFileSync(file, 'utf8');
assert.ok(text.includes(from), `fixture CONSTRAINTS.md must contain ${JSON.stringify(from)}`);
fs.writeFileSync(file, text.replace(from, to));
}

function runGuard(root) {
return spawnSync(process.execPath, [guard, '--base', 'HEAD'], { cwd: root, encoding: 'utf8' });
}

const cases = [
['unchanged repository is clean', 0, () => {}],
['a suppression added to a tracked file is a violation', 1, (root) => {
fs.writeFileSync(path.join(root, 'app.js'), '// @ts-ignore\nmodule.exports = 1;\n');
}],
['a suppression in a new untracked file is a violation', 1, (root) => {
fs.writeFileSync(path.join(root, 'new.js'), '// @ts-ignore\nmodule.exports = 1;\n');
}],
['a skipped test in a new untracked file is a violation', 1, (root) => {
fs.writeFileSync(path.join(root, 'new.test.js'), "test.skip('regression', () => {});\n");
}],
['a suppression in a staged new file is a violation', 1, (root) => {
fs.writeFileSync(path.join(root, 'new.js'), '// @ts-ignore\nmodule.exports = 1;\n');
git(root, 'add', '-A');
}],
['a deleted test file is a violation', 1, (root) => {
fs.unlinkSync(path.join(root, 'app.test.js'));
}],
['a staged deleted test file is a violation', 1, (root) => {
fs.unlinkSync(path.join(root, 'app.test.js'));
git(root, 'add', '-A');
}],
['an assertion removed from a surviving test file is a violation', 1, (root) => {
fs.writeFileSync(path.join(root, 'app.test.js'), "const assert = require('assert');\n");
}],
['lowering a minimum is a violation', 1, (root) => {
editConstraints(root, '| Coverage | >= 80% |', '| Coverage | >= 60% |');
}],
['raising a minimum is silent', 0, (root) => {
editConstraints(root, '| Coverage | >= 80% |', '| Coverage | >= 90% |');
}],
['raising a maximum is a violation', 1, (root) => {
editConstraints(root, '| Bundle | <= 200 KB |', '| Bundle | <= 300 KB |');
}],
['lowering a maximum is silent', 0, (root) => {
editConstraints(root, '| Bundle | <= 200 KB |', '| Bundle | <= 150 KB |');
}],
['deleting one threshold from a rule is a violation', 1, (root) => {
editConstraints(root, 'p95 under 200 ms and p99 under 900 ms.', 'p95 under 200 ms.');
}],
['a number inserted before a threshold is silent', 0, (root) => {
editConstraints(root, '| Coverage | >= 80% |', '| Coverage | per ADR 7, >= 80% |');
}],
['adding a threshold to a rule is silent', 0, (root) => {
editConstraints(root, '| Bundle | <= 200 KB |', '| Bundle | <= 200 KB, <= 60 KB gzipped |');
}],
['a deleted floor rule is a violation', 1, (root) => {
editConstraints(root, '- No skipped tests.\n', '');
}],
['a new exception row is a violation', 1, (root) => {
const file = path.join(root, 'CONSTRAINTS.md');
fs.appendFileSync(file, '| W2 | temporary waiver | @owner | 2026-10-01 |\n');
}],
];

for (const [name, expectedExit, mutate] of cases) {
test(`floor guard: ${name}`, () => {
const root = makeRepo();
mutate(root);
const result = runGuard(root);
assert.equal(
result.status, expectedExit,
`expected exit ${expectedExit}, got ${result.status}\nstdout: ${result.stdout}\nstderr: ${result.stderr}`,
);
});
}

test('floor guard: a removed exception row is silent', () => {
const root = makeRepo();
editConstraints(root, '| W1 | no-explicit-any | @owner | 2026-11-01 |\n', '');
const result = runGuard(root);
assert.equal(result.status, 0, result.stderr);
});

test('floor guard: a missing merge base exits 2, never 0', () => {
const root = makeRepo();
const result = spawnSync(process.execPath, [guard, '--base', 'no-such-ref'], {
cwd: root, encoding: 'utf8',
});
assert.equal(result.status, 2, result.stderr);
});

test('floor guard: a threshold with no readable direction is reported when it changes', () => {
const root = makeRepo();
editConstraints(root, '| W1 | no-explicit-any | @owner | 2026-11-01 |', '| W1 | no-explicit-any | @owner | 2027-11-01 |');
const result = runGuard(root);
assert.equal(result.status, 1, result.stderr);
assert.match(result.stderr, /threshold-changed/);
});

test('floor guard: a renamed rule is reported as removed, with a note that its label may have changed', () => {
const root = makeRepo();
editConstraints(root, '| Coverage | >= 80% |', '| Code coverage | >= 80% |');
const result = runGuard(root);
assert.equal(result.status, 1, result.stderr);
assert.match(result.stderr, /\[rule-removed\]/);
assert.match(result.stderr, /label changed/);
});

test('floor guard: a threshold that loses its direction words is reported as removed, with a note saying so', () => {
const root = makeRepo();
editConstraints(root, '| Coverage | >= 80% |', '| Coverage | 80% |');
const result = runGuard(root);
assert.equal(result.status, 1, result.stderr);
assert.match(result.stderr, /\[threshold-removed\]/);
assert.match(result.stderr, /direction words/);
});
115 changes: 92 additions & 23 deletions skills/constraint-driven-development/references/floor-guard.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,33 +25,49 @@ const base = (() => {
return i > -1 ? process.argv[i + 1] : 'origin/main';
})();

const git = (args) => {
try { return execFileSync('git', args, { encoding: 'utf8' }); }
catch { return null; }
// `git diff --no-index` exits 1 whenever the two sides differ, which is the normal case for a
// new file, so that output is kept. Any other failure is null, and null never reads as clean.
const git = (args, { diffExit = false } = {}) => {
try { return execFileSync('git', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); }
catch (e) { return diffExit && e.status === 1 && typeof e.stdout === 'string' ? e.stdout : null; }
};
const bail = (msg) => { console.error('floor-guard: ' + msg); process.exit(2); };

// Merge base; bail to exit 2 rather than pretending a shallow/rootless clone is clean.
const mergeBase = git(['merge-base', base, 'HEAD'])?.trim();
if (!mergeBase) { console.error('floor-guard: no merge base against ' + base); process.exit(2); }
if (!mergeBase) bail('no merge base against ' + base);

// Unified diff plus untracked files (git diff alone cannot see new files).
const tracked = git(['diff', '--unified=0', mergeBase, '--']) ?? '';
const untracked = (git(['ls-files', '--others', '--exclude-standard']) ?? '')
.split('\n').filter(Boolean)
.map((f) => git(['diff', '--no-index', '--unified=0', '/dev/null', f]) ?? '')
.join('\n');
const tracked = git(['diff', '--unified=0', mergeBase, '--']);
if (tracked === null) bail('could not diff against ' + mergeBase);
const untrackedFiles = git(['ls-files', '--others', '--exclude-standard']);
if (untrackedFiles === null) bail('could not list untracked files');
const untracked = untrackedFiles.split('\n').filter(Boolean).map((f) => {
const d = git(['diff', '--no-index', '--unified=0', '/dev/null', f], { diffExit: true });
if (d === null) bail('could not diff untracked file ' + f);
return d;
}).join('\n');
const diff = tracked + '\n' + untracked;

const added = [], removed = [];
let file = '';
// Walk the diff. Both headers name the file, so a deletion (`+++ /dev/null`) keeps its name.
const added = [], removed = [], deleted = [];
const pathOf = (s) => s.replace(/^[ab]\//, '');
let file = '', oldFile = '';
for (const line of diff.split('\n')) {
if (line.startsWith('+++ ')) file = line.slice(6);
if (line.startsWith('--- ')) oldFile = pathOf(line.slice(4));
else if (line.startsWith('+++ ')) {
const newFile = pathOf(line.slice(4));
file = newFile === '/dev/null' ? oldFile : newFile;
if (newFile === '/dev/null') deleted.push(file);
}
else if (line.startsWith('+') && !line.startsWith('+++')) added.push({ file, text: line.slice(1) });
else if (line.startsWith('-') && !line.startsWith('---')) removed.push({ file, text: line.slice(1) });
}

const findings = [];
const flag = (rule, f, text) => findings.push({ rule, file: f, text: text.trim().slice(0, 120) });
const isTest = (f) => /\.(test|spec)\.|_test\.|test_/.test(f);
const isConstraints = (f) => /CONSTRAINTS\.md$/.test(f);

// 1. Silenced checker — extend this list for your ecosystem.
const SUPPRESSIONS = /@ts-ignore|@ts-nocheck|eslint-disable|biome-ignore|# *noqa|# *type: *ignore|istanbul ignore|nosemgrep|gitleaks:allow|Stryker disable/;
Expand All @@ -64,30 +80,83 @@ for (const { file, text } of added) {
if (SUPPRESSIONS.test(text)) flag('silenced-checker', file, text);
if (STUBS.test(text)) flag('unfinished-work', file, text);
if (SKIPS.test(text)) flag('test-made-easier', file, text);
if (/CONSTRAINTS\.md$/.test(file) && /^\| *(W|E)\d+ *\|/.test(text)) flag('new-exception', file, text);
if (isConstraints(file) && /^\| *(W|E)\d+ *\|/.test(text)) flag('new-exception', file, text);
}

// 2b. Assertion removed from a test file that still exists.
// 2b. A test file deleted, or an assertion removed from a test file that still exists.
for (const f of deleted) if (isTest(f)) flag('test-deleted', f, 'file deleted');
for (const { file, text } of removed) {
if (/\.(test|spec)\.|_test\.|test_/.test(file) && /\b(expect|assert|should)\b/.test(text)) {
if (isTest(file) && !deleted.includes(file) && /\b(expect|assert|should)\b/.test(text)) {
flag('assertion-removed', file, text);
}
}

// 1b/2c. Weakened threshold: a number in CONSTRAINTS.md that went down, or a floor bullet deleted.
const nums = (s) => (s.match(/\d+(\.\d+)?/g) || []).map(Number);
const removedConstraints = removed.filter((l) => /CONSTRAINTS\.md$/.test(l.file));
const addedConstraints = added.filter((l) => /CONSTRAINTS\.md$/.test(l.file));
for (const r of removedConstraints) {
const a = addedConstraints.find((x) => x.text.split(/[|:]/)[0] === r.text.split(/[|:]/)[0]);
if (a && nums(a.text).some((n, i) => nums(r.text)[i] !== undefined && n < nums(r.text)[i])) {
flag('threshold-lowered', r.file, r.text + ' -> ' + a.text);
// 1b/2c. A rule in CONSTRAINTS.md weakened or removed. A rule is a floor bullet or a table row,
// identified by the bullet's text before its first colon or by the row's first cell. Each number
// carries a direction read from the words around it: a minimum (>=, at least, must not fall) is
// loosened by going down, a maximum (<=, at most, under, must not grow) by going up. A number whose
// direction cannot be read is reported whenever it changes, because the guard cannot tell
// tightening from loosening and staying quiet is the wrong default. Numbers are paired within
// their direction (the first minimum with the first minimum, and so on), so a number added
// elsewhere in the text does not shift the pairing; a threshold with no counterpart after the
// edit was removed, and an added one tightens.
const ruleKey = (t) => {
const s = t.trim();
if (s.startsWith('|')) return s.split('|').map((c) => c.trim()).filter(Boolean)[0] ?? '';
if (/^[-*] /.test(s)) return s.slice(2).split(':')[0].trim();
return null; // prose, headings, dates: not a rule
};
const isException = (t) => /^\| *(W|E)\d+ *\|/.test(t.trim());
const MIN_BEFORE = /(>=|>|≥|at least|minimum|\bmin\b|no less than|not fall|not drop)\s*$/;
const MAX_BEFORE = /(<=|<|≤|at most|maximum|\bmax\b|no more than|under|below|not grow|not exceed)\s*$/;
const MIN_AFTER = /^\s*\S*\s*(or more|or higher|must not fall|must not drop)/;
const MAX_AFTER = /^\s*\S*\s*(or less|or lower|must not grow|must not exceed)/;
const thresholds = (t) => {
const out = [], re = /\d+(?:\.\d+)?/g;
let m;
while ((m = re.exec(t))) {
const before = t.slice(Math.max(0, m.index - 24), m.index).toLowerCase();
const after = t.slice(m.index + m[0].length, m.index + m[0].length + 40).toLowerCase();
const dir = MIN_BEFORE.test(before) || MIN_AFTER.test(after) ? 'min'
: MAX_BEFORE.test(before) || MAX_AFTER.test(after) ? 'max' : null;
out.push({ n: Number(m[0]), dir });
}
return out;
};
const removedRules = removed.filter((l) => isConstraints(l.file) && ruleKey(l.text) !== null);
const addedRules = added.filter((l) => isConstraints(l.file) && ruleKey(l.text) !== null);
for (const r of removedRules) {
const a = addedRules.find((x) => ruleKey(x.text) === ruleKey(r.text));
if (!a) {
if (!isException(r.text)) flag('rule-removed', r.file, r.text); // dropping an exception tightens: silent
continue;
}
const before = thresholds(r.text), after = thresholds(a.text);
let verdict = null;
for (const dir of ['min', 'max', null]) {
const was = before.filter((x) => x.dir === dir), now = after.filter((x) => x.dir === dir);
was.forEach((b, i) => {
const n = now[i];
if (verdict) return;
if (!n) verdict = 'threshold-removed';
else if (n.n === b.n) return;
else if (dir === 'min' ? n.n < b.n : dir === 'max' ? n.n > b.n : true) {
verdict = dir ? 'threshold-loosened' : 'threshold-changed';
}
});
}
if (verdict) flag(verdict, r.file, r.text + ' -> ' + a.text);
}

if (findings.length === 0) { console.log('floor-guard: clean'); process.exit(0); }
console.error('floor-guard: ' + findings.length + ' floor violation(s):');
for (const f of findings) console.error(` [${f.rule}] ${f.file}: ${f.text}`);
if (findings.some((f) => f.rule === 'rule-removed')) {
console.error('\nA rule-removed finding can also mean the rule\'s label changed: rename a rule in one commit and change its thresholds in another.');
}
if (findings.some((f) => f.rule === 'threshold-removed')) {
console.error('\nA threshold-removed finding can also mean a number gained or lost its direction words (">= 80%" becoming "80%", or the reverse): compare the two lines before assuming a threshold was deleted.');
}
console.error('\nEach is a move that lowers the bar. Fix the code, or route it through a tracked exception.');
process.exit(1);
```
Expand Down
Loading