fix(#474): deterministic STATE dates via deepened clock seam (nowIso/today + GSD_NOW_MS adapter) (#477)

* fix(#474): route state date-stamping + installer lock loop through clock seam (nowIso/today + GSD_NOW_MS adapter)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(#474): use process.ppid (not pid 1) as held-lock owner in install-lock timeout test

pid 1 is POSIX init/launchd (always alive) but does not exist on Windows,
so isPidAlive(1) returns false, the lock is reclaimed as stale, and
acquireInstallMigrationLock no longer throws -- failing the timeout
assertion on windows-latest,22. process.ppid is a live, non-self process
on every platform, so the lock is seen as held and the timeout path
throws deterministically cross-platform.

Refs #474

---------

Co-authored-by: CI Rebase Check <ci@gsd-redux>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-05-29 18:21:25 -04:00
committed by GitHub
parent 75b29c2c08
commit a8ff46484b
8 changed files with 420 additions and 37 deletions

View File

@@ -19,12 +19,67 @@
// identical to allocating a fresh buffer each time.
const _realSleepBuf = new Int32Array(new SharedArrayBuffer(4));
/**
* Parse GSD_NOW_MS to a valid pinned epoch millisecond value, or return null.
*
* Accepts ONLY strict decimal integer strings within JS Date bounds
* (abs(ms) <= 8.64e15). Rejects empty strings, whitespace-only, floats
* ('12.5'), scientific notation ('1e30'), and out-of-range values.
*
* Returns null (fall back to Date.now()) for any invalid or absent input.
* Returns null when GSD_TEST_MODE is not set.
*
* @returns {number|null}
*/
function _pinnedNowMs() {
if (!process.env.GSD_TEST_MODE) return null;
const raw = process.env.GSD_NOW_MS;
if (typeof raw !== 'string') return null;
const t = raw.trim();
if (!/^-?\d+$/.test(t)) return null; // reject '', 'abc', '1e30', '12.5'
const ms = Number(t);
if (!Number.isFinite(ms) || Math.abs(ms) > 8.64e15) return null; // Date-valid bounds
return ms;
}
const realClock = {
/** Return current epoch milliseconds (same as the inline Date.now() calls in state.cjs). */
/**
* Return current epoch milliseconds.
*
* When both GSD_TEST_MODE and GSD_NOW_MS are set (subprocess time-pin adapter,
* issue #474), returns the pinned millisecond value so all date-stamping in the
* subprocess SUT is deterministic. In production, falls back to Date.now().
*
* Only strict decimal integer strings within JS Date bounds are accepted as pins.
* Any other value (empty string, float, scientific notation, out-of-range) falls
* back to Date.now() to prevent RangeError from new Date(ms).toISOString().
*/
now() {
const pinned = _pinnedNowMs();
if (pinned !== null) return pinned;
return Date.now();
},
/**
* Return the current instant as an ISO 8601 string (UTC).
* Uses this.now() so the subprocess time-pin adapter is honoured.
*
* @returns {string} e.g. "2020-06-15T12:00:00.000Z"
*/
nowIso() {
return new Date(this.now()).toISOString();
},
/**
* Return today's date as a YYYY-MM-DD string (UTC calendar day).
* Uses this.now() so the subprocess time-pin adapter is honoured.
*
* @returns {string} e.g. "2020-06-15"
*/
today() {
return this.nowIso().split('T')[0];
},
/**
* Synchronous sleep via Atomics.wait.
* This is the identical primitive acquireStateLock and withPlanningLock used

View File

@@ -8,6 +8,7 @@ const {
validateInstallerMigrationRecord,
} = require('./installer-migration-authoring.cjs');
const { platformWriteSync } = require('./shell-command-projection.cjs');
const { realClock } = require('./clock.cjs');
const MANIFEST_NAME = 'gsd-file-manifest.json';
const INSTALL_STATE_NAME = 'gsd-install-state.json';
@@ -257,10 +258,10 @@ function readLockFile(lockPath) {
}
}
function acquireInstallMigrationLock(configDir, { timeoutMs = DEFAULT_LOCK_TIMEOUT_MS } = {}) {
function acquireInstallMigrationLock(configDir, { timeoutMs = DEFAULT_LOCK_TIMEOUT_MS } = {}, clock = realClock) {
fs.mkdirSync(configDir, { recursive: true });
const lockPath = path.join(configDir, INSTALL_MIGRATION_LOCK_NAME);
const started = Date.now();
const started = clock.now();
while (true) {
let fd = null;
@@ -324,11 +325,11 @@ function acquireInstallMigrationLock(configDir, { timeoutMs = DEFAULT_LOCK_TIMEO
if (reclaimed) continue;
}
}
if (Date.now() - started >= timeoutMs) {
if (clock.now() - started >= timeoutMs) {
const holderInfo = lockData ? ` (held by pid ${lockData.pid} since ${lockData.acquiredAt})` : '';
throw new Error(`installer migration lock is held: ${lockPath}${holderInfo}`);
}
sleepSync(Math.min(50, Math.max(1, timeoutMs - (Date.now() - started))));
clock.sleep(Math.min(50, Math.max(1, timeoutMs - (clock.now() - started))));
continue;
}
throw error;
@@ -765,6 +766,7 @@ module.exports = {
INSTALL_MIGRATION_LOCK_NAME,
INSTALL_STATE_NAME,
MANIFEST_NAME,
acquireInstallMigrationLock,
applyInstallerMigrationPlan,
classifyArtifact,
discoverInstallerMigrations,

View File

@@ -300,7 +300,7 @@ function cmdStateAdvancePlan(cwd, raw) {
const statePath = planningPaths(cwd).state;
if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
const today = new Date().toISOString().split('T')[0];
const today = realClock.today();
let result = null;
readModifyWriteStateMd(statePath, (content) => {
@@ -629,7 +629,7 @@ function cmdStateRecordSession(cwd, options, raw) {
const statePath = planningPaths(cwd).state;
if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
const now = new Date().toISOString();
const now = realClock.nowIso();
const updated = [];
readModifyWriteStateMd(statePath, (content) => {
@@ -927,7 +927,7 @@ function buildStateFrontmatter(bodyContent, cwd) {
fm.status = normalizedStatus;
if (stoppedAt) fm.stopped_at = stoppedAt;
if (pausedAt) fm.paused_at = pausedAt;
fm.last_updated = new Date().toISOString();
fm.last_updated = realClock.nowIso();
if (lastActivity) fm.last_activity = lastActivity;
const progress = {};
@@ -1176,7 +1176,7 @@ function cmdStateBeginPhase(cwd, phaseNumber, phaseName, planCount, raw) {
return;
}
const today = new Date().toISOString().split('T')[0];
const today = realClock.today();
const updated = [];
readModifyWriteStateMd(statePath, (content) => {
@@ -1310,7 +1310,7 @@ function cmdSignalWaiting(cwd, type, question, options, phase, raw) {
type: type || 'decision_point',
question: question || null,
options: options ? options.split('|').map(o => o.trim()) : [],
since: new Date().toISOString(),
since: realClock.nowIso(),
phase: phase || null,
};
@@ -1393,7 +1393,7 @@ function cmdStatePlannedPhase(cwd, phaseNumber, planCount, raw) {
}
let content = fs.readFileSync(statePath, 'utf-8');
const today = new Date().toISOString().split('T')[0];
const today = realClock.today();
const updated = [];
const statusDefaults = KNOWN_TEMPLATE_DEFAULTS['Status'];
@@ -1448,7 +1448,7 @@ function cmdStateMilestoneSwitch(cwd, version, name, raw) {
}
const resolvedName = (name && String(name).trim()) || 'milestone';
const statePath = planningPaths(cwd).state;
const today = new Date().toISOString().split('T')[0];
const today = realClock.today();
const lockPath = acquireStateLock(statePath);
try {
@@ -1475,7 +1475,7 @@ function cmdStateMilestoneSwitch(cwd, version, name, raw) {
milestone: version,
milestone_name: resolvedName,
status: 'planning',
last_updated: new Date().toISOString(),
last_updated: realClock.nowIso(),
last_activity: today,
progress: {
total_phases: 0,
@@ -1581,7 +1581,7 @@ function cmdStateSync(cwd, options, raw) {
const content = fs.readFileSync(statePath, 'utf-8');
const changes = [];
let modified = content;
const today = new Date().toISOString().split('T')[0];
const today = realClock.today();
const phasesDir = planningPaths(cwd).phases;
if (!fs.existsSync(phasesDir)) {
@@ -1856,7 +1856,7 @@ function cmdStatePrune(cwd, options, raw) {
// Write archived entries to STATE-ARCHIVE.md
if (archived.length > 0) {
const timestamp = new Date().toISOString().split('T')[0];
const timestamp = realClock.today();
let archiveContent = platformReadSync(archivePath);
if (archiveContent === null) {
archiveContent = '# STATE Archive\n\nPruned entries from STATE.md. Recoverable but no longer loaded into agent context.\n\n';
@@ -1931,7 +1931,7 @@ function cmdStateCompletePhase(cwd, raw, overridePhase) {
return;
}
const today = new Date().toISOString().split('T')[0];
const today = realClock.today();
const updated = [];
readModifyWriteStateMd(statePath, (content) => {