* test(#3882): failing-first rows for sentinel phases skewing calibration Adds A1a/A1b/A2/A3 to tests/estimate-calibrate.test.cjs, the module's existing test file, rather than a new bug-NNNN file. collectCalibrationSamples (src/estimate-cli.cts:206) does a raw readdirSync over .planning/phases and never applies isSentinelPhaseId, so a sentinel phase (milestone 0 or 999) carrying a PLAN estimate / SUMMARY actuals pair contributes a phantom calibration sample. computeCalibration is median-based, so a single 50x outlier among three samples leaves the factor unmoved — asserting "the factor is unchanged" against one sentinel would pass on the broken code for the wrong reason. Each row instead asserts the WHOLE computed CalibrationResult object (factor, applied, confidence, sampleCount, clamped) for a sentinel-free project against its sentinel-injected twin: - A1a: one sentinel flips applied false->true and confidence low->med on phantom evidence (calibration switches on with zero real signal). - A1b: two sentinels corrupt the factor itself (1 -> 3, clamped false->true). - A2: the sentinel's own sample is verified absent from the returned list. - A3: the two genuine phases still contribute their own unchanged samples (regression pin — stops A1/A2 passing by filtering everything). Verified RED on today's code (node tests/estimate-calibrate.test.cjs): A1a/A1b/A2 fail with the exact differing objects; A3 and all pre-existing rows in the file remain green (no collateral). Refs #3882 * feat(#3882): route phase enumeration through its owner and name the sentinel axis Task 1: collectCalibrationSamples (src/estimate-cli.cts) hand-rolled a raw readdirSync over .planning/phases, treating every directory (including sentinel phases, milestone 0/999) as a completed phase and feeding phantom PLAN/SUMMARY samples into the estimation calibration factor. Routed through the existing owner, listMilestonePhaseDirs(phasesRoot) with no cwd -- already 'all milestones, sentinels excluded', exactly the combination this caller needs; no new API was required for this half. It now also surfaces the scope discriminator: an unreadable phases directory throws PhasesUnreadableError instead of silently returning zero samples, and cmdEstimateCalibrate reports it via a new ERROR_REASON.ESTIMATE_PHASES_UNREADABLE instead of persisting a phantom empty calibration document. Task 2: added listAllPhaseDirs(phasesDir, { includeSentinels }) to src/phase-locator.cts -- the one genuinely missing axis: 'physical set, sentinels INCLUDED'. includeSentinels has no default and is required, so a call site cannot obtain sentinel-inclusion by omission (compile-time refusal, not just documentation). Mirrors listMilestonePhaseDirs's absent/unreadable scope handling. Task 3: migrated the two exemptions whose written reason maps cleanly onto 'physical set, sentinels included' -- cmdRoadmapAnalyze's _phaseDirNames (src/roadmap.cts) and cmdInitMilestoneOp's diskPhaseDirs (src/init.cts), both heading->directory lookup indexes. Left the rest: archivePhaseDirectories's own body has no readdirSync to migrate (its callers already resolve dirs before calling it, and both current callers deliberately EXCLUDE sentinels -- migrating it would be an unauthorized behavior change, not an API swap); cmdValidateHealth's exemption is vestigial (its actual physical-set sweep already lives in planning-snapshot.cts's buildAllPhaseDirNamesField, a pre-existing near-duplicate of the new axis, flagged as a finding, not restructured); cmdPhasesClear/cmdMilestoneComplete/cmdVerifySchemaDrift/detectHasPriorPhases/detectUiPhaseActive want a different combination (sentinels excluded, or a single-phase lookup) and are unaffected. Task 4: detector 2 (sentinel literal) is untouched and retained. Removed exemption entries only for the two migrated call sites; every other function-scoped exemption is preserved. Guard exits 0. Refs #3882 * refactor(#3882): delegate the snapshot phase-dir scan to its owner buildAllPhaseDirNamesField duplicated listAllPhaseDirs's own readdirSync + directory-filter + absent/unreadable handling — the 'one implementation per rule' defect ADR-3473 SS8.3 names, introduced by this branch's own #3882 work. Delegate to listAllPhaseDirs and re-apply the field's existing lexicographic sort on top, since W007's observable order must not change. Refs #3882 * docs(#3882): document the sentinel axis and the enumeration consolidation Records listAllPhaseDirs in the Phase Locator glossary entry, and the fact that the owner already answers the all-milestones sentinel-free question when called without a cwd -- the call collectCalibrationSamples was missing. Also notes that buildAllPhaseDirNamesField now delegates rather than carrying a second readdir, and that exactly one readdirSync over the phases directory remains across the two modules. Refs #3882 * test(#3882): close review findings — real order proof, unreadable coverage, collision fixtures Refs #3882 * chore(#3882): backfill changeset PR number Refs #3882 --------- Co-authored-by: sim <sim@local>
This commit is contained in:
@@ -23,6 +23,11 @@ const path = require('node:path');
|
||||
|
||||
const { createTempProject, cleanup, runGsdTools } = require('./helpers.cjs');
|
||||
const est = require('../gsd-core/bin/lib/phase-estimation.cjs');
|
||||
const estimateCli = require('../gsd-core/bin/lib/estimate-cli.cjs');
|
||||
// io.cjs owns error()/ERROR_REASON/JSON-error-mode — driven directly here so
|
||||
// H1 below can assert a typed `reason`, mirroring tests/config-get-default.test.cjs's
|
||||
// established in-process CLI-error-path pattern.
|
||||
const io = require('../gsd-core/bin/lib/io.cjs');
|
||||
|
||||
/** Write a phase dir containing a PLAN with an estimate and a SUMMARY with actuals. */
|
||||
function writePhase(tmpDir, phaseDir, { estTokens, actTokens, tasks = 3, commits = 4 }) {
|
||||
@@ -364,3 +369,252 @@ describe('multi-plan phases pair per plan, not per phase', () => {
|
||||
assert.equal(out.applied, true);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── sentinel phases must not skew calibration (#3882, ADR-3473 §8.2) ──────
|
||||
//
|
||||
// collectCalibrationSamples enumerates .planning/phases with a raw readdirSync
|
||||
// and treats every directory as a completed phase — it never routes through
|
||||
// the phase-directory owner and never applies isSentinelPhaseId, so a sentinel
|
||||
// directory (milestone 0 or 999 — SENTINEL_RANGES in src/phase-id.cts) whose
|
||||
// PLAN/SUMMARY pair carries an estimate/actuals block contributes a phantom
|
||||
// calibration sample.
|
||||
//
|
||||
// Governing constraint (.gsd/phase/feat-3882-enumerations/50-test-matrix.md
|
||||
// row A1): computeCalibration is MEDIAN-based, so a single outlier sample does
|
||||
// not move a 3-sample factor at all — asserting "the factor is unchanged" against
|
||||
// exactly one sentinel would pass on the broken code for the wrong reason. The
|
||||
// real, measured damage is the MIN_CALIBRATION_SAMPLES threshold crossing
|
||||
// (applied flips false -> true, confidence low -> med on phantom evidence) and,
|
||||
// once two sentinels are present, actual factor corruption. Every assertion
|
||||
// below compares the WHOLE computed CalibrationResult object between a
|
||||
// sentinel-free project and its sentinel-injected twin, reached the same way
|
||||
// production reaches it (collectCalibrationSamples -> computeCalibration, the
|
||||
// exact pair cmdEstimateCalibrate calls).
|
||||
describe('sentinel phases must not skew calibration (#3882)', () => {
|
||||
// Two genuine phases with DIFFERING ratios (1x and 2x), so A3 can pin each
|
||||
// one's own unchanged value rather than two indistinguishable duplicates.
|
||||
const REAL_PHASES = [
|
||||
['01-alpha', 1000, 1000],
|
||||
['02-beta', 2000, 4000],
|
||||
];
|
||||
// A deliberately extreme, fabricated ratio (50x) — the shape of what a
|
||||
// sentinel's PLAN/SUMMARY pair would carry.
|
||||
const SENTINEL_SAMPLE = { estTokens: 1000, actTokens: 50000 };
|
||||
|
||||
function buildRealOnlyProject() {
|
||||
const tmpDir = createTempProject();
|
||||
for (const [dir, estTokens, actTokens] of REAL_PHASES) {
|
||||
writePhase(tmpDir, dir, { estTokens, actTokens });
|
||||
}
|
||||
return tmpDir;
|
||||
}
|
||||
|
||||
/** Reached the way production reaches it — see cmdEstimateCalibrate above. */
|
||||
function calibrationResultFor(tmpDir) {
|
||||
return est.computeCalibration(estimateCli.collectCalibrationSamples(tmpDir));
|
||||
}
|
||||
|
||||
test('A1a: sentinelPhaseDoesNotActivateCalibration', (t) => {
|
||||
const realOnly = buildRealOnlyProject();
|
||||
t.after(() => cleanup(realOnly));
|
||||
const withSentinel = buildRealOnlyProject();
|
||||
t.after(() => cleanup(withSentinel));
|
||||
// milestone 999 — reserved icebox sentinel range (SENTINEL_RANGES).
|
||||
writePhase(withSentinel, '999-icebox', SENTINEL_SAMPLE);
|
||||
|
||||
const realOnlyResult = calibrationResultFor(realOnly);
|
||||
const withSentinelResult = calibrationResultFor(withSentinel);
|
||||
|
||||
assert.deepEqual(
|
||||
withSentinelResult, realOnlyResult,
|
||||
'a single sentinel phase must not change the computed calibration at all — '
|
||||
+ `real-only=${JSON.stringify(realOnlyResult)} with-sentinel=${JSON.stringify(withSentinelResult)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('A1b: sentinelPhasesDoNotCorruptTheFactor', (t) => {
|
||||
const realOnly = buildRealOnlyProject();
|
||||
t.after(() => cleanup(realOnly));
|
||||
const withTwoSentinels = buildRealOnlyProject();
|
||||
t.after(() => cleanup(withTwoSentinels));
|
||||
// milestone 999 and milestone 0 — both reserved sentinel ranges.
|
||||
writePhase(withTwoSentinels, '999-icebox', SENTINEL_SAMPLE);
|
||||
writePhase(withTwoSentinels, '0-backlog', SENTINEL_SAMPLE);
|
||||
|
||||
const realOnlyResult = calibrationResultFor(realOnly);
|
||||
const withSentinelsResult = calibrationResultFor(withTwoSentinels);
|
||||
|
||||
assert.deepEqual(
|
||||
withSentinelsResult, realOnlyResult,
|
||||
'sentinel phases must not corrupt the calibration factor — '
|
||||
+ `real-only=${JSON.stringify(realOnlyResult)} with-sentinels=${JSON.stringify(withSentinelsResult)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('A2: sentinelPhaseContributesNoCalibrationSample', (t) => {
|
||||
const withTwoSentinels = buildRealOnlyProject();
|
||||
t.after(() => cleanup(withTwoSentinels));
|
||||
writePhase(withTwoSentinels, '999-icebox', SENTINEL_SAMPLE);
|
||||
writePhase(withTwoSentinels, '0-backlog', SENTINEL_SAMPLE);
|
||||
|
||||
const samples = estimateCli.collectCalibrationSamples(withTwoSentinels);
|
||||
const sentinelHits = samples.filter(
|
||||
(s) => s.estimateTokens === SENTINEL_SAMPLE.estTokens && s.actualTokens === SENTINEL_SAMPLE.actTokens,
|
||||
);
|
||||
assert.equal(
|
||||
sentinelHits.length, 0,
|
||||
`the sentinel phases' sample must be absent from the returned list; got ${JSON.stringify(samples)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('A3: realPhasesStillContribute', (t) => {
|
||||
const withTwoSentinels = buildRealOnlyProject();
|
||||
t.after(() => cleanup(withTwoSentinels));
|
||||
writePhase(withTwoSentinels, '999-icebox', SENTINEL_SAMPLE);
|
||||
writePhase(withTwoSentinels, '0-backlog', SENTINEL_SAMPLE);
|
||||
|
||||
const samples = estimateCli.collectCalibrationSamples(withTwoSentinels);
|
||||
const realSamples = samples.filter(
|
||||
(s) => !(s.estimateTokens === SENTINEL_SAMPLE.estTokens && s.actualTokens === SENTINEL_SAMPLE.actTokens),
|
||||
);
|
||||
assert.deepEqual(
|
||||
realSamples.sort((a, b) => a.estimateTokens - b.estimateTokens),
|
||||
[
|
||||
{ estimateTokens: 1000, actualTokens: 1000 },
|
||||
{ estimateTokens: 2000, actualTokens: 4000 },
|
||||
],
|
||||
'the two genuine phases must still contribute their own, unchanged samples',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── PhasesUnreadableError / estimate_phases_unreadable (#3882, ADR-3473 §8.5,
|
||||
// review finding #2) ─────────────────────────────────────────────────────
|
||||
//
|
||||
// `collectCalibrationSamples` now routes through `listMilestonePhaseDirs`
|
||||
// (the #3882 fix above), which means an unreadable phases directory is no
|
||||
// longer output-identical to a genuinely empty one — it surfaces as
|
||||
// `scope: SCOPE.UNREADABLE`. `cmdEstimateCalibrate` converts that into a
|
||||
// refusal (`PhasesUnreadableError`, `process.exit(1)`,
|
||||
// `ERROR_REASON.ESTIMATE_PHASES_UNREADABLE`) instead of silently persisting
|
||||
// a phantom empty calibration document — a real behavior change (previously
|
||||
// silent-empty), disclosed and tested here rather than left as an
|
||||
// undocumented side effect of the routing fix.
|
||||
//
|
||||
// H1 drives the real `cmdEstimateCalibrate` IN-PROCESS: `runGsdTools` spawns
|
||||
// a real subprocess, and neither `fs.readdirSync` monkeypatching nor
|
||||
// `process.exit` interception crosses that process boundary. The pattern
|
||||
// below is the two established repo idioms composed, not invented: the
|
||||
// process.exit-interception + `--json-errors`-mode capture from
|
||||
// tests/config-get-default.test.cjs, and the `fs.readdirSync` method
|
||||
// monkeypatch (never chmod, which root/CI bypasses — CLAUDE.md's
|
||||
// cross-platform IO-failure-injection rule) already used in
|
||||
// tests/phase-locator.test.cjs for `listAllPhaseDirs`'s own unreadable case.
|
||||
describe('unreadable phases directory refuses calibration (#3882, ADR-3473 §8.5)', () => {
|
||||
class _ExitSignal extends Error {
|
||||
constructor(code, message) {
|
||||
super(message ?? `process.exit(${code})`);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs cmdEstimateCalibrate in-process with process.exit + stderr(fd 2) captured. */
|
||||
function runCalibrateExpectError(tmpDir) {
|
||||
const origExit = process.exit;
|
||||
const origWriteSync = fs.writeSync;
|
||||
io.setJsonErrorMode(true);
|
||||
let exitCount = 0;
|
||||
let exitCode;
|
||||
let stderr = '';
|
||||
fs.writeSync = (fd, ...rest) => {
|
||||
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
|
||||
const [data, offset = 0, length] = rest;
|
||||
const chunk = Buffer.isBuffer(data)
|
||||
? data.subarray(offset, offset + (length ?? data.length - offset)).toString('utf8')
|
||||
: String(data);
|
||||
stderr += chunk;
|
||||
return Buffer.byteLength(chunk);
|
||||
};
|
||||
const lastError = () => {
|
||||
const parts = stderr.split('\n').filter(Boolean);
|
||||
try { return JSON.parse(parts[parts.length - 1]); } catch { return {}; }
|
||||
};
|
||||
process.exit = (code) => {
|
||||
exitCount++;
|
||||
exitCode = code;
|
||||
throw new _ExitSignal(code, lastError().message);
|
||||
};
|
||||
try {
|
||||
estimateCli.cmdEstimateCalibrate(tmpDir, [], false);
|
||||
} catch (e) {
|
||||
if (!(e instanceof _ExitSignal)) throw e;
|
||||
} finally {
|
||||
process.exit = origExit;
|
||||
fs.writeSync = origWriteSync;
|
||||
io.setJsonErrorMode(false);
|
||||
}
|
||||
assert.ok(exitCode !== 0 && exitCode !== undefined, 'expected a non-zero exit code');
|
||||
assert.equal(exitCount, 1, 'error() must fire exactly once (production process.exit terminates)');
|
||||
return { status: exitCode, ...lastError() };
|
||||
}
|
||||
|
||||
test('H1: unreadable phases directory exits non-zero with estimate_phases_unreadable', (t) => {
|
||||
const tmpDir = createTempProject();
|
||||
t.after(() => cleanup(tmpDir));
|
||||
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
||||
|
||||
const originalReaddirSync = fs.readdirSync;
|
||||
fs.readdirSync = (...args) => {
|
||||
if (args[0] === phasesDir) {
|
||||
const err = new Error('EACCES: permission denied, scandir');
|
||||
err.code = 'EACCES';
|
||||
throw err;
|
||||
}
|
||||
return originalReaddirSync.apply(fs, args);
|
||||
};
|
||||
let result;
|
||||
try {
|
||||
result = runCalibrateExpectError(tmpDir);
|
||||
} finally {
|
||||
fs.readdirSync = originalReaddirSync;
|
||||
}
|
||||
|
||||
assert.equal(result.status, 1);
|
||||
assert.equal(result.reason, io.ERROR_REASON.ESTIMATE_PHASES_UNREADABLE);
|
||||
assert.ok(
|
||||
!fs.existsSync(path.join(tmpDir, '.planning', 'estimation-calibration.json')),
|
||||
'refusing the rebuild must not persist a phantom empty calibration document',
|
||||
);
|
||||
});
|
||||
|
||||
test('H2: a genuinely-empty phases directory still succeeds with empty calibration (boundary the H1 guard must not cross)', (t) => {
|
||||
// Real CLI as a subprocess (runGsdTools) — this is the boundary case:
|
||||
// .planning/phases/ EXISTS and is READABLE, but has zero entries. Must
|
||||
// succeed, not be caught by the unreadable-directory refusal above.
|
||||
// Overlaps the pre-existing "no phases at all is a clean no-op" test
|
||||
// above; kept as its own named row because it pins THIS boundary
|
||||
// specifically (see 50-test-matrix.md row H2), not incidentally.
|
||||
const tmpDir = createTempProject();
|
||||
t.after(() => cleanup(tmpDir));
|
||||
|
||||
const r = runGsdTools('query estimate-calibrate', tmpDir);
|
||||
assert.ok(r.success, `a readable, genuinely-empty phases dir must succeed: ${r.error}`);
|
||||
const out = JSON.parse(r.output);
|
||||
assert.equal(out.sample_count, 0);
|
||||
assert.equal(out.applied, false);
|
||||
});
|
||||
|
||||
test('H3: a normal project with real phases is unaffected by the unreadable-dir guard', (t) => {
|
||||
const tmpDir = createTempProject();
|
||||
t.after(() => cleanup(tmpDir));
|
||||
writePhase(tmpDir, '01-a', { estTokens: 100, actTokens: 200 });
|
||||
writePhase(tmpDir, '02-b', { estTokens: 100, actTokens: 200 });
|
||||
writePhase(tmpDir, '03-c', { estTokens: 100, actTokens: 200 });
|
||||
|
||||
const r = runGsdTools('query estimate-calibrate', tmpDir);
|
||||
assert.ok(r.success, `a normal readable project must not be affected by the guard: ${r.error}`);
|
||||
const out = JSON.parse(r.output);
|
||||
assert.equal(out.sample_count, 3);
|
||||
assert.equal(out.applied, true);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user