leerness 1.9.424 → 1.9.425

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/leerness.js CHANGED
@@ -31,7 +31,7 @@ const { _evidenceQuality, _parseEvidenceStats, _shellGuardAnalyze, _claimFileInG
31
31
  // 1.9.295 (UR-0025 4단계): 정적 데이터 카탈로그 모듈 분리 (비파괴, require-based).
32
32
  const { CAPABILITY_SURFACE, POWERFUL_COMMANDS, ADAPTERS, REUSE_CATEGORIES, REUSE_CHECKLIST, _DEFAULT_PLATFORM_CONSTRAINTS, _DEFAULT_DOMAIN_CATALOG, _LSP_LANG_PATTERNS, OPTIMISM_PATTERNS, BUILT_IN_PERSONAS, STRINGS, BUILTIN_CATALOG, ROADMAP_STATUS_LABEL, ROADMAP_STATUS_COLOR, SECRET_PATTERNS, MERGE_OVERWRITE_FILES, MINIMAL_SKIP_KEYS, REQUIRED_WORKSPACE_FILES, KEYWORD_STOPWORDS, SKILL_CATALOG_PRESETS } = require('../lib/catalogs'); // 1.9.344/368/369 (UR-0025): catalog 분리 (MERGE_OVERWRITE_FILES/MINIMAL_SKIP_KEYS 포함)
33
33
 
34
- const VERSION = '1.9.424';
34
+ const VERSION = '1.9.425';
35
35
 
36
36
  // 1.9.290 (UR-0037, Codex gpt-5.5 #4 수렴): CLI 전용 부작용은 require 시 실행하지 않는다.
37
37
  // 이전: warning listener 제거 / NODE_OPTIONS 변경 / chcp IIFE 가 top-level 즉시 실행 → require('harness') 시 호스트 프로세스 오염.
@@ -2929,7 +2929,7 @@ function _selfTestCases() {
2929
2929
  { name: 'MCP notification 준수: id없는 요청 무응답 가드 + ping {} (UR-0049 설치리뷰 1.9.313)', run: () => { const src = read(__filename); const guard = src.includes("const isNotification = !('id' in req)") && src.includes("req.method.startsWith('notifications/')") && src.includes('if (isNotification) return;'); const ping = src.includes("req.method === 'ping'") && /ping[\s\S]{0,140}result: \{\} \}/.test(src); return guard && ping; } },
2930
2930
  { name: 'PowerShell 감지: pwsh7(channel/Documents\\PowerShell/install) + ps5.1 영구경로 과경고 안함 (UR-0052 설치리뷰 1.9.314)', run: () => { const f = _detectPwshFromEnv; const pwsh7a = f({ POWERSHELL_DISTRIBUTION_CHANNEL: 'MSI:Windows 10' }).version === '7'; const pwsh7b = f({ PSModulePath: 'C:\\Users\\me\\Documents\\PowerShell\\Modules' }).version === '7'; const pwsh7c = f({ PSModulePath: 'C:\\Program Files\\PowerShell\\7\\Modules' }).version === '7'; const noFalsePs5 = f({ PSModulePath: 'C:\\Users\\me\\Documents\\WindowsPowerShell\\Modules' }).isPowerShell === false; const cmdSys = f({ PSModulePath: 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Modules' }).isPowerShell === false; const empty = f({}).isPowerShell === false; const src = read(__filename); const wired = src.includes('const fromEnv = _detectPwshFromEnv()') && src.includes('const pwshEnv = _detectPwshFromEnv()'); return pwsh7a && pwsh7b && pwsh7c && noFalsePs5 && cmdSys && empty && wired; } },
2931
2931
  { name: 'doc/surface 정합: doctor 명령 + stale MCP 카운트 동적화(commands/banner) (UR-0054 설치리뷰 1.9.315)', run: () => { const src = read(__filename); const doctorOk = typeof doctorCmd === 'function' && /cmd === 'doctor'/.test(src) && /# leerness doctor/.test(src); const dynCount = /MCP 도구: \$\{_mcpToolCount\(\)\}/.test(src) && /외부 AI 통합 \(MCP \$\{_mcpToolCount\(\)\} 도구\)/.test(src); return doctorOk && dynCount; } },
2932
- { name: 'drift 마커 버그: session-handoff 프론트매터는 ^--- 일 때만 + drift 최신 Last generated (1.9.316)', run: () => { const src = read(__filename); const writeFix = src.includes('if (/^---\\r?\\n/.test(cur))') && src.includes('writeUtf8(handoffPath(root), frontmatter + block)'); const readFix = src.includes('matchAll(/Last generated') && src.includes('allGen[allGen.length - 1]'); return writeFix && readFix; } },
2932
+ { name: 'drift 마커 버그: session-handoff 프론트매터는 ^--- 일 때만 + drift 최신 Last generated (1.9.316)', run: () => { const src = read(__filename); const scSrc = read(path.join(path.dirname(__filename), '..', 'lib', 'session-close.js')); const writeFix = scSrc.includes('if (/^---\\r?\\n/.test(cur))') && scSrc.includes('writeUtf8(handoffPath(root), frontmatter + block)'); const readFix = src.includes('matchAll(/Last generated') && src.includes('allGen[allGen.length - 1]'); return writeFix && readFix; } },
2933
2933
  { name: '텔레메트리 분리: 내부 auto-call(LEERNESS_INTERNAL) usage 집계 제외 + 주요 spawn 마킹 (UR-0051 설치리뷰 1.9.317)', run: () => { const src = read(__filename); const guard = src.includes("process.env.LEERNESS_INTERNAL !== '1'"); const marked = (src.match(/LEERNESS_INTERNAL: '1'/g) || []).length >= 10; const reviewMarked = /'review-request'[\s\S]{0,200}LEERNESS_INTERNAL: '1'/.test(src); return guard && marked && reviewMarked; } },
2934
2934
  { name: 'lib/pure-utils: HTML 파싱 유틸 3종 모듈 분리 + 동작 + 인라인 제거 (UR-0025 1.9.318)', run: () => { const m = require('../lib/pure-utils'); const fnOk = typeof m._htmlToText === 'function' && typeof m._extractTitle === 'function' && typeof m._extractLinks === 'function'; const work = m._htmlToText('<p>Hello <b>World</b></p>') === 'Hello World' && m._extractTitle('<html><title>My &amp; Page</title></html>') === 'My & Page' && m._extractLinks('<a href="/a">A</a><a href="https://other.com/b">B</a>', 'https://x.com/').length === 1; const moved = m._htmlToText === _htmlToText && !/^function _htmlToText\(html\) \{/m.test(read(__filename)); return fnOk && work && moved; } },
2935
2935
  { name: 'MCP ToolRegistry 일치성: 모든 도구 def 가 dispatch case 보유 + 고아 case 0 + requiredTier 완비 (UR-0044 1.9.319)', run: () => { const tools = require('../lib/mcp-tools'); const src = read(__filename); const missing = tools.filter(t => !src.includes("case '" + t.name + "':")); const cases = [...src.matchAll(/case '(leerness_[a-z_]+)':/g)].map(m => m[1]); const defNames = new Set(tools.map(t => t.name)); const orphans = [...new Set(cases)].filter(c => !defNames.has(c)); const tierOk = tools.every(t => typeof t.requiredTier === 'string' && PERMISSION_TIERS.includes(t.requiredTier)); return tools.length >= 83 && missing.length === 0 && orphans.length === 0 && tierOk; } },
@@ -3073,6 +3073,16 @@ function _selfTestCases() {
3073
3073
  } },
3074
3074
  { name: '9라운드 (UR-0119/0120): team review(메인 검수) — _composeTeamPlan reviewStep + handoff 검수필요 + team add 와이어 (1.9.414)', run: () => { const m = require('../lib/pure-utils'); const on = m._composeTeamPlan({ id: 't', members: ['a', 'b'], personas: ['security'] }, '점검'); const off = m._composeTeamPlan({ id: 't', members: ['a'], review: false }, '점검'); const planOk = on.review === true && !!on.reviewStep && on.reviewStep.suggestedCommand.includes('verify-claim') && off.review === false && !off.reviewStep; const rem = m._teamHandoffReminders([{ id: 'r', schedule: 'every-session', status: 'active', members: ['a'], review: true }]); const remOk = rem.length === 1 && rem[0].includes('검수필요'); const teamSrc = read(path.join(path.dirname(__filename), '..', 'lib', 'team.js')); const wired = teamSrc.includes("review: !has('--no-review')") && teamSrc.includes('메인 검수 (필수)'); return planOk && remOk && wired; } },
3075
3075
  { name: '파일명 변경 (UR-0126): bin 파일=leerness.js + package.json bin/main 일치 (1.9.419)', run: () => { const okName = path.basename(__filename) === 'leerness.js'; let pkg; try { pkg = require('../package.json'); } catch { return false; } const okBin = pkg && pkg.bin && pkg.bin.leerness === 'bin/leerness.js' && pkg.main === 'bin/leerness.js'; return okName && okBin; } },
3076
+ { name: 'UR-0025 큰핸들러 모듈화 10번째: sessionClose → lib/session-close.js + DI 위임 (1.9.425)', run: () => {
3077
+ const m = require('../lib/session-close');
3078
+ const expOk = typeof m.sessionClose === 'function';
3079
+ const src = read(__filename);
3080
+ const delegated = src.includes("require('../lib/session-close')") && src.includes('_sessionClose.sessionClose(root, opts,');
3081
+ const modSrc = read(path.join(path.dirname(__filename), '..', 'lib', 'session-close.js'));
3082
+ const bodyMarker = 'recommended' + 'Direction'; // session-close 본문 고유(split-literal 자기참조 회피)
3083
+ const movedToLib = modSrc.includes("require('./io')") && modSrc.includes("require('./pure-utils')") && modSrc.includes('STATUSES, MARK') && modSrc.includes(bodyMarker) && !src.includes(bodyMarker);
3084
+ return expOk && delegated && movedToLib;
3085
+ } },
3076
3086
  { name: 'UR-0025 큰핸들러 모듈화 9번째: agentsCmd → lib/agents.js + DI 위임 + rest→array (1.9.424)', run: () => {
3077
3087
  const m = require('../lib/agents');
3078
3088
  const expOk = typeof m.agentsCmd === 'function';
@@ -11243,605 +11253,9 @@ function llmBenchRecordCmd(root) {
11243
11253
  ok(`기록됨: ${histFile}`);
11244
11254
  }
11245
11255
 
11246
- function sessionClose(root, opts = {}) {
11247
- root = absRoot(root);
11248
- // 1.9.103: --json 모드 stdout 억제 구조화 출력
11249
- const jsonMode = !!opts.json || has('--json');
11250
- const _origWrite = process.stdout.write.bind(process.stdout);
11251
- if (jsonMode) process.stdout.write = () => true;
11252
- const jsonResult = { version: VERSION, root, closedAt: now() };
11253
- try {
11254
- const rows = readProgressRows(root);
11255
- const buckets = {};
11256
- for (const s of STATUSES) buckets[s] = [];
11257
- for (const r of rows) (buckets[r.status] || (buckets[r.status] = [])).push(r);
11258
- // 1.9.103: JSON 결과 누적
11259
- jsonResult.taskCounts = {};
11260
- for (const s of STATUSES) jsonResult.taskCounts[s] = (buckets[s] || []).length;
11261
- jsonResult.recommendedDirection = (buckets['in-progress'][0]?.request) || (buckets['planned'][0]?.request) || (buckets['requested'][0]?.request) || null;
11262
- jsonResult.nextExactStep = (buckets['in-progress'][0]?.nextAction) || (buckets['planned'][0]?.nextAction) || (buckets['requested'][0]?.nextAction) || null;
11263
-
11264
- function rowsToList(arr) {
11265
- if (!arr || !arr.length) return '- 없음';
11266
- return arr.map(r => `- ${r.id} ${r.request} → next: ${r.nextAction}`).join('\n');
11267
- }
11268
-
11269
- // 1.9.287 (Codex 리뷰 수렴): evidence 임베딩 시 코드펜스(```) 가 session-handoff.md 마크다운을 깨뜨리는 품질 버그 수정.
11270
- const evidenceSummary = _sanitizeFences(exists(evidencePath(root)) ? (read(evidencePath(root)).split('\n').slice(-30).join('\n')) : '(no review-evidence.md)');
11271
- const block = [
11272
- `# Session Handoff`,
11273
- ``,
11274
- `Last generated: ${now()}`,
11275
- ``,
11276
- `## Completed`,
11277
- rowsToList(buckets['done']),
11278
- ``,
11279
- `## In Progress`,
11280
- rowsToList(buckets['in-progress']),
11281
- ``,
11282
- `## Incomplete / Waiting / On Hold / Blocked`,
11283
- rowsToList([...(buckets['incomplete']||[]), ...(buckets['waiting']||[]), ...(buckets['on-hold']||[]), ...(buckets['blocked']||[])]),
11284
- ``,
11285
- `## Dropped`,
11286
- rowsToList(buckets['dropped']),
11287
- ``,
11288
- `## Verification`,
11289
- '```',
11290
- evidenceSummary.trim() || '(empty)',
11291
- '```',
11292
- ``,
11293
- `## Recommended Direction`,
11294
- `- ${(buckets['in-progress'][0]?.request) || (buckets['planned'][0]?.request) || (buckets['requested'][0]?.request) || '다음 우선순위를 사용자와 정합니다.'}`,
11295
- ``,
11296
- `## Next Exact Step`,
11297
- `- ${(buckets['in-progress'][0]?.nextAction) || (buckets['planned'][0]?.nextAction) || (buckets['requested'][0]?.nextAction) || '없음'}`,
11298
- ``
11299
- ].join('\n');
11300
- const cur = exists(handoffPath(root)) ? read(handoffPath(root)) : '';
11301
- // 1.9.316 (drift 마커 버그): 프론트매터는 파일이 '---' 로 시작할 때만 추출.
11302
- // 이전: 본문의 '---'(수평선/구분자)을 프론트매터 종료로 오인 → 구 블록(구 'Last generated')을 보존 →
11303
- // session-handoff.md 에 'Last generated' 중복 누적 → drift 가 첫(=구) 매치를 읽어 'session close 누락' 영구 오발화.
11304
- let frontmatter = '';
11305
- if (/^---\r?\n/.test(cur)) {
11306
- const fmEnd = cur.indexOf('\n---\n', 4);
11307
- if (fmEnd > 0) frontmatter = cur.slice(0, fmEnd + 5) + MARK + '\n';
11308
- }
11309
- writeUtf8(handoffPath(root), frontmatter + block);
11310
-
11311
- if (exists(currentStatePath(root))) {
11312
- let cs = read(currentStatePath(root));
11313
- cs = cs.replace(/Updated: \d{4}-\d{2}-\d{2}/, `Updated: ${today()}`);
11314
- cs = cs.replace(/## Now\n[\s\S]*?(?=\n## Next)/, `## Now\n- ${(buckets['in-progress'][0]?.request) || '대기 중'}\n`);
11315
- cs = cs.replace(/## Next\n[\s\S]*?(?=\n## Blockers)/, `## Next\n- ${(buckets['planned'][0]?.request) || (buckets['requested'][0]?.request) || '계획된 작업 없음'}\n`);
11316
- cs = cs.replace(/## Blockers\n[\s\S]*$/, `## Blockers\n${(buckets['blocked']||[]).map(b=>`- ${b.id} ${b.request}`).join('\n') || '-'}\n`);
11317
- writeUtf8(currentStatePath(root), cs);
11318
- }
11319
-
11320
- append(taskLogPath(root), `\n## ${today()} session-close\n- Generated session-handoff.md and refreshed current-state.md.\n`);
11321
-
11322
- log('# Session Close');
11323
- log('## Task Lists');
11324
- for (const s of STATUSES) {
11325
- log(`\n### ${s}`);
11326
- log(rowsToList(buckets[s]));
11327
- }
11328
- // 1.9.8: 룰 검증 자동 수행 + 보고
11329
- const ruleResults = verifyRules(root);
11330
- jsonResult.rules = ruleResults.map(r => ({ id: r.id, trigger: r.trigger, verified: r.verified, note: r.note }));
11331
- log('\n## ⚡ User Rules verification');
11332
- if (!ruleResults.length) log('- 활성 룰 없음');
11333
- else {
11334
- log('| ID | Trigger | Rule | Verified | Note |');
11335
- log('|---|---|---|---|---|');
11336
- const ic = { pass: '✓ pass', pending: '⓿ pending', manual: 'ⓘ manual', baseline: '○ baseline' };
11337
- for (const r of ruleResults) log(`| ${r.id} | ${r.trigger} | ${r.rule.slice(0, 40)} | ${ic[r.verified] || '?'} | ${r.note} |`);
11338
- }
11339
- log('\n## Required final response sections');
11340
- log('- 완료 작업\n- 진행 중 작업\n- 미완료/예정/대기/보류/차단/드랍 작업\n- 검증 결과\n- 추천 방향\n- 다음 정확한 작업\n- ⚡ 활성 룰별 검증 결과');
11341
- ok(`session-handoff.md and current-state.md updated`);
11342
- // 1.9.12: session close 끝에 roadmap.html 자동 갱신
11343
- _autoRoadmap(root, 'session-close');
11344
- // 1.9.57: --suggest 옵션 — 마감 시 skill suggest + drift check + lessons 통합 보고
11345
- // 1.9.59: default 활성 — --no-suggest로 명시 비활성 가능
11346
- const suggestEnabled = (has('--suggest') || (!has('--no-suggest') && process.env.LEERNESS_NO_SUGGEST !== '1'));
11347
- if (suggestEnabled) {
11348
- const isTty = process.stdout && process.stdout.isTTY;
11349
- const cy = s => isTty ? `\x1b[36m${s}\x1b[0m` : s;
11350
- const dim = s => isTty ? `\x1b[2m${s}\x1b[0m` : s;
11351
- log('');
11352
- log(cy('## 💡 다음 라운드 추천 (1.9.57 --suggest)'));
11353
- // 1) skill suggest
11354
- try {
11355
- const r = cp.spawnSync(process.execPath, [__filename, 'skill', 'suggest', '--path', root, '--min', '3', '--json'],
11356
- { encoding: 'utf8', timeout: 15000, env: { ...process.env, LEERNESS_INTERNAL: '1', LEERNESS_NO_PROMPT: '1', LEERNESS_NO_DRIFT_CHECK: '1' } });
11357
- const j = JSON.parse(r.stdout);
11358
- if (j.candidates && j.candidates.length) {
11359
- log(dim(' 📌 신규 skill 후보 (Hermes-style 자동 학습):'));
11360
- for (const c of j.candidates.slice(0, 3)) log(` • ${c.keyword} (${c.count}회 등장, 출처: ${c.source})`);
11361
- jsonResult.skillCandidates = j.candidates.slice(0, 5);
11362
- }
11363
- } catch {}
11364
- // 2) drift check
11365
- try {
11366
- const r = cp.spawnSync(process.execPath, [__filename, 'drift', 'check', root, '--json'],
11367
- { encoding: 'utf8', timeout: 15000, env: { ...process.env, LEERNESS_INTERNAL: '1', LEERNESS_NO_PROMPT: '1', LEERNESS_NO_DRIFT_CHECK: '0' } });
11368
- const j = JSON.parse(r.stdout.trim());
11369
- if (j.level) {
11370
- log(dim(` 🩺 drift 상태: ${j.level} ${j.score}/200`));
11371
- if (j.fired && j.fired.length) log(dim(` 🔥 ${j.fired.length}건 임계 초과 — \`leerness drift check\` 상세`));
11372
- jsonResult.drift = { level: j.level, score: j.score, fired: (j.fired || []).map(f => ({ label: f.label, weight: f.weight })) };
11373
- }
11374
- } catch {}
11375
- // 3) usage stats top
11376
- try {
11377
- const stats = _readUsageStats(root);
11378
- const entries = Object.entries(stats.commands || {}).sort((a, b) => b[1] - a[1]).slice(0, 3);
11379
- if (entries.length) {
11380
- log(dim(` 📊 가장 많이 쓴 명령: ${entries.map(([c, n]) => `${c}(${n})`).join(', ')}`));
11381
- jsonResult.topCommands = entries.map(([command, count]) => ({ command, count }));
11382
- }
11383
- // 1.9.74: MCP tools/call 통계 + rare 도구 노출
11384
- if (stats.mcp && stats.mcp.tools) {
11385
- const mcpEntries = Object.entries(stats.mcp.tools).sort((a, b) => b[1] - a[1]);
11386
- if (mcpEntries.length) {
11387
- const mcpTotal = mcpEntries.reduce((s, [, n]) => s + n, 0);
11388
- log(dim(` 🔌 MCP 호출 (1.9.74): 총 ${mcpTotal}회, top: ${mcpEntries.slice(0, 3).map(([t, n]) => `${t}(${n})`).join(', ')}`));
11389
- const threshold = Math.max(1, Math.floor(mcpTotal * 0.05));
11390
- const rare = mcpEntries.filter(([, n]) => n <= threshold).map(([t]) => t);
11391
- if (rare.length && mcpTotal >= 5) log(dim(` 💡 드물게 호출된 MCP: ${rare.slice(0, 4).join(', ')}`));
11392
- jsonResult.mcpStats = { total: mcpTotal, top: mcpEntries.slice(0, 5).map(([tool, count]) => ({ tool, count })), rare: rare.slice(0, 10) };
11393
- }
11394
- }
11395
- } catch {}
11396
- // 1.9.74: skill match query top (skill-suggestions.md 누적)
11397
- try {
11398
- const histPath = path.join(root, '.harness', 'skill-suggestions.md');
11399
- if (exists(histPath)) {
11400
- const histTxt = read(histPath);
11401
- const queries = [];
11402
- for (const block of histTxt.split(/\n(?=## )/)) {
11403
- const h = block.match(/^## ([\d-]+ [\d:]+) — query "([^"]+)"/);
11404
- if (h) queries.push(h[2]);
11405
- }
11406
- if (queries.length) {
11407
- // 같은 query 개수 카운트
11408
- const counts = {};
11409
- for (const q of queries) counts[q] = (counts[q] || 0) + 1;
11410
- const topQueries = Object.entries(counts).sort((a, b) => b[1] - a[1]).slice(0, 3);
11411
- log(dim(` 📒 skill match query 누적 (1.9.74): 총 ${queries.length}회 / 종류 ${Object.keys(counts).length}개`));
11412
- for (const [q, n] of topQueries) log(dim(` • "${q.slice(0, 50)}"${n > 1 ? ` (${n}회)` : ''}`));
11413
- }
11414
- }
11415
- } catch {}
11416
- log('');
11417
- }
11418
- // 1.9.13: 세션 카운터 + 자동 한 줄 요약 + 5세션마다 깊은 회고
11419
- try {
11420
- const sc = readSessionCounter(root);
11421
- sc.count = (sc.count || 0) + 1;
11422
- sc.lastCloseAt = now();
11423
- writeSessionCounter(root, sc);
11424
- const agg = _retroAggregate(root);
11425
- log(`\n## 📈 진행 요약 (session #${sc.count})`);
11426
- log(` ${_retroOneLine(agg)}`);
11427
- // 1.9.132: archive 활동 1줄 요약 — 마감 시점에 DELETE 활동 가시화 (handoff 7번째 회수와 symmetric)
11428
- try {
11429
- const hdSC = path.join(root, '.harness');
11430
- const arc = { d: 0, l: 0, p: 0, total: 0 };
11431
- for (const [k, f] of [['d', 'decisions.archive.md'], ['l', 'lessons.archive.md'], ['p', 'plan.archive.md']]) {
11432
- const fp = path.join(hdSC, f);
11433
- if (exists(fp)) {
11434
- const entries = _parseArchiveBlocks(read(fp));
11435
- arc[k] = entries.length;
11436
- arc.total += entries.length;
11437
- }
11438
- }
11439
- if (arc.total > 0) {
11440
- log(` 🗑 archive 누적: D${arc.d}/L${arc.l}/P${arc.p} (${arc.total}건) — 복원 후보: leerness memory archive list`);
11441
- }
11442
- } catch {}
11443
- if (sc.count % 5 === 0) {
11444
- log(`\n## 🔄 ${sc.count}세션 마일스톤 — 자동 회고 (5세션마다)`);
11445
- retroCmd(root);
11446
- sc.lastDeepRetroAt = now();
11447
- writeSessionCounter(root, sc);
11448
- } else {
11449
- const left = 5 - (sc.count % 5);
11450
- log(` 💡 ${left}세션 후 자동 깊은 회고 — \`leerness retro\`로 즉시 실행 가능`);
11451
- }
11452
- // 1.9.16: 워크스페이스 안내 (다른 leerness 프로젝트가 있으면)
11453
- try {
11454
- const wsCands = [path.resolve(root, '_apps'), path.resolve(root, '..', '_apps')];
11455
- let wsCount = 0;
11456
- for (const base of wsCands) {
11457
- if (!exists(base)) continue;
11458
- try { if (!fs.statSync(base).isDirectory()) continue; } catch { continue; }
11459
- for (const e of fs.readdirSync(base)) {
11460
- try {
11461
- const p = path.join(base, e);
11462
- if (fs.statSync(p).isDirectory() && exists(path.join(p, '.harness')) && p !== root) wsCount++;
11463
- } catch {}
11464
- }
11465
- }
11466
- if (wsCount > 0) log(` 🌐 워크스페이스에 ${wsCount}개 다른 leerness 프로젝트 — \`leerness retro --all-apps\`로 통합 회고`);
11467
- jsonResult.workspacePeers = wsCount;
11468
- } catch {}
11469
- } catch (e) {
11470
- warn('retro 요약 실패: ' + (e && e.message ? e.message : e));
11471
- jsonResult.retroSummaryError = e && e.message ? e.message : String(e);
11472
- }
11473
- } finally {
11474
- // 1.9.103: stdout 복원
11475
- if (jsonMode) process.stdout.write = _origWrite;
11476
- }
11477
- // 1.9.103: JSON 모드 — 구조화 출력
11478
- if (jsonMode) {
11479
- try {
11480
- const sc = readSessionCounter(root);
11481
- jsonResult.sessionNumber = sc.count;
11482
- } catch {}
11483
- // 1.9.122: memorySurface 통합 (handoff --json 1.9.115 와 동일 패턴)
11484
- try {
11485
- const rows0 = readProgressRows(root);
11486
- const tasksByStatus0 = {};
11487
- for (const s of STATUSES) tasksByStatus0[s] = 0;
11488
- for (const r of rows0) tasksByStatus0[r.status] = (tasksByStatus0[r.status] || 0) + 1;
11489
- const tasksInProgress0 = tasksByStatus0['in-progress'] || 0;
11490
- const decisionsCount0 = _loadDecisions(root).length; // 1.9.339 (UR-0053): canonical 단일 진실소스
11491
- const rules0 = readRules(root);
11492
- const rulesActive0 = rules0.filter(r => r.status === 'active').length;
11493
- const planText0 = exists(planPath(root)) ? read(planPath(root)) : '';
11494
- const milestones0 = (planText0.match(/^### M-\d{4}\./gm) || []).length;
11495
- const lessonsCount0 = _loadLessons(root).length;
11496
- // 1.9.130: archive 카운트 통합
11497
- const archiveCountsS = { decisions: 0, lessons: 0, plan: 0, total: 0 };
11498
- try {
11499
- const hdS = path.join(root, '.harness');
11500
- for (const [key, file] of [['decisions', 'decisions.archive.md'], ['lessons', 'lessons.archive.md'], ['plan', 'plan.archive.md']]) {
11501
- const fpS = path.join(hdS, file);
11502
- if (exists(fpS)) {
11503
- const entries = _parseArchiveBlocks(read(fpS));
11504
- archiveCountsS[key] = entries.length;
11505
- archiveCountsS.total += entries.length;
11506
- }
11507
- }
11508
- } catch {}
11509
- jsonResult.memorySurface = {
11510
- tasks: { inProgress: tasksInProgress0, total: rows0.length, byStatus: tasksByStatus0 },
11511
- decisions: { count: decisionsCount0 },
11512
- rules: { active: rulesActive0, total: rules0.length },
11513
- plan: { milestones: milestones0 },
11514
- lessons: { count: lessonsCount0 },
11515
- archive: archiveCountsS, // 1.9.130
11516
- summary: `T${tasksInProgress0}/D${decisionsCount0}/R${rulesActive0}/P${milestones0}/L${lessonsCount0}`,
11517
- };
11518
- // 1.9.142: featureCounts 통합 — session close JSON에 Feature Graph 통계
11519
- try {
11520
- const { nodes: fNodesC } = _readFeatureGraph(root);
11521
- const edgeCount = fNodesC.reduce((s, n) => s + (n.dependsOn?.length || 0) + (n.affects?.length || 0) + (n.coChangesWith?.length || 0), 0);
11522
- const linkedIds = new Set();
11523
- for (const n of fNodesC) {
11524
- for (const x of [...(n.dependsOn||[]), ...(n.affects||[]), ...(n.coChangesWith||[])]) { linkedIds.add(n.id); linkedIds.add(x); }
11525
- }
11526
- const isolated = fNodesC.length ? (fNodesC.length - linkedIds.size) : 0;
11527
- jsonResult.featureGraph = {
11528
- total: fNodesC.length,
11529
- edges: edgeCount,
11530
- isolated: Math.max(0, isolated),
11531
- summary: `F${fNodesC.length}/E${edgeCount}${isolated > 0 ? `/iso${isolated}` : ''}`
11532
- };
11533
- } catch {}
11534
- } catch {}
11535
-
11536
- // 1.9.217: session close 자동 통합 — 1.9.207 + 1.9.209 + 1.9.212
11537
- // 마감 시 미답 요청 / pre-wake audit / 멱등성 검사 자동 실행 + JSON 통합
11538
- try {
11539
- // 1.9.207: 미답 사용자 요청 audit
11540
- const reqAudit = _auditUserRequests(root);
11541
- jsonResult.userRequestsAudit = {
11542
- total: reqAudit.total,
11543
- open: reqAudit.open,
11544
- missing: reqAudit.missing ? reqAudit.missing.length : 0,
11545
- tracked: reqAudit.tracked ? reqAudit.tracked.length : 0,
11546
- stale: reqAudit.stale ? reqAudit.stale.length : 0
11547
- };
11548
- // 1.9.223: delivered 패턴 자동 감지 통합
11549
- try {
11550
- const delivered = _detectDeliveredRequests(root);
11551
- jsonResult.deliveredRequests = {
11552
- candidates: delivered.candidates.length,
11553
- currentVersion: delivered.currentVersion,
11554
- autoCompleteAvailable: delivered.candidates.length > 0
11555
- };
11556
- } catch {}
11557
- // 1.9.227: roundHistory 통합 (session close JSON 6번째 통합 필드)
11558
- try {
11559
- const rh = _computeRoundHistory(root);
11560
- jsonResult.roundHistory = {
11561
- roundCount: rh.roundCount,
11562
- baselineVersion: rh.baselineVersion,
11563
- nextMilestone: rh.nextMilestone,
11564
- roundsToNextMilestone: rh.roundsToNextMilestone,
11565
- daysActive: rh.daysActive,
11566
- avgRoundsPerDay: rh.avgRoundsPerDay
11567
- };
11568
- } catch {}
11569
- // 1.9.230: milestones 통합 (session close JSON 7번째 통합 필드)
11570
- try {
11571
- const ms = _computeMilestones(root);
11572
- jsonResult.milestones = {
11573
- reachedCount: ms.reached.length,
11574
- reached: ms.reached.map(m => ({ milestone: m.milestone, version: m.version, reachedAt: m.reachedAt })),
11575
- next: ms.next,
11576
- avgRoundsPerDay: ms.avgRoundsPerDay
11577
- };
11578
- } catch {}
11579
- // 1.9.234: recentChanges 통합 (session close JSON 8번째 통합 필드) — 최근 5 라운드 변경
11580
- try {
11581
- jsonResult.recentChanges = _computeRecentChanges(root, 5);
11582
- } catch {}
11583
- // 1.9.240: pyFiles 통합 (session close JSON 9번째 통합 필드) — UR-0013 2단계
11584
- try {
11585
- const pyFiles = _collectPyFiles(root, 200);
11586
- const analyses = pyFiles.slice(0, 200).map(f => _analyzePyFile(f)).filter(Boolean);
11587
- jsonResult.pyFiles = {
11588
- total: pyFiles.length,
11589
- analyzed: analyses.length,
11590
- totalLOC: analyses.reduce((s, a) => s + a.loc, 0),
11591
- totalImports: analyses.reduce((s, a) => s + a.imports, 0),
11592
- totalFuncs: analyses.reduce((s, a) => s + a.funcs, 0),
11593
- totalClasses: analyses.reduce((s, a) => s + a.classes, 0)
11594
- };
11595
- } catch {}
11596
- // 1.9.242: envInfo 통합 (session close JSON 10번째 통합 필드) — UR-0014 2단계
11597
- try {
11598
- const runtimeEnv = _collectRuntimeEnv();
11599
- const encScan = _scanShellScriptsEncoding(root);
11600
- jsonResult.envInfo = {
11601
- os: runtimeEnv.os.platform,
11602
- isKoreanWindows: runtimeEnv.locale.isKoreanWindows || false,
11603
- codepage: runtimeEnv.locale.codepage || null,
11604
- nodeVersion: runtimeEnv.node.version,
11605
- shellScriptsScanned: encScan.scanned,
11606
- encodingRiskCount: encScan.atRisk.length,
11607
- encodingRiskFiles: encScan.atRisk.slice(0, 5).map(r => r.file),
11608
- // 1.9.249 (UR-0018): 터미널 출력 인코딩 안전 여부 + 자동 회복 결과
11609
- terminalEncodingOk: runtimeEnv.locale.codepage === 65001 || !runtimeEnv.locale.isKoreanWindows,
11610
- autoChcpApplied: process.env._LEERNESS_AUTOCHCP_APPLIED || null,
11611
- // 1.9.250 (UR-0018 2단계): POSIX (Linux/macOS/WSL) terminal encoding 점검
11612
- posixEncodingOk: runtimeEnv.locale.posixEncodingOk,
11613
- isWSL: runtimeEnv.locale.isWSL || false
11614
- };
11615
- } catch {}
11616
- // 1.9.245: apiSkills 통합 (session close JSON 11번째 통합 필드) — UR-0015
11617
- try {
11618
- const allSkills = _listAPISkills(root);
11619
- let currentTaskText = '';
11620
- try {
11621
- const rows = readProgressRows(root);
11622
- const ip = rows.find(r => r.status === 'in-progress');
11623
- if (ip) currentTaskText = (ip.title || '') + ' ' + (ip.notes || '');
11624
- } catch {}
11625
- const matched = currentTaskText ? _matchAPISkills(root, currentTaskText) : [];
11626
- jsonResult.apiSkills = {
11627
- total: allSkills.length,
11628
- matched: matched.length,
11629
- matchedIds: matched.slice(0, 5).map(s => s.id),
11630
- ids: allSkills.slice(0, 10).map(s => s.id)
11631
- };
11632
- } catch {}
11633
- // 1.9.264: shellGuard 통합 (session close JSON 12번째 통합 필드) — UR-0020 셸 실패 메모리 + 환경 변동
11634
- try {
11635
- const sf = _loadShellFailures(root);
11636
- const drift = _shellEnvDrift(root);
11637
- jsonResult.shellGuard = {
11638
- failureCount: sf.failures.length,
11639
- recent: sf.failures.slice(-3).map(f => ({ cmd: (f.cmd || '').slice(0, 50), exitCode: f.exitCode, shell: f.shell, rules: f.issues || [] })),
11640
- envDriftChanges: drift && drift.changes ? drift.changes.length : 0,
11641
- envDrift: drift ? drift.changes : null
11642
- };
11643
- } catch {}
11644
- } catch {}
11645
- try {
11646
- // 1.9.209: pre-wake-audit 자동 실행 + 저장 (sleep 전 자동 점검)
11647
- if (!opts.noPreWake && !has('--no-pre-wake')) {
11648
- const audit = _runPreWakeAudit(root);
11649
- _saveAndAppendPreWakeReport(root, audit);
11650
- jsonResult.preWakeAudit = {
11651
- auditedAt: audit.auditedAt,
11652
- critical: audit.summary.criticalCount,
11653
- warning: audit.summary.warningCount,
11654
- info: audit.summary.infoCount,
11655
- needsAttention: audit.summary.needsAttention
11656
- };
11657
- }
11658
- } catch {}
11659
- try {
11660
- // 1.9.212: 멱등성 검사 자동 실행 (rule/task/user-requests/wakeups 4영역)
11661
- const idemp = _runIdempotencyAudit(root);
11662
- jsonResult.idempotencyAudit = {
11663
- violations: idemp.summary.totalViolations,
11664
- high: idemp.summary.highSeverity,
11665
- medium: idemp.summary.mediumSeverity,
11666
- low: idemp.summary.lowSeverity,
11667
- verified: idemp.summary.verifiedAreas,
11668
- overall: idemp.summary.overall
11669
- };
11670
- } catch {}
11671
- try {
11672
- // 1.9.221: abnormalShutdown 자동 감지 (1.9.220 통합) — session close 시 다음 재개 가이드 회수
11673
- const ad = _detectAbnormalShutdown(root);
11674
- jsonResult.abnormalShutdown = {
11675
- detected: ad.abnormalShutdown,
11676
- severity: ad.severity,
11677
- signalCount: ad.signals.length,
11678
- signals: ad.signals.map(s => ({ kind: s.kind, severity: s.severity, detail: s.detail })),
11679
- resumeGuide: ad.resumeGuide
11680
- };
11681
- } catch {}
11682
-
11683
- process.stdout.write(JSON.stringify(jsonResult, null, 2) + '\n');
11684
- } else {
11685
- // 1.9.217: human 출력 모드에서도 통합 보고 노출 (마감 직전)
11686
- try {
11687
- const isTty = process.stdout.isTTY;
11688
- const grn = s => isTty ? `\x1b[32m${s}\x1b[0m` : s;
11689
- const yel = s => isTty ? `\x1b[33m${s}\x1b[0m` : s;
11690
- const red = s => isTty ? `\x1b[31m${s}\x1b[0m` : s;
11691
- const dim = s => isTty ? `\x1b[2m${s}\x1b[0m` : s;
11692
-
11693
- log('');
11694
- log(`## 🔚 session close 자동 통합 보고 (1.9.217)`);
11695
- // 1.9.207 + 1.9.223 (delivered 패턴 자동 권장) + 1.9.224 (--auto-apply-delivered 옵션)
11696
- try {
11697
- const reqAudit = _auditUserRequests(root);
11698
- const missCnt = reqAudit.missing ? reqAudit.missing.length : 0;
11699
- let delivered = { candidates: [] };
11700
- try { delivered = _detectDeliveredRequests(root); } catch {}
11701
- if (delivered.candidates && delivered.candidates.length > 0) {
11702
- if (has('--auto-apply-delivered')) {
11703
- // 1.9.224: 자동 정리 (마감 시 호출 — 안전: 패턴 매칭 + 버전 가드)
11704
- let ok = 0;
11705
- for (const c of delivered.candidates) {
11706
- const u = _updateUserRequest(root, c.id, { status: 'completed', autoCompletedAt: new Date().toISOString(), autoCompleteReason: 'session-close-auto-apply-1.9.224' });
11707
- if (u) ok++;
11708
- }
11709
- log(grn(` ✓ delivered 패턴 ${ok}건 자동 완료 (--auto-apply-delivered 1.9.224)`));
11710
- } else {
11711
- log(yel(` 📥 delivered 패턴 ${delivered.candidates.length}건 (1.9.223) — 자동 완료 가능`));
11712
- log(dim(` → leerness requests auto-complete --apply (수동) 또는 session close --auto-apply-delivered (1.9.224)`));
11713
- }
11714
- } else if (missCnt > 0) {
11715
- log(red(` ⚠ 미답 사용자 요청 ${missCnt}건 (task-log/plan/decisions 매칭 안 됨)`));
11716
- } else if (reqAudit.open > 0) {
11717
- log(grn(` ✓ 사용자 요청 ${reqAudit.open}건 모두 tracked`));
11718
- } else {
11719
- log(dim(` ℹ 사용자 요청 없음 (UR 백로그 비어있음)`));
11720
- }
11721
- } catch {}
11722
- // 1.9.209
11723
- try {
11724
- if (!opts.noPreWake && !has('--no-pre-wake')) {
11725
- const audit = _runPreWakeAudit(root);
11726
- _saveAndAppendPreWakeReport(root, audit);
11727
- const sum = audit.summary;
11728
- if (sum.criticalCount > 0) {
11729
- log(red(` 🚨 pre-wake-audit: critical ${sum.criticalCount} (다음 깨어남 시 점검 필요)`));
11730
- } else if (sum.warningCount > 0) {
11731
- log(yel(` ⚠ pre-wake-audit: warning ${sum.warningCount}`));
11732
- } else {
11733
- log(grn(` ✓ pre-wake-audit: clean (sleep 안전)`));
11734
- }
11735
- }
11736
- } catch {}
11737
- // 1.9.212
11738
- try {
11739
- const idemp = _runIdempotencyAudit(root);
11740
- const v = idemp.summary.totalViolations;
11741
- if (v > 0) {
11742
- log(red(` ⚠ 멱등성 위반 ${v}건 (high: ${idemp.summary.highSeverity})`));
11743
- log(dim(` → leerness idempotency audit 으로 상세 확인`));
11744
- } else {
11745
- log(grn(` ✓ 멱등성 검사 통과 — verified ${idemp.summary.verifiedAreas} 영역`));
11746
- }
11747
- } catch {}
11748
- // 1.9.264: 셸 실패 메모리 + 환경 변동 요약 (UR-0020) — 마감 시 이번 세션 셸 실패를 회고에 노출
11749
- try {
11750
- const sf = _loadShellFailures(root);
11751
- const drift = _shellEnvDrift(root);
11752
- const driftN = drift && drift.changes ? drift.changes.length : 0;
11753
- if (sf.failures.length > 0 || driftN > 0) {
11754
- if (driftN > 0) log(yel(` ⚠ 환경 버전 변동 ${driftN}건 — 다음 세션 셸 실패 기록 재검토 권장`));
11755
- if (sf.failures.length > 0) {
11756
- log(yel(` 🐚 셸 실패 누적 ${sf.failures.length}건 — 다음 handoff 가 자동 노출`));
11757
- log(dim(` → 명령 실행 전 점검: leerness shell-guard "<command>"`));
11758
- }
11759
- } else {
11760
- log(grn(` ✓ 셸 실패 기록 없음 (터미널 호환성 양호)`));
11761
- }
11762
- } catch {}
11763
- // 1.9.237: session close --auto-cleanup-branches — 50+ release/* branches 시 자동 정리
11764
- // 1.9.224 패턴 (--auto-apply-delivered) 확장 — 마감 시 운영 누적 폐기물 자동 정리
11765
- // 안전: keep 10, merged 만, 현재 branch 보호
11766
- try {
11767
- const branchR = cp.spawnSync('git', ['branch', '--merged', 'main', '--list', 'release/*'], { cwd: root, encoding: 'utf8' });
11768
- if (branchR.status === 0) {
11769
- const merged = (branchR.stdout || '').split('\n')
11770
- .map(l => l.replace(/^\*?\s+/, '').trim())
11771
- .filter(l => l && /^release\/\d+\.\d+\.\d+$/.test(l));
11772
- if (merged.length > 50) {
11773
- if (has('--auto-cleanup-branches')) {
11774
- merged.sort((a, b) => {
11775
- const va = a.replace('release/', '').split('.').map(n => parseInt(n, 10) || 0);
11776
- const vb = b.replace('release/', '').split('.').map(n => parseInt(n, 10) || 0);
11777
- for (let i = 0; i < 3; i++) if (va[i] !== vb[i]) return vb[i] - va[i];
11778
- return 0;
11779
- });
11780
- const curR = cp.spawnSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: root, encoding: 'utf8' });
11781
- const cur = (curR.stdout || '').trim();
11782
- const toDelete = merged.slice(10).filter(b => b !== cur);
11783
- let okCnt = 0;
11784
- for (const b of toDelete) {
11785
- const r = cp.spawnSync('git', ['branch', '-d', b], { cwd: root, encoding: 'utf8' });
11786
- if (r.status === 0) okCnt++;
11787
- }
11788
- log(grn(` ✓ release 정리 ${okCnt}/${toDelete.length}건 (--auto-cleanup-branches 1.9.237, keep 10)`));
11789
- } else {
11790
- log(yel(` 🗑 release/* merged ${merged.length}개 (50+) — cleanup 가능 (1.9.235)`));
11791
- log(dim(` → leerness release cleanup --apply --keep 10 (수동)`));
11792
- log(dim(` → 또는 session close --auto-cleanup-branches (1.9.237 자동)`));
11793
- }
11794
- }
11795
- }
11796
- } catch {}
11797
- // 1.9.243: session close --auto-fix-encoding — 셸 스크립트 인코딩 위험 자동 회복 (UR-0014 3단계)
11798
- // 1.9.224 (--auto-apply-delivered) / 1.9.237 (--auto-cleanup-branches) 패턴 확장
11799
- // 마감 시 한국어/일본어/중국어 PowerShell 인코딩 위험 자동 BOM 추가
11800
- try {
11801
- const encScan = _scanShellScriptsEncoding(root);
11802
- if (encScan.atRisk && encScan.atRisk.length > 0) {
11803
- if (has('--auto-fix-encoding')) {
11804
- let ok = 0;
11805
- for (const r of encScan.atRisk) {
11806
- try {
11807
- const fullPath = path.join(root, r.file);
11808
- const orig = fs.readFileSync(fullPath);
11809
- const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
11810
- const fixed = Buffer.concat([bom, orig]);
11811
- fs.writeFileSync(fullPath, fixed);
11812
- ok++;
11813
- } catch {}
11814
- }
11815
- log(grn(` ✓ 인코딩 위험 ${ok}/${encScan.atRisk.length}건 UTF-8 BOM 자동 추가 (--auto-fix-encoding 1.9.243)`));
11816
- } else {
11817
- log(yel(` ⚠ 셸 스크립트 인코딩 위험 ${encScan.atRisk.length}건 (1.9.241) — 자동 회복 가능`));
11818
- log(dim(` → leerness env encoding --apply (수동) 또는 session close --auto-fix-encoding (1.9.243 자동)`));
11819
- }
11820
- }
11821
- } catch {}
11822
- // 1.9.232: 마감 시 pulse 한 줄 자동 노출 — 다음 라운드 진입 시 즉시 상태 인지
11823
- try {
11824
- const rh = _computeRoundHistory(root);
11825
- const ms = _computeMilestones(root);
11826
- const rows = readProgressRows(root);
11827
- const tIn = rows.filter(r => r.status === 'in-progress').length;
11828
- const dCnt = _loadDecisions(root).length; // 1.9.339 (UR-0053): canonical 단일 진실소스
11829
- const rActive = readRules(root).filter(r => r.status === 'active').length;
11830
- const planText = exists(planPath(root)) ? read(planPath(root)) : '';
11831
- const pCnt = (planText.match(/^### M-\d{4}\./gm) || []).length;
11832
- const lCnt = _loadLessons(root).length;
11833
- const mem = `T${tIn}/D${dCnt}/R${rActive}/P${pCnt}/L${lCnt}`;
11834
- let pulseLine = `📍 v${VERSION} · 🔄 R${rh.roundCount} · 🧠 ${mem}`;
11835
- if (ms.next) {
11836
- const eta = ms.next.etaDays != null ? ` (${ms.next.etaDays}d)` : '';
11837
- pulseLine += ` · 🎯 R${ms.next.milestone}${eta}`;
11838
- }
11839
- log('');
11840
- log(` ${pulseLine} ${dim('— leerness pulse (1.9.232)')}`);
11841
- } catch {}
11842
- } catch {}
11843
- }
11844
- }
11256
+ const _sessionClose = require('../lib/session-close');
11257
+ // 1.9.425 (UR-0025/UR-0125 큰 핸들러 모듈화 10번째): sessionClose → lib/session-close.js (DI 위임)
11258
+ function sessionClose(root, opts = {}) { return _sessionClose.sessionClose(root, opts, { VERSION, STATUSES, MARK, has, arg, harnessPath: __filename, readProgressRows, evidencePath, handoffPath, currentStatePath, taskLogPath, verifyRules, _autoRoadmap, _readUsageStats, readSessionCounter, writeSessionCounter, _retroAggregate, _retroOneLine, retroCmd, _loadDecisions, readRules, planPath, _loadLessons, _readFeatureGraph, _auditUserRequests, _detectDeliveredRequests, _computeRoundHistory, _computeMilestones, _computeRecentChanges, _collectPyFiles, _analyzePyFile, _collectRuntimeEnv, _scanShellScriptsEncoding, _listAPISkills, _matchAPISkills, _loadShellFailures, _shellEnvDrift, _runPreWakeAudit, _saveAndAppendPreWakeReport, _runIdempotencyAudit, _detectAbnormalShutdown, _updateUserRequest }); }
11845
11259
 
11846
11260
  function readmeCmd(root) { syncReadme(absRoot(root)); }
11847
11261
  function consistencyCheck(root) {