#!/usr/bin/env node 'use strict'; /** * selftest.js — regression test for the Nomad scripts/ package (offline, never * touches any real deployment). Mirrors production hooks-core's selftest.js * pattern: pure-function unit tests + real spawned-subprocess end-to-end tests * against a mock team directory built fresh under the OS temp dir. * * Coverage: * 1. lib/config.js — findUp/resolveTeamRoot/resolveAgentHome/resolveLanguage/ * resolveSharedPath/firstExisting boundary cases * 2. lib/emit.js — three-platform payload shapes, resolveCwd priority chain, * isDuplicateInvocation dedup guard * 3. session-start.js pure functions — parseTeamlogHead/parseKanbanHot * (structured hit + degrade-to-raw miss)/parseInboxUnreadCount * 4. session-stop.js — decide() four branches + boundary values, newestMtimeMs * 5. lib/session-lock.js — acquire/release/check, conflict warning * 6. lib/file-lock.js — acquire/release, stale-lock self-heal * 7. append-log.js — end-to-end concurrency-safe insert against a mock file, * --target resolution via team-config.json, anchor-miss hard error * 8. Three hook scripts spawned as real subprocesses (normal/empty/bad-JSON * stdin), schema checks, double-fire dedup e2e * 9. (inside 8/9 blocks) double-fire dedup * 10. lib/frontmatter.js — block extraction/BOM/incomplete-block/column-zero * scalar parsing (indented lines invisible by design) * 11. frontmatter-touch.js pure functions — computeNext decision matrix * (replace/insert/idempotent/malformed-date/gate misses, CRLF+BOM * preservation) + structural exclusion rules * 12. frontmatter-touch.js end-to-end — real subprocess against a mock * NON-GIT team dir (the zip-extracted-team scenario): refresh + insert + * mtime restore + second-run idempotence + exclusions + cap + outside-team * silence. Also session-start.js charter-pointer section e2e. * * Results are written to a scratch dir under the OS temp dir; the printed path * is the source of truth — don't trust only the stdout summary line for a * failing run, open the JSON. * * Usage: node selftest.js */ const fs = require('fs'); const path = require('path'); const os = require('os'); const { execFileSync } = require('child_process'); const SCRIPTS_DIR = __dirname; const RUN_ID = 'nomad_scripts_selftest_' + Date.now(); const SCRATCH = fs.mkdtempSync(path.join(os.tmpdir(), 'nomad-scripts-selftest-')); const results = { runId: RUN_ID, scriptsDir: SCRIPTS_DIR, scratch: SCRATCH, cases: [] }; function record(name, pass, detail) { results.cases.push({ name, pass, detail }); } function assertEq(name, actual, expected) { record(name, JSON.stringify(actual) === JSON.stringify(expected), { actual, expected }); } function assertTrue(name, cond, detail) { record(name, !!cond, detail); } // ── session_id factory for e2e cases ── // NEVER hardcode a session_id literal in an e2e case that spawns a hook script. // isDuplicateInvocation() keys its marker file on eventName+session_id under // os.tmpdir(), and that marker OUTLIVES the test process (5s dedup window, no // cleanup by the hook itself). A fixed literal therefore makes the case fail // whenever selftest is run twice within 5 seconds — which is exactly what // `session_id:"pc1"` did to e2e_precompact_exit0_schemaSystemMessageOnly until // 2026-07-26. Date.now() alone is not sufficient either: it is millisecond // granular, so two calls inside the same tick collide. pid + counter close that. let sidCounter = 0; function uniqueSid(prefix) { sidCounter += 1; return prefix + '_' + Date.now() + '_' + process.pid + '_' + sidCounter; } // Marker path mirrors emit.isDuplicateInvocation()'s naming so a case can assert // on / clean up after its own dedup state. Kept in sync with lib/emit.js. function dedupeMarkerPath(eventName, sessionId) { return path.join(os.tmpdir(), 'nomad_dedupe_' + String(eventName) + '_' + String(sessionId).replace(/[^A-Za-z0-9]/g, '') + '.marker'); } // ══════════════ mock team fixture (built once, reused by several sections) ══════════════ function buildMockTeam(label) { const teamRoot = path.join(SCRATCH, 'team_' + label + '_' + Date.now()); const agentHome = path.join(teamRoot, '01-agents', 'tester'); const memDir = path.join(agentHome, 'memory'); const sharedDir = path.join(teamRoot, '02-shared'); fs.mkdirSync(memDir, { recursive: true }); fs.mkdirSync(sharedDir, { recursive: true }); fs.writeFileSync(path.join(agentHome, 'AGENTS.md'), '# Tester agent\n', 'utf8'); fs.writeFileSync( path.join(teamRoot, 'team-config.json'), JSON.stringify( { team_root: teamRoot, principal: { name_or_alias: 'Tester', language: 'en' }, os: 'windows', shared_paths: { team_log: '02-shared/team-log.md', kanban: '02-shared/kanban.md' }, }, null, 2 ), 'utf8' ); fs.writeFileSync(path.join(sharedDir, 'team-log.md'), '# Team Log\n\n- seed entry\n', 'utf8'); fs.writeFileSync(path.join(memDir, 'inbox.md'), '## Unread\n\n## Already read\n', 'utf8'); return { teamRoot, agentHome, memDir, sharedDir }; } // ══════════════ 1. lib/config.js ══════════════ const cfgLib = require(path.join(SCRIPTS_DIR, 'lib', 'config.js')); { const t = buildMockTeam('config'); assertEq('config_resolveTeamRoot_fromAgentHome', cfgLib.resolveTeamRoot(t.agentHome), t.teamRoot); assertEq('config_resolveTeamRoot_fromDeeperCwd', cfgLib.resolveTeamRoot(path.join(t.memDir)), t.teamRoot); assertEq('config_resolveAgentHome_fromAgentHomeItself', cfgLib.resolveAgentHome(t.agentHome), t.agentHome); assertEq('config_resolveAgentHome_fromMemDir', cfgLib.resolveAgentHome(t.memDir), t.agentHome); assertEq('config_resolveTeamRoot_noTeamConfigAnywhere', cfgLib.resolveTeamRoot(os.tmpdir()), null); assertEq('config_resolveAgentHome_noAgentsMdAnywhere', cfgLib.resolveAgentHome(os.tmpdir()), null); const config = cfgLib.loadTeamConfig(t.teamRoot); assertTrue('config_loadTeamConfig_parsesOk', !!(config && config.principal && config.principal.name_or_alias === 'Tester'), config); assertEq('config_loadTeamConfig_missingTeamRoot', cfgLib.loadTeamConfig(null), null); assertEq('config_resolveLanguage_fromConfigEn', cfgLib.resolveLanguage({ principal: { language: 'en' } }), 'en'); assertEq('config_resolveLanguage_fromConfigZh', cfgLib.resolveLanguage({ principal: { language: 'zh-CN' } }), 'zh-CN'); assertEq('config_resolveLanguage_noConfigFallsBackEn', cfgLib.resolveLanguage(null), 'en'); assertEq('config_resolveLanguage_zhVariantNormalizes', cfgLib.resolveLanguage({ principal: { language: 'zh' } }), 'zh-CN'); const sharedTeamLog = cfgLib.resolveSharedPath(t.teamRoot, config, 'team_log'); assertEq('config_resolveSharedPath_teamLog', sharedTeamLog, path.join(t.teamRoot, '02-shared', 'team-log.md')); assertEq('config_resolveSharedPath_missingKey', cfgLib.resolveSharedPath(t.teamRoot, config, 'nonexistent_key'), null); assertEq('config_resolveSharedPath_nullConfig', cfgLib.resolveSharedPath(t.teamRoot, null, 'team_log'), null); assertEq('config_firstExisting_findsSecondCandidate', cfgLib.firstExisting(t.agentHome, ['nope', 'memory']), t.memDir); assertEq('config_firstExisting_noneExist', cfgLib.firstExisting(t.agentHome, ['nope1', 'nope2']), null); // BOM handling const bomFile = path.join(SCRATCH, 'bom_test.json'); fs.writeFileSync(bomFile, '' + JSON.stringify({ a: 1 }), 'utf8'); assertEq('config_readJsonFile_stripsBOM', cfgLib.readJsonFile(bomFile).a, 1); } { // env override for team root (validated — must actually contain team-config.json) const t = buildMockTeam('envoverride'); const prevEnv = process.env.NOMAD_TEAM_ROOT; process.env.NOMAD_TEAM_ROOT = t.teamRoot; assertEq('config_resolveTeamRoot_envOverride_valid', cfgLib.resolveTeamRoot(os.tmpdir()), t.teamRoot); process.env.NOMAD_TEAM_ROOT = path.join(SCRATCH, 'does_not_exist_xyz'); assertEq('config_resolveTeamRoot_envOverride_invalid_ignored', cfgLib.resolveTeamRoot(t.agentHome), t.teamRoot); if (prevEnv === undefined) delete process.env.NOMAD_TEAM_ROOT; else process.env.NOMAD_TEAM_ROOT = prevEnv; const prevLang = process.env.NOMAD_LANG; process.env.NOMAD_LANG = 'zh-CN'; assertEq('config_resolveLanguage_envOverridesConfig', cfgLib.resolveLanguage({ principal: { language: 'en' } }), 'zh-CN'); if (prevLang === undefined) delete process.env.NOMAD_LANG; else process.env.NOMAD_LANG = prevLang; } // ══════════════ 2. lib/emit.js ══════════════ const emitLib = require(path.join(SCRIPTS_DIR, 'lib', 'emit.js')); { assertEq('emit_normalizePlatform_unknownFallsBackClaude', emitLib.normalizePlatform('hermes'), 'claude'); assertEq('emit_normalizePlatform_caseInsensitive', emitLib.normalizePlatform(' CODEX '), 'codex'); assertEq('emit_sessionStart_claude', emitLib.buildSessionStartPayload('x', 'claude'), { hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: 'x' }, }); assertEq('emit_sessionStart_codexSameAsClaude', emitLib.buildSessionStartPayload('x', 'codex'), { hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: 'x' }, }); assertEq('emit_sessionStart_cursor', emitLib.buildSessionStartPayload('x', 'cursor'), { additional_context: 'x' }); assertEq('emit_stop_claude', emitLib.buildStopBlockPayload('r', 'claude'), { decision: 'block', reason: 'r' }); assertEq('emit_stop_cursor', emitLib.buildStopBlockPayload('r', 'cursor'), { followup_message: 'r' }); assertEq('emit_precompact_claude', emitLib.buildPreCompactPayload('m', 'claude'), { systemMessage: 'm' }); assertEq('emit_precompact_cursor', emitLib.buildPreCompactPayload('m', 'cursor'), { user_message: 'm' }); assertEq('emit_resolveCwd_stdinCwdWins', emitLib.resolveCwd('{"cwd":"D:\\\\foo"}', 'claude', () => 'D:\\should-not-be-used'), 'D:\\foo'); assertEq('emit_resolveCwd_fallsBackToProcessCwd', emitLib.resolveCwd('{"other":1}', 'claude', () => 'D:\\pcwd'), 'D:\\pcwd'); assertEq( 'emit_resolveCwd_cursorWorkspaceRootsFallback', emitLib.resolveCwd(JSON.stringify({ workspace_roots: ['/D:/foo/bar'] }), 'cursor', () => ''), 'D:\\foo\\bar' ); // Regression guard: a genuine POSIX workspace_root (no drive-letter prefix) must be returned // UNCHANGED — the old code unconditionally flipped every '/' to '\\', corrupting real Mac/Linux paths. assertEq( 'emit_resolveCwd_cursorPosixPathNotMangled', emitLib.resolveCwd(JSON.stringify({ workspace_roots: ['/home/user/project'] }), 'cursor', () => ''), '/home/user/project' ); assertEq('emit_resolveCwd_nonCursorIgnoresWorkspaceRoots', emitLib.resolveCwd(JSON.stringify({ workspace_roots: ['/D:/foo/bar'] }), 'claude', () => ''), ''); assertTrue('emit_looksMojibake_detectsReplacementChar', emitLib.looksMojibake('foo�bar'), null); assertTrue('emit_looksMojibake_normalTextNotFlagged', !emitLib.looksMojibake('D:\\team\\agent'), null); assertEq('emit_extractSessionId_normal', emitLib.extractSessionId('{"session_id":"abc"}'), 'abc'); assertEq('emit_extractSessionId_badJson', emitLib.extractSessionId('not json{{'), ''); } { const sid = 'selftest_dedupe_' + Date.now(); assertEq('emit_dedupe_firstCallNotDuplicate', emitLib.isDuplicateInvocation('UnitEvt', sid), false); assertEq('emit_dedupe_secondCallWithinWindowIsDuplicate', emitLib.isDuplicateInvocation('UnitEvt', sid), true); assertEq('emit_dedupe_shortWindowTreatsOldMarkerAsNewBatch', emitLib.isDuplicateInvocation('UnitEvt', sid, { windowMs: 1 }), false); assertEq('emit_dedupe_noSessionIdNeverDedupes', emitLib.isDuplicateInvocation('UnitEvt', ''), false); } // ══════════════ 3. session-start.js pure functions ══════════════ const ssc = require(path.join(SCRIPTS_DIR, 'session-start.js')); { const lines = []; for (let i = 1; i <= 10; i++) lines.push('line' + i); const content = lines.join('\n'); assertEq('ssc_parseTeamlogHead_first3', ssc.parseTeamlogHead(content, 3), 'line1\nline2\nline3'); assertEq('ssc_parseTeamlogHead_moreThanTotalReturnsAll', ssc.parseTeamlogHead(content, 100), content); } { const longStatus = 'x'.repeat(200); const kb = [ '## In Progress', '### Item A', '- **Status**: ' + longStatus, '### Item B', '- **status**:lowercase label also matches', '## Done', '### Item C (should not appear)', '- **Status**: should not be collected', ].join('\n'); const { items, total } = ssc.parseKanbanHot(kb, 150); assertEq('ssc_parseKanbanHot_englishHeading_total2', total, 2); assertTrue('ssc_parseKanbanHot_150charTruncation', items[0].includes(longStatus.slice(0, 150) + '...'), { item0: items[0] }); assertTrue('ssc_parseKanbanHot_doneSectionExcluded', !items.some((s) => s.includes('Item C')), { items }); const kbZh = ['## 🔥 进行中', '### 项目A', '- **状态**:s1', '## ✅ 已完成', '### 项目B', '- **状态**:s2'].join('\n'); const zhResult = ssc.parseKanbanHot(kbZh, 150); assertEq('ssc_parseKanbanHot_chineseHeading_total1', zhResult.total, 1); const kbUnstructured = ['# Random board', 'no structured sections here', '- just a bullet'].join('\n'); assertEq('ssc_parseKanbanHot_noStructuralMatch_total0', ssc.parseKanbanHot(kbUnstructured, 150).total, 0); } { const inbox3 = ['## Unread', '- a', '- b', '- c', '## Already read', '- d'].join('\n'); assertEq('ssc_parseInboxUnreadCount_english_3', ssc.parseInboxUnreadCount(inbox3), 3); const inboxZh = ['## 未读', '- a', '- b', '## 已读归档'].join('\n'); assertEq('ssc_parseInboxUnreadCount_chinese_2', ssc.parseInboxUnreadCount(inboxZh), 2); const inbox0 = ['## Unread', '## Already read', '- x'].join('\n'); assertEq('ssc_parseInboxUnreadCount_zero', ssc.parseInboxUnreadCount(inbox0), 0); } { assertEq('ssc_extractCwd_normal', ssc.extractCwd('{"cwd":"D:\\\\foo"}'), 'D:\\foo'); assertEq('ssc_extractCwd_badJson', ssc.extractCwd('not json {{{'), ''); } { // buildKanbanSection degrade-to-raw path with a real mock team + English messages const t = buildMockTeam('kanban_degrade'); fs.writeFileSync(path.join(t.sharedDir, 'kanban.md'), '# Board\nno structured format here\njust free text\n', 'utf8'); const messages = require(path.join(SCRIPTS_DIR, 'lib', 'messages.js')); const config = cfgLib.loadTeamConfig(t.teamRoot); const section = ssc.buildKanbanSection(t.teamRoot, config, messages.get('en')); assertTrue('ssc_buildKanbanSection_degradesToRawExcerptWhenUnstructured', section.includes('no structured') && section.includes('could not match'), { section }); const t2 = buildMockTeam('kanban_structured'); fs.writeFileSync(path.join(t2.sharedDir, 'kanban.md'), '## In Progress\n### Task X\n- **Status**: halfway\n', 'utf8'); const config2 = cfgLib.loadTeamConfig(t2.teamRoot); const section2 = ssc.buildKanbanSection(t2.teamRoot, config2, messages.get('en')); assertTrue('ssc_buildKanbanSection_structuredHitUsesStructuredFormat', section2.includes('Task X') && section2.includes('halfway'), { section2 }); } // ══════════════ 4. session-stop.js ══════════════ const frc = require(path.join(SCRIPTS_DIR, 'session-stop.js')); { const r1 = frc.decide({ exists: false, lastT: 0, lastM: 0 }, 500, 1000); assertEq('frc_decide_noStateFile_remindsFirstTime', { remind: r1.remind, newT: r1.newT, newM: r1.newM }, { remind: true, newT: 500, newM: 1000 }); const r2 = frc.decide({ exists: true, lastT: 1000, lastM: 5000 }, 2000, 9000); assertEq('frc_decide_memoryUpdated_noReminderAdvancesBaseline', { remind: r2.remind, newT: r2.newT, newM: r2.newM }, { remind: false, newT: 2000, newM: 9000 }); const r3 = frc.decide({ exists: true, lastT: 1000, lastM: 5000 }, 10500, 5000); assertEq('frc_decide_deltaOverThreshold_remindsAdvancesBaseline', { remind: r3.remind, newT: r3.newT, newM: r3.newM }, { remind: true, newT: 10500, newM: 5000 }); const r4 = frc.decide({ exists: true, lastT: 1000, lastM: 5000 }, 5000, 5000); assertEq('frc_decide_deltaUnderThreshold_noReminderBaselineUnchanged', { remind: r4.remind, newT: r4.newT, newM: r4.newM }, { remind: false, newT: 1000, newM: 5000 }); assertEq('frc_decide_boundaryExactly9000_notTriggered', frc.decide({ exists: true, lastT: 1000, lastM: 5000 }, 10000, 5000).remind, false); assertEq('frc_decide_boundary9001_triggered', frc.decide({ exists: true, lastT: 1000, lastM: 5000 }, 10001, 5000).remind, true); } { const t = buildMockTeam('mtime'); fs.writeFileSync(path.join(t.memDir, 'x.md'), 'hello', 'utf8'); assertTrue('frc_newestMtimeMs_nonZeroForRealDir', frc.newestMtimeMs(t.memDir) > 0, null); assertEq('frc_newestMtimeMs_missingDirReturns0', frc.newestMtimeMs(path.join(SCRATCH, 'does_not_exist')), 0); assertTrue('frc_newestMtimeMs_isIntegerNotFraction', Number.isInteger(frc.newestMtimeMs(t.memDir)), null); } // ══════════════ 5. lib/session-lock.js ══════════════ const sessLock = require(path.join(SCRIPTS_DIR, 'lib', 'session-lock.js')); { const t = buildMockTeam('lock'); const r0 = sessLock.check(t.agentHome); assertEq('lock_check_noLockInitially', r0.hasLock, false); const r1 = sessLock.acquire(t.agentHome, 'codex'); assertTrue('lock_acquire_firstTime_notWarned', r1.ok && !r1.warned, r1); assertTrue('lock_acquire_writesLockFile', fs.existsSync(sessLock.lockFilePath(t.agentHome)), null); const r2 = sessLock.acquire(t.agentHome, 'claude'); assertTrue('lock_acquire_secondHolder_warnedWithPriorHolderInfo', r2.ok && r2.warned && r2.priorHolder && r2.priorHolder.harness === 'codex', r2); const r3 = sessLock.release(t.agentHome); assertTrue('lock_release_existed', r3.ok && r3.existed, r3); assertTrue('lock_release_fileGone', !fs.existsSync(sessLock.lockFilePath(t.agentHome)), null); const r4 = sessLock.release(t.agentHome); assertTrue('lock_release_idempotent_secondCallOkNotExisted', r4.ok && !r4.existed, r4); // expired lock: no warning const lp = sessLock.lockFilePath(t.agentHome); fs.writeFileSync(lp, JSON.stringify({ harness: 'old', pid: 1, acquiredAt: new Date(Date.now() - 5 * 60 * 60 * 1000).toISOString(), ttlMs: sessLock.TTL_MS }), 'utf8'); const r5 = sessLock.acquire(t.agentHome, 'claude'); assertTrue('lock_acquire_expiredPriorLock_noWarning', r5.ok && !r5.warned, r5); sessLock.release(t.agentHome); } // ══════════════ 6. lib/file-lock.js ══════════════ const flock = require(path.join(SCRIPTS_DIR, 'lib', 'file-lock.js')); { const lockPath = path.join(SCRATCH, 'flocktest.lock'); flock.acquireLockSync(lockPath, { retryMax: 3, retryIntervalMs: 50 }); assertTrue('flock_acquire_createsLockFile', fs.existsSync(lockPath), null); flock.releaseLock(lockPath); assertTrue('flock_release_removesLockFile', !fs.existsSync(lockPath), null); // stale lock self-heal fs.writeFileSync(lockPath, '99999 stale', 'utf8'); const oldTime = new Date(Date.now() - 60000); fs.utimesSync(lockPath, oldTime, oldTime); let staleCleared = false; flock.acquireLockSync(lockPath, { staleMs: 5000, retryMax: 3, retryIntervalMs: 50, onStaleClear: () => (staleCleared = true) }); assertTrue('flock_staleLock_selfHeals', staleCleared, null); flock.releaseLock(lockPath); const target = path.join(SCRATCH, 'atomic_write_test.txt'); flock.atomicWriteSync(target, 'hello world'); assertEq('flock_atomicWriteSync_contentCorrect', fs.readFileSync(target, 'utf8'), 'hello world'); } // ══════════════ 7. append-log.js end-to-end ══════════════ function runNode(scriptName, args, stdinText) { try { const out = execFileSync(process.execPath, [path.join(SCRIPTS_DIR, scriptName)].concat(args || []), { input: stdinText != null ? stdinText : '', encoding: 'utf8', timeout: 15000, }); return { exitCode: 0, stdout: out, stderr: '' }; } catch (e) { return { exitCode: e.status, stdout: e.stdout ? e.stdout.toString('utf8') : '', stderr: e.stderr ? e.stderr.toString('utf8') : '', error: e.message }; } } { const t = buildMockTeam('appendlog'); const teamLogPath = path.join(t.sharedDir, 'team-log.md'); const r1 = runNode('append-log.js', ['- entry one', '--target', teamLogPath]); assertTrue('appendlog_explicitTarget_exit0', r1.exitCode === 0, r1); assertTrue('appendlog_explicitTarget_entryLanded', fs.readFileSync(teamLogPath, 'utf8').includes('- entry one'), null); // resolve target via team-config.json by running with cwd inside the agent home const r2 = execFileSync(process.execPath, [path.join(SCRIPTS_DIR, 'append-log.js'), '- entry two (via config)'], { cwd: t.agentHome, encoding: 'utf8', }); assertTrue('appendlog_resolvesTargetFromTeamConfig', fs.readFileSync(teamLogPath, 'utf8').includes('- entry two (via config)'), { r2 }); // anchor miss = hard error const r3 = runNode('append-log.js', ['- entry three', '--target', teamLogPath, '--anchor', '^ZZZ_NEVER_MATCHES_ZZZ$']); assertTrue('appendlog_anchorMiss_nonZeroExit', r3.exitCode !== 0, r3); // bottom mode const r4 = runNode('append-log.js', ['- entry four', '--target', teamLogPath, '--mode', 'bottom']); assertTrue('appendlog_bottomMode_exit0AndAtEnd', r4.exitCode === 0 && fs.readFileSync(teamLogPath, 'utf8').trim().endsWith('- entry four'), r4); // missing target file const r5 = runNode('append-log.js', ['- x', '--target', path.join(SCRATCH, 'does_not_exist.md')]); assertTrue('appendlog_missingTargetFile_nonZeroExit', r5.exitCode !== 0, r5); // real concurrent writers — spawn N processes appending to the same file, verify none lost / none corrupted const concurTarget = path.join(t.sharedDir, 'concurrent.md'); fs.writeFileSync(concurTarget, '# Concurrent test\n\n', 'utf8'); const N = 15; const { spawnSync } = require('child_process'); const kids = []; for (let i = 0; i < N; i++) { kids.push( spawnSync(process.execPath, [path.join(SCRIPTS_DIR, 'append-log.js'), '- concurrent entry ' + i, '--target', concurTarget], { encoding: 'utf8' }) ); } const allOk = kids.every((k) => k.status === 0); const finalContent = fs.readFileSync(concurTarget, 'utf8'); const allPresent = Array.from({ length: N }, (_, i) => i).every((i) => finalContent.includes('- concurrent entry ' + i)); assertTrue('appendlog_concurrent15Writers_allExitedOk', allOk, kids.map((k) => k.status)); assertTrue('appendlog_concurrent15Writers_allEntriesPresentNoneLost', allPresent, { finalContent }); } // ══════════════ 8. three hook scripts — real subprocess end-to-end ══════════════ function tryParseJson(s) { try { return JSON.parse(s.trim()); } catch (e) { return null; } } { const t = buildMockTeam('hooks_e2e'); const stdinNormal = JSON.stringify({ cwd: t.agentHome, session_id: 'e2e_ss_' + Date.now() }); const r1 = runNode('session-start.js', [], stdinNormal); const j1 = tryParseJson(r1.stdout); assertTrue('e2e_sessionStart_normalInput_exit0', r1.exitCode === 0, r1); assertTrue( 'e2e_sessionStart_schemaCorrect', !!(j1 && j1.hookSpecificOutput && j1.hookSpecificOutput.hookEventName === 'SessionStart' && typeof j1.hookSpecificOutput.additionalContext === 'string'), j1 ); assertTrue('e2e_sessionStart_containsTeamlogSeedEntry', j1.hookSpecificOutput.additionalContext.includes('seed entry'), { ctx: j1.hookSpecificOutput.additionalContext }); const r2 = runNode('session-start.js', [], ''); assertTrue('e2e_sessionStart_emptyInput_exit0StillValidJson', r2.exitCode === 0 && !!tryParseJson(r2.stdout), r2); const r3 = runNode('session-start.js', [], 'not json {{{'); assertTrue('e2e_sessionStart_badJson_exit0StillValidJson', r3.exitCode === 0 && !!tryParseJson(r3.stdout), r3); const stdinCursor = JSON.stringify({ cwd: t.agentHome, session_id: 'e2e_ss_cursor_' + Date.now() }); const r4 = runNode('session-start.js', ['--platform', 'cursor'], stdinCursor); const j4 = tryParseJson(r4.stdout); assertTrue('e2e_sessionStart_cursorSchema', !!(j4 && typeof j4.additional_context === 'string' && !j4.hookSpecificOutput), j4); } { const pcSid = uniqueSid('e2e_pc'); const pcMarker = dedupeMarkerPath('PreCompact', pcSid); const r1 = runNode('precompact.js', [], JSON.stringify({ session_id: pcSid })); const j1 = tryParseJson(r1.stdout); assertTrue('e2e_precompact_exit0_schemaSystemMessageOnly', r1.exitCode === 0 && !!(j1 && typeof j1.systemMessage === 'string' && !j1.hookSpecificOutput), r1); // Teeth for the flake fix: prove the case really went through the dedup path // (so a future regression can't pass by accident because dedup got skipped), // then drop this run's marker so selftest leaves no state behind in tmpdir. assertTrue('e2e_precompact_dedupeMarkerWrittenForThisRun', fs.existsSync(pcMarker), { marker: pcMarker }); try { fs.unlinkSync(pcMarker); } catch (e) { /* ignore */ } assertTrue('e2e_precompact_dedupeMarkerCleanedUp', !fs.existsSync(pcMarker), { marker: pcMarker }); const r2 = runNode('precompact.js', [], ''); assertTrue('e2e_precompact_emptyInput_stillOutputs', r2.exitCode === 0 && !!tryParseJson(r2.stdout), r2); } { const t = buildMockTeam('flush_e2e'); const transcriptPath = path.join(SCRATCH, 'mock_transcript_' + Date.now() + '.jsonl'); fs.writeFileSync(transcriptPath, 'x'.repeat(500), 'utf8'); const sid = 'e2e_flush_' + Date.now(); const stateFile = path.join(os.tmpdir(), 'nomad_stop_' + sid.replace(/[^A-Za-z0-9]/g, '') + '.txt'); try { fs.unlinkSync(stateFile); } catch (e) { /* ignore */ } const stdinJson = JSON.stringify({ session_id: sid, cwd: t.agentHome, transcript_path: transcriptPath }); const r1 = runNode('session-stop.js', [], stdinJson); const j1 = tryParseJson(r1.stdout); assertTrue('e2e_flush_firstStop_reminds', r1.exitCode === 0 && !!(j1 && j1.decision === 'block' && typeof j1.reason === 'string'), r1); assertTrue('e2e_flush_stateFileWritten', fs.existsSync(stateFile), null); assertTrue('e2e_flush_reasonMentionsAppendLog', j1.reason.includes('append-log.js'), { reason: j1.reason }); // no session_id => proceed silently const r2 = runNode('session-stop.js', [], JSON.stringify({ cwd: t.agentHome })); assertTrue('e2e_flush_noSessionId_silentProceed', r2.exitCode === 0 && r2.stdout.trim() === '', r2); try { fs.unlinkSync(stateFile); } catch (e) { /* ignore */ } } // ══════════════ 8b. session-stop: a failing writeState must NOT cost the lock release ══════════════ // Regression for the agent-modpack v0.6.0 external-review finding (3-6): writeState() // was the only bare fs write left in main(); when it threw (tmpdir unwritable / disk // full / EPERM), control jumped to the outer catch and sessionLock.release() below it // never ran — .session_lock.json stayed behind and every later start falsely reported // "another session is already running". Forced here by pointing TEMP/TMP at a *file*, // so path.join(os.tmpdir(), ...) writes under a non-directory and fails with ENOTDIR. { const t = buildMockTeam('stop_lock_release'); sessLock.acquire(t.agentHome, 'selftest'); const lockPath = sessLock.lockFilePath(t.agentHome); assertTrue('e2e_stopLock_setupAcquired', fs.existsSync(lockPath), null); const bogusTmp = path.join(SCRATCH, 'not_a_directory_' + Date.now() + '.txt'); fs.writeFileSync(bogusTmp, 'x', 'utf8'); const env = Object.assign({}, process.env, { TEMP: bogusTmp, TMP: bogusTmp, TMPDIR: bogusTmp }); let exitCode = 0; try { execFileSync(process.execPath, [path.join(SCRIPTS_DIR, 'session-stop.js')], { input: JSON.stringify({ session_id: 'e2e_stoplock_' + Date.now(), cwd: t.agentHome, transcript_path: '', }), encoding: 'utf8', timeout: 15000, env, stdio: ['pipe', 'pipe', 'pipe'], }); } catch (e) { exitCode = e.status; } assertTrue('e2e_stopLock_exitsZeroDespiteStateWriteFailure', exitCode === 0, { exitCode }); assertTrue('e2e_stopLock_lockStillReleasedWhenStateWriteFails', !fs.existsSync(lockPath), { lockPath }); } // ══════════════ 9. double-fire dedup — three hook scripts, spawned twice with same session_id ══════════════ { const t = buildMockTeam('dedupe_e2e'); const sid = 'e2e_dedupe_ss_' + Date.now(); const stdin = JSON.stringify({ cwd: t.agentHome, session_id: sid }); const first = runNode('session-start.js', [], stdin); const second = runNode('session-start.js', [], stdin); assertTrue('e2e_dedupe_sessionStart_firstCallHasOutput', !!tryParseJson(first.stdout), first); assertTrue('e2e_dedupe_sessionStart_secondCallWithinWindowSilent', second.exitCode === 0 && second.stdout.trim() === '', second); } { const sid = 'e2e_dedupe_pc_' + Date.now(); const stdin = JSON.stringify({ session_id: sid }); const first = runNode('precompact.js', [], stdin); const second = runNode('precompact.js', [], stdin); assertTrue('e2e_dedupe_precompact_firstCallHasOutput', !!tryParseJson(first.stdout), first); assertTrue('e2e_dedupe_precompact_secondCallWithinWindowSilent', second.exitCode === 0 && second.stdout.trim() === '', second); } // ══════════════ 10. lib/frontmatter.js ══════════════ const fmLib = require(path.join(SCRIPTS_DIR, 'lib', 'frontmatter.js')); { assertEq('fm_parse_noFrontmatter_null', fmLib.parse('# Just a heading\n'), null); assertEq('fm_parse_emptyString_null', fmLib.parse(''), null); const broken = fmLib.parse('---\nowner: a\nno closing fence ever\n'); assertTrue('fm_parse_incompleteBlock_flagged', !!(broken && broken.complete === false), broken); const simple = fmLib.parse('---\ntype: rule\nowner: team\ncreated: 2026-07-22\nstatus: active\n---\nbody\n'); assertTrue('fm_parse_simple_complete', !!(simple && simple.complete), simple); assertEq('fm_parse_simple_owner', simple.fields.owner, 'team'); assertEq('fm_parse_simple_headerLineCount', simple.headerLineCount, 6); assertEq('fm_parse_simple_lineIndex_created', simple.lineIndexByKey.created, 2); const bom = fmLib.parse('---\nowner: x\ncreated: 2026-01-01\nstatus: active\n---\n'); assertTrue('fm_parse_bom_detectedAndParsed', !!(bom && bom.complete && bom.hasBom && bom.fields.owner === 'x'), bom); // Indented lines (links object-array rows) must NOT register as scalar fields. const nested = fmLib.parse('---\nowner: a\ncreated: 2026-01-01\nstatus: active\nlinks:\n - rel: references\n target: some/file.md\n---\n'); assertTrue('fm_parse_indentedLines_invisible', nested.fields.target === undefined && nested.fields.rel === undefined, nested.fields); // Duplicate key: first occurrence wins, stable. const dup = fmLib.parse('---\nowner: first\nowner: second\ncreated: 2026-01-01\nstatus: active\n---\n'); assertEq('fm_parse_duplicateKey_firstWins', dup.fields.owner, 'first'); } // ══════════════ 11. frontmatter-touch.js pure functions ══════════════ const ftLib = require(path.join(SCRIPTS_DIR, 'frontmatter-touch.js')); { const D = '2026-07-23'; const mk = (fmBody) => '---\n' + fmBody + '---\n\n# Body\n'; // replace: updated behind file date const r1 = ftLib.computeNext(mk('type: rule\nowner: team\ncreated: 2026-07-20\nupdated: 2026-07-21\nstatus: active\n'), D); assertTrue('ft_replace_staleUpdated', !!(r1 && !r1.inserted && r1.content.includes('updated: ' + D) && !r1.content.includes('updated: 2026-07-21')), r1); // idempotent: updated already equals file date assertEq('ft_idempotent_upToDate', ftLib.computeNext(mk('owner: team\ncreated: 2026-07-20\nupdated: ' + D + '\nstatus: active\n'), D), null); // idempotent: updated NEWER than file date (mtime-restored file) → no touch assertEq('ft_idempotent_updatedNewerThanMtime', ftLib.computeNext(mk('owner: team\ncreated: 2026-07-20\nupdated: 2026-09-01\nstatus: active\n'), D), null); // insert: no updated line, created behind file date → inserted right after created const r2 = ftLib.computeNext(mk('type: rule\nowner: team\ncreated: 2026-07-20\nstatus: active\n'), D); assertTrue('ft_insert_missingUpdated', !!(r2 && r2.inserted && r2.content.includes('created: 2026-07-20\nupdated: ' + D + '\nstatus: active')), r2); // no insert when created == file date (fresh file, created already says it) assertEq('ft_noInsert_createdSameDay', ftLib.computeNext(mk('owner: team\ncreated: ' + D + '\nstatus: active\n'), D), null); // charter-schema gate: any of owner/created/status missing → untouchable assertEq('ft_gate_noOwner', ftLib.computeNext(mk('name: my-skill\ndescription: whatever\ncreated: 2026-07-20\nstatus: active\n'), D), null); assertEq('ft_gate_noStatus', ftLib.computeNext(mk('owner: team\ncreated: 2026-07-20\n'), D), null); assertEq('ft_gate_emptyOwnerValue', ftLib.computeNext(mk('owner:\ncreated: 2026-07-20\nstatus: active\n'), D), null); // malformed dates → never guess assertEq('ft_malformed_updatedValue', ftLib.computeNext(mk('owner: team\ncreated: 2026-07-20\nupdated: sometime\nstatus: active\n'), D), null); assertEq('ft_malformed_createdValue_noUpdatedLine', ftLib.computeNext(mk('owner: team\ncreated: yesterday\nstatus: active\n'), D), null); assertEq('ft_malformed_fileDate', ftLib.computeNext(mk('owner: team\ncreated: 2026-07-20\nstatus: active\n'), 'not-a-date'), null); // no frontmatter / broken block assertEq('ft_noFrontmatter', ftLib.computeNext('# plain doc\n', D), null); assertEq('ft_brokenBlock', ftLib.computeNext('---\nowner: team\ncreated: 2026-07-20\nstatus: active\n', D), null); // CRLF file: newline style preserved on replace AND on insert const crlf = '---\r\nowner: team\r\ncreated: 2026-07-20\r\nupdated: 2026-07-21\r\nstatus: active\r\n---\r\nbody\r\n'; const r3 = ftLib.computeNext(crlf, D); assertTrue('ft_crlf_replacePreservesNewlines', !!(r3 && r3.content.includes('updated: ' + D + '\r\nstatus') && !r3.content.includes('\n\n')), r3 && JSON.stringify(r3.content)); const crlfIns = '---\r\nowner: team\r\ncreated: 2026-07-20\r\nstatus: active\r\n---\r\nbody\r\n'; const r4 = ftLib.computeNext(crlfIns, D); assertTrue('ft_crlf_insertPreservesNewlines', !!(r4 && r4.inserted && r4.content.includes('created: 2026-07-20\r\nupdated: ' + D + '\r\nstatus: active')), r4 && JSON.stringify(r4.content)); // BOM preserved through a rewrite const r5 = ftLib.computeNext('---\nowner: team\ncreated: 2026-07-20\nupdated: 2026-07-21\nstatus: active\n---\n', D); assertTrue('ft_bom_preserved', !!(r5 && r5.content.charCodeAt(0) === 0xfeff && r5.content.includes('updated: ' + D)), r5); // body content byte-identical apart from the one frontmatter line const bodyBefore = mk('owner: team\ncreated: 2026-07-20\nupdated: 2026-07-21\nstatus: active\n').split('---')[2]; const r6 = ftLib.computeNext(mk('owner: team\ncreated: 2026-07-20\nupdated: 2026-07-21\nstatus: active\n'), D); assertTrue('ft_bodyUntouched', !!(r6 && r6.content.split('---')[2] === bodyBefore), null); // structural exclusion rules assertTrue('ft_exclude_dotDirs', ftLib.isExcludedDirName('.git') && ftLib.isExcludedDirName('.claude'), null); assertTrue('ft_exclude_nodeModules', ftLib.isExcludedDirName('node_modules'), null); assertTrue('ft_exclude_slot97_98_99_bothNamings', ftLib.isExcludedDirName('97-inbox-misc') && ftLib.isExcludedDirName('98-archive') && ftLib.isExcludedDirName('99-recycle-bin') && ftLib.isExcludedDirName('97_待归纳') && ftLib.isExcludedDirName('98_归档') && ftLib.isExcludedDirName('99_回收站') && ftLib.isExcludedDirName('98') , null); assertTrue('ft_exclude_notOverbroad', !ftLib.isExcludedDirName('01-agents') && !ftLib.isExcludedDirName('91-team-tools') && !ftLib.isExcludedDirName('970-not-a-slot') && !ftLib.isExcludedDirName('记忆'), null); assertTrue('ft_exclude_bakFiles', ftLib.isExcludedFileName('notes.bak.md') && ftLib.isExcludedFileName('a.md.bak_20260701') && !ftLib.isExcludedFileName('normal.md'), null); } // ══════════════ 12. frontmatter-touch.js e2e — non-git mock team (zip-extracted scenario) ══════════════ { // buildMockTeam never runs `git init`, so this whole fixture IS the // "zip-extracted plain folder" environment the mtime mechanism exists for. const t = buildMockTeam('fmtouch_e2e'); assertTrue('fmtouch_e2e_fixtureIsNotGit', !fs.existsSync(path.join(t.teamRoot, '.git')), null); const dayMs = 24 * 60 * 60 * 1000; const yesterday = new Date(Date.now() - dayMs); const y = yesterday.getFullYear() + '-' + String(yesterday.getMonth() + 1).padStart(2, '0') + '-' + String(yesterday.getDate()).padStart(2, '0'); const beforeY = new Date(Date.now() - 3 * dayMs); const beforeYStr = beforeY.getFullYear() + '-' + String(beforeY.getMonth() + 1).padStart(2, '0') + '-' + String(beforeY.getDate()).padStart(2, '0'); // (a) charter-schema file with a stale `updated`, mtime = yesterday const fileA = path.join(t.sharedDir, 'stale-updated.md'); fs.writeFileSync(fileA, '---\ntype: rule\nowner: team\ncreated: ' + beforeYStr + '\nupdated: ' + beforeYStr + '\nstatus: active\n---\n\n# Doc A\n', 'utf8'); fs.utimesSync(fileA, yesterday, yesterday); // (b) charter-schema file with NO `updated` line, mtime = yesterday → insert expected const fileB = path.join(t.sharedDir, 'no-updated-line.md'); fs.writeFileSync(fileB, '---\ntype: rule\nowner: team\ncreated: ' + beforeYStr + '\nstatus: active\n---\n\n# Doc B\n', 'utf8'); fs.utimesSync(fileB, yesterday, yesterday); // (c) SKILL.md-style foreign schema — must never be touched const fileC = path.join(t.sharedDir, 'foreign-schema.md'); const contentC = '---\nname: some-skill\ndescription: not ours\n---\n\n# Doc C\n'; fs.writeFileSync(fileC, contentC, 'utf8'); fs.utimesSync(fileC, yesterday, yesterday); // (d) stale charter-schema file inside an excluded 98-archive slot — untouched const archiveDir = path.join(t.teamRoot, '98-archive'); fs.mkdirSync(archiveDir, { recursive: true }); const fileD = path.join(archiveDir, 'archived.md'); const contentD = '---\nowner: team\ncreated: ' + beforeYStr + '\nupdated: ' + beforeYStr + '\nstatus: archived\n---\n\n# Doc D\n'; fs.writeFileSync(fileD, contentD, 'utf8'); fs.utimesSync(fileD, yesterday, yesterday); // Clear any scan-baseline state left from a previous selftest run of this teamRoot. try { fs.unlinkSync(ftLib.stateFilePath(t.teamRoot)); } catch (e) { /* ignore */ } const run1 = runNode('frontmatter-touch.js', [], JSON.stringify({ cwd: t.agentHome, session_id: 'e2e_ft_1_' + Date.now() })); assertTrue('fmtouch_e2e_run1_exit0_zeroStdout', run1.exitCode === 0 && run1.stdout.trim() === '', run1); const afterA = fs.readFileSync(fileA, 'utf8'); assertTrue('fmtouch_e2e_staleUpdated_refreshedToMtimeDate', afterA.includes('updated: ' + y) && !afterA.includes('updated: ' + beforeYStr), { afterA }); const afterB = fs.readFileSync(fileB, 'utf8'); assertTrue('fmtouch_e2e_missingUpdated_inserted', afterB.includes('created: ' + beforeYStr + '\nupdated: ' + y + '\nstatus: active'), { afterB }); assertEq('fmtouch_e2e_foreignSchema_untouched', fs.readFileSync(fileC, 'utf8'), contentC); assertEq('fmtouch_e2e_excludedSlot_untouched', fs.readFileSync(fileD, 'utf8'), contentD); // mtime restore: rewritten files must still read as "edited yesterday" // (tolerance ±5s — utimes handoff plus FAT-style timestamp granularity). const mtA = fs.statSync(fileA).mtimeMs; assertTrue('fmtouch_e2e_mtimeRestored', Math.abs(mtA - yesterday.getTime()) < 5000, { mtA, expected: yesterday.getTime() }); // no leftover locks / tmp files assertTrue('fmtouch_e2e_noLockLeftover', !fs.existsSync(fileA + '.lock') && !fs.existsSync(fileB + '.lock'), null); // second run (fresh session_id, so dedup doesn't mask it): fully idempotent const snapshotA = fs.readFileSync(fileA, 'utf8'); const snapshotB = fs.readFileSync(fileB, 'utf8'); const run2 = runNode('frontmatter-touch.js', [], JSON.stringify({ cwd: t.agentHome, session_id: 'e2e_ft_2_' + Date.now() })); assertTrue('fmtouch_e2e_run2_exit0', run2.exitCode === 0, run2); assertEq('fmtouch_e2e_run2_idempotentA', fs.readFileSync(fileA, 'utf8'), snapshotA); assertEq('fmtouch_e2e_run2_idempotentB', fs.readFileSync(fileB, 'utf8'), snapshotB); // outside any team (no team-config.json up the tree) → silent no-op success const orphanDir = path.join(SCRATCH, 'no_team_here'); fs.mkdirSync(orphanDir, { recursive: true }); const run3 = runNode('frontmatter-touch.js', [], JSON.stringify({ cwd: orphanDir, session_id: 'e2e_ft_3_' + Date.now() })); assertTrue('fmtouch_e2e_outsideTeam_silentExit0', run3.exitCode === 0 && run3.stdout.trim() === '', run3); // bad stdin JSON → still exit 0, still silent (falls back to process.cwd — // selftest's own cwd is not inside a mock team, so it no-ops) const run4 = runNode('frontmatter-touch.js', [], 'not json {{{'); assertTrue('fmtouch_e2e_badJson_silentExit0', run4.exitCode === 0 && run4.stdout.trim() === '', run4); // per-run touch cap: 3 stale files, cap=1 → exactly one touched per run, converges over runs const tCap = buildMockTeam('fmtouch_cap'); const capFiles = []; for (let i = 0; i < 3; i++) { const p = path.join(tCap.sharedDir, 'cap' + i + '.md'); fs.writeFileSync(p, '---\nowner: team\ncreated: ' + beforeYStr + '\nupdated: ' + beforeYStr + '\nstatus: active\n---\nbody\n', 'utf8'); fs.utimesSync(p, yesterday, yesterday); capFiles.push(p); } try { fs.unlinkSync(ftLib.stateFilePath(tCap.teamRoot)); } catch (e) { /* ignore */ } const prevCap = process.env.NOMAD_FMTOUCH_MAX_TOUCH; process.env.NOMAD_FMTOUCH_MAX_TOUCH = '1'; const capRun1 = runNode('frontmatter-touch.js', [], JSON.stringify({ cwd: tCap.agentHome, session_id: 'e2e_ftcap_1_' + Date.now() })); const touchedAfter1 = capFiles.filter((p) => fs.readFileSync(p, 'utf8').includes('updated: ' + y)).length; assertTrue('fmtouch_e2e_cap_boundsWorkPerRun', capRun1.exitCode === 0 && touchedAfter1 === 1, { touchedAfter1 }); runNode('frontmatter-touch.js', [], JSON.stringify({ cwd: tCap.agentHome, session_id: 'e2e_ftcap_2_' + Date.now() })); runNode('frontmatter-touch.js', [], JSON.stringify({ cwd: tCap.agentHome, session_id: 'e2e_ftcap_3_' + Date.now() })); const touchedAfter3 = capFiles.filter((p) => fs.readFileSync(p, 'utf8').includes('updated: ' + y)).length; assertTrue('fmtouch_e2e_cap_convergesAcrossRuns', touchedAfter3 === 3, { touchedAfter3 }); if (prevCap === undefined) delete process.env.NOMAD_FMTOUCH_MAX_TOUCH; else process.env.NOMAD_FMTOUCH_MAX_TOUCH = prevCap; // dedup: same session_id twice — second invocation must skip work. // Observable via a fresh stale file the second call would otherwise touch. const tDedup = buildMockTeam('fmtouch_dedup'); const sidD = 'e2e_ftdedup_' + Date.now(); try { fs.unlinkSync(ftLib.stateFilePath(tDedup.teamRoot)); } catch (e) { /* ignore */ } runNode('frontmatter-touch.js', [], JSON.stringify({ cwd: tDedup.agentHome, session_id: sidD })); const lateFile = path.join(tDedup.sharedDir, 'late-arrival.md'); fs.writeFileSync(lateFile, '---\nowner: team\ncreated: ' + beforeYStr + '\nupdated: ' + beforeYStr + '\nstatus: active\n---\nbody\n', 'utf8'); fs.utimesSync(lateFile, yesterday, yesterday); // Remove the scan baseline the first run just wrote — otherwise the baseline // filter alone would hide lateFile and this assertion would pass even with a // broken dedup guard (a fake-green test proves nothing). try { fs.unlinkSync(ftLib.stateFilePath(tDedup.teamRoot)); } catch (e) { /* ignore */ } runNode('frontmatter-touch.js', [], JSON.stringify({ cwd: tDedup.agentHome, session_id: sidD })); assertTrue('fmtouch_e2e_dedup_secondCallSkipsWork', fs.readFileSync(lateFile, 'utf8').includes('updated: ' + beforeYStr), null); } // ══════════════ 12b. session-start.js charter-pointer section e2e ══════════════ { const t = buildMockTeam('charter_e2e'); fs.writeFileSync(path.join(t.teamRoot, 'ARCHITECTURE.md'), '# Team charter\n', 'utf8'); const r1 = runNode('session-start.js', [], JSON.stringify({ cwd: t.agentHome, session_id: 'e2e_charter_1_' + Date.now() })); const j1 = tryParseJson(r1.stdout); assertTrue('charter_e2e_pointerInjectedWhenCharterExists', !!(j1 && j1.hookSpecificOutput && j1.hookSpecificOutput.additionalContext.includes('ARCHITECTURE.md')), j1); const t2 = buildMockTeam('charter_absent_e2e'); const r2 = runNode('session-start.js', [], JSON.stringify({ cwd: t2.agentHome, session_id: 'e2e_charter_2_' + Date.now() })); const j2 = tryParseJson(r2.stdout); assertTrue('charter_e2e_noPointerWhenNoCharter', !!(j2 && j2.hookSpecificOutput && !j2.hookSpecificOutput.additionalContext.includes('Structure governance') && !j2.hookSpecificOutput.additionalContext.includes('结构治理')), j2); // zh naming candidate also resolves const t3 = buildMockTeam('charter_zh_e2e'); fs.writeFileSync(path.join(t3.teamRoot, '团队结构宪章.md'), '# 宪章\n', 'utf8'); const r3 = runNode('session-start.js', [], JSON.stringify({ cwd: t3.agentHome, session_id: 'e2e_charter_3_' + Date.now() })); const j3 = tryParseJson(r3.stdout); assertTrue('charter_e2e_zhCharterFilenameAlsoDetected', !!(j3 && j3.hookSpecificOutput && j3.hookSpecificOutput.additionalContext.includes('团队结构宪章.md')), j3); } // ══════════════ summary ══════════════ const passCount = results.cases.filter((c) => c.pass).length; const failCount = results.cases.length - passCount; results.summary = { total: results.cases.length, pass: passCount, fail: failCount, allPass: failCount === 0 }; const outPath = path.join(SCRATCH, 'result_' + RUN_ID + '.json'); fs.writeFileSync(outPath, JSON.stringify(results, null, 2), 'utf8'); process.stdout.write('[selftest] ' + passCount + '/' + results.cases.length + ' pass. Full detail: ' + outPath + '\n'); if (failCount > 0) { process.stdout.write('[selftest] failing cases:\n'); for (const c of results.cases) { if (!c.pass) process.stdout.write(' - ' + c.name + '\n'); } process.exitCode = 1; }