| #!/usr/bin/env node
|
| 'use strict';
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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);
|
| }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| let sidCounter = 0;
|
| function uniqueSid(prefix) {
|
| sidCounter += 1;
|
| return prefix + '_' + Date.now() + '_' + process.pid + '_' + sidCounter;
|
| }
|
|
|
|
|
| function dedupeMarkerPath(eventName, sessionId) {
|
| return path.join(os.tmpdir(), 'nomad_dedupe_' + String(eventName) + '_' + String(sessionId).replace(/[^A-Za-z0-9]/g, '') + '.marker');
|
| }
|
|
|
|
|
| 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 };
|
| }
|
|
|
|
|
| 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);
|
|
|
|
|
| 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);
|
| }
|
|
|
| {
|
|
|
| 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;
|
| }
|
|
|
|
|
| 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'
|
| );
|
|
|
|
|
| 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);
|
| }
|
|
|
|
|
| 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 {{{'), '');
|
| }
|
|
|
| {
|
|
|
| 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 });
|
| }
|
|
|
|
|
| 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);
|
| }
|
|
|
|
|
| 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);
|
|
|
|
|
| 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);
|
| }
|
|
|
|
|
| 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);
|
|
|
|
|
| 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');
|
| }
|
|
|
|
|
| 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);
|
|
|
|
|
| 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 });
|
|
|
|
|
| const r3 = runNode('append-log.js', ['- entry three', '--target', teamLogPath, '--anchor', '^ZZZ_NEVER_MATCHES_ZZZ$']);
|
| assertTrue('appendlog_anchorMiss_nonZeroExit', r3.exitCode !== 0, r3);
|
|
|
|
|
| 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);
|
|
|
|
|
| const r5 = runNode('append-log.js', ['- x', '--target', path.join(SCRATCH, 'does_not_exist.md')]);
|
| assertTrue('appendlog_missingTargetFile_nonZeroExit', r5.exitCode !== 0, r5);
|
|
|
|
|
| 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 });
|
| }
|
|
|
|
|
| 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);
|
|
|
|
|
|
|
|
|
| assertTrue('e2e_precompact_dedupeMarkerWrittenForThisRun', fs.existsSync(pcMarker), { marker: pcMarker });
|
| try {
|
| fs.unlinkSync(pcMarker);
|
| } catch (e) {
|
|
|
| }
|
| 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) {
|
|
|
| }
|
|
|
| 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 });
|
|
|
|
|
| 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) {
|
|
|
| }
|
| }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| {
|
| 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 });
|
| }
|
|
|
|
|
| {
|
| 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);
|
| }
|
|
|
|
|
| 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);
|
|
|
|
|
| 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);
|
|
|
|
|
| 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');
|
| }
|
|
|
|
|
| const ftLib = require(path.join(SCRIPTS_DIR, 'frontmatter-touch.js'));
|
|
|
| {
|
| const D = '2026-07-23';
|
| const mk = (fmBody) => '---\n' + fmBody + '---\n\n# Body\n';
|
|
|
|
|
| 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);
|
|
|
|
|
| assertEq('ft_idempotent_upToDate', ftLib.computeNext(mk('owner: team\ncreated: 2026-07-20\nupdated: ' + D + '\nstatus: active\n'), D), null);
|
|
|
|
|
| assertEq('ft_idempotent_updatedNewerThanMtime', ftLib.computeNext(mk('owner: team\ncreated: 2026-07-20\nupdated: 2026-09-01\nstatus: active\n'), D), null);
|
|
|
|
|
| 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);
|
|
|
|
|
| assertEq('ft_noInsert_createdSameDay', ftLib.computeNext(mk('owner: team\ncreated: ' + D + '\nstatus: active\n'), D), null);
|
|
|
|
|
| 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);
|
|
|
|
|
| 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);
|
|
|
|
|
| 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);
|
|
|
|
|
| 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));
|
|
|
|
|
| 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);
|
|
|
|
|
| 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);
|
|
|
|
|
| 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);
|
| }
|
|
|
|
|
| {
|
|
|
|
|
| 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');
|
|
|
|
|
| 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);
|
|
|
|
|
| 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);
|
|
|
|
|
| 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);
|
|
|
|
|
| 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);
|
|
|
|
|
| try { fs.unlinkSync(ftLib.stateFilePath(t.teamRoot)); } catch (e) { }
|
|
|
| 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);
|
|
|
|
|
|
|
| const mtA = fs.statSync(fileA).mtimeMs;
|
| assertTrue('fmtouch_e2e_mtimeRestored', Math.abs(mtA - yesterday.getTime()) < 5000, { mtA, expected: yesterday.getTime() });
|
|
|
|
|
| assertTrue('fmtouch_e2e_noLockLeftover', !fs.existsSync(fileA + '.lock') && !fs.existsSync(fileB + '.lock'), null);
|
|
|
|
|
| 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);
|
|
|
|
|
| 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);
|
|
|
|
|
|
|
| const run4 = runNode('frontmatter-touch.js', [], 'not json {{{');
|
| assertTrue('fmtouch_e2e_badJson_silentExit0', run4.exitCode === 0 && run4.stdout.trim() === '', run4);
|
|
|
|
|
| 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) { }
|
| 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;
|
|
|
|
|
|
|
| const tDedup = buildMockTeam('fmtouch_dedup');
|
| const sidD = 'e2e_ftdedup_' + Date.now();
|
| try { fs.unlinkSync(ftLib.stateFilePath(tDedup.teamRoot)); } catch (e) { }
|
| 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);
|
|
|
|
|
|
|
| try { fs.unlinkSync(ftLib.stateFilePath(tDedup.teamRoot)); } catch (e) { }
|
| 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);
|
| }
|
|
|
|
|
| {
|
| 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);
|
|
|
|
|
| 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);
|
| }
|
|
|
|
|
| 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;
|
| }
|
|
|