leerness 1.9.390 → 1.9.392

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/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.9.392 — 2026-06-06 — UR-0025 큰 핸들러 모듈화 4번째: doctor/which → lib/diagnostics.js (DI)
4
+
5
+ **🧩 네 번째 핸들러 모듈 — 진단 명령(doctor/which)을 lib/diagnostics.js 로 분리.**
6
+
7
+ ### 구현
8
+ 1. **lib/diagnostics.js 신규**: doctorCmd + whichCmd 이전.
9
+ - 직접 require: `./io`(log) · node child_process.
10
+ - **DI 주입**: VERSION · _selfTestCases · _detectShellCtx · _mcpToolCount · has · harnessPath.
11
+ - `_selfTestCases` 의 각 case.run 클로저는 harness 모듈 스코프를 유지 → 함수 참조 주입만으로 정상 동작.
12
+ 2. **harness thin wrapper**: deps 구성 후 위임. dispatch·동작·출력·exit code 무변경.
13
+
14
+ ### 검증 (회귀 0)
15
+ - **selftest 137→138 PASS** (lib/diagnostics 2 exports + 위임 와이어 + lib 본문 이동 교차참조 + behavioral: stub _selfTestCases(빈 배열)로 lib doctorCmd 호출 → 재귀 회피 + report.version/selftest/healthy/mcpTools 검증).
16
+ - **E2E 332 유지 PASS** (doctor/which 회귀). 락 flake 시 재실행.
17
+ - 실측: doctor(--json selftest 137/137 healthy + 사람용 + exit0) · which(--json runningFrom/diagnostics + 사람용) 보존.
18
+
19
+ ## 1.9.391 — 2026-06-06 — UR-0025 큰 핸들러 모듈화 3번째: feature → lib/feature.js (DI)
20
+
21
+ **🧩 세 번째 핸들러 모듈 — feature add/link/impact/list/show 를 lib/feature.js 로 분리. 1.9.390 순수 코어 토대 위에 완성.**
22
+
23
+ ### 배경 (UR-0025, 사용자 승인 모듈화)
24
+ migrate(1.9.388)/team(1.9.389) 에 이어 세 번째. 1.9.390 에서 feature-graph 순수 코어를 pure-utils 로 뺀 덕에 이제 핸들러를 깨끗이 분리 가능.
25
+
26
+ ### 구현
27
+ 1. **lib/feature.js 신규**: 5 핸들러(add/link/impact/list/show) 이전.
28
+ - 직접 require: `./io`(absRoot/log/ok/warn/fail) · `./pure-utils`(_nextFeatureId/_featureImpactBfs).
29
+ - **DI 주입**: _ensureFeatureGraph · _readFeatureGraph · _writeFeatureGraph(feature-graph I/O 헬퍼) · arg · has.
30
+ 2. **_featureImpactBfs → pure-utils**: 영향 BFS(affects/co-changes transitive + depends-on 역방향)는 순수 + handoff(8613)/audit(19302)도 공유 → pure-utils 로 이동, harness+lib 양쪽 import.
31
+ 3. **I/O 헬퍼는 harness 유지**: _readFeatureGraph(7+곳 공유) 등은 그대로, deps 로 주입.
32
+ 4. **harness thin wrapper**: _featureDeps() 구성 후 5 wrapper 위임. dispatch·MCP·동작·출력 무변경.
33
+
34
+ ### 검증 (회귀 0)
35
+ - **selftest 136→137 PASS** (lib/feature 5 exports + _featureImpactBfs reference-equality + BFS 동작 + 위임 와이어 + lib 본문 이동 교차참조 + behavioral list --json).
36
+ - **E2E 332 유지 PASS** (feature add/link/impact/list/show + 공유 _featureImpactBfs(handoff/audit) 회귀). 락 flake 시 재실행.
37
+ - 실측: add(depends-on)·link(affects)·impact(transitive)·list·show(--json)·에러(BADID exit1)·handoff(공유 BFS) 보존.
38
+
3
39
  ## 1.9.390 — 2026-06-06 — UR-0025 모듈화: feature-graph 순수 코어 → pure-utils (feature 핸들러 분리 토대)
4
40
 
5
41
  **🧩 feature-graph 의 순수 로직(템플릿/파서/ID/블록 렌더)을 lib/pure-utils.js 로 분리 — 가장 많이 공유되는 서브시스템의 핵심을 단일출처·테스트 가능화.**
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  > **AI 코딩 에이전트의 거짓 완료·중복·망각·충돌을 막아주는 검수·기억·협업 CLI 하네스.**
4
4
  > **A CLI harness that stops AI coding agents from faking completion, duplicating work, forgetting context, and colliding.**
5
5
 
6
- [![npm](https://img.shields.io/badge/npm-leerness-blue)](https://www.npmjs.com/package/leerness) [![version](https://img.shields.io/badge/version-1.9.390-green)]() [![tests](https://img.shields.io/badge/e2e-332%2F332-success)]() [![selftest](https://img.shields.io/badge/selftest-136-success)]() [![mcp](https://img.shields.io/badge/MCP--tools-85-brightgreen)]() [![providers](https://img.shields.io/badge/AI_providers-10-brightgreen)]() [![license](https://img.shields.io/badge/license-MIT-lightgrey)]()
6
+ [![npm](https://img.shields.io/badge/npm-leerness-blue)](https://www.npmjs.com/package/leerness) [![version](https://img.shields.io/badge/version-1.9.392-green)]() [![tests](https://img.shields.io/badge/e2e-332%2F332-success)]() [![selftest](https://img.shields.io/badge/selftest-138-success)]() [![mcp](https://img.shields.io/badge/MCP--tools-85-brightgreen)]() [![providers](https://img.shields.io/badge/AI_providers-10-brightgreen)]() [![license](https://img.shields.io/badge/license-MIT-lightgrey)]()
7
7
 
8
8
  ```
9
9
  ╔══════════════════════════════════════════════════════════════╗
@@ -471,7 +471,7 @@ MIT — © leerness contributors
471
471
  <!-- leerness:project-readme:start -->
472
472
  ## Leerness Project Harness
473
473
 
474
- 이 프로젝트는 Leerness v1.9.390 하네스를 사용합니다. AI 에이전트는 작업 전 `leerness handoff`로 컨텍스트를 적재하고, 작업 후 `leerness check`/`leerness audit`/`leerness session close`를 수행해야 합니다.
474
+ 이 프로젝트는 Leerness v1.9.392 하네스를 사용합니다. AI 에이전트는 작업 전 `leerness handoff`로 컨텍스트를 적재하고, 작업 후 `leerness check`/`leerness audit`/`leerness session close`를 수행해야 합니다.
475
475
 
476
476
  ### 정체성 — AI 에이전트 운영 레이어 (UR-0030)
477
477
 
@@ -525,7 +525,7 @@ leerness memory restore decision <date|title>
525
525
 
526
526
  ### MCP server (외부 AI 통합)
527
527
 
528
- Leerness v1.9.390는 stdio JSON-RPC MCP server를 내장합니다 — Claude Code · Cursor · Codex CLI 등 외부 AI에 **85개 도구**를 노출:
528
+ Leerness v1.9.392는 stdio JSON-RPC MCP server를 내장합니다 — Claude Code · Cursor · Codex CLI 등 외부 AI에 **85개 도구**를 노출:
529
529
 
530
530
  ```jsonc
531
531
  // 카테고리별
@@ -546,7 +546,7 @@ Leerness v1.9.390는 stdio JSON-RPC MCP server를 내장합니다 — Claude Cod
546
546
  `<<autonomous-loop-dynamic>>` 신호만 보내면 AI가:
547
547
  1) 다음 라운드 후보 선정 → 2) 코드 변경 → 3) stress-v* 신규 작성 + 누적 회귀 → 4) e2e 219/219 → 5) npm pack + git tag + GitHub release → 6) main 자동 push (1.9.140+) → 7) session close → 8) 다음 라운드 예약.
548
548
 
549
- 현재 누적: **70 라운드 (1.9.40 → 1.9.390)** · 매 라운드 GitHub release/태그 생성 · _reports/는 비공개 보존.
549
+ 현재 누적: **70 라운드 (1.9.40 → 1.9.392)** · 매 라운드 GitHub release/태그 생성 · _reports/는 비공개 보존.
550
550
 
551
551
  ### 성능 가이드 (1.9.140 측정)
552
552
 
@@ -584,6 +584,6 @@ leerness release pack --close --auto-main-push
584
584
  - `.harness/session-handoff.md`: 다음 세션 인수인계 (자동 작성)
585
585
  - `.harness/lessons.md` / `decisions.md` / `rules.md`: 영구 메모리 (5 surface)
586
586
 
587
- Last synced by Leerness v1.9.390: 2026-06-06
587
+ Last synced by Leerness v1.9.392: 2026-06-06
588
588
  <!-- leerness:project-readme:end -->
589
589
 
package/bin/harness.js CHANGED
@@ -24,13 +24,13 @@ const { _isSecretKey, _isPlaceholderSecret, _looksSecretLike, _mergeLines, _merg
24
24
  _decisionsFromMd, _renderDecisionsMd, _renderLessonsMd,
25
25
  _withBuiltinSource, _esc, _roadmapTokenStyles, _parseSkillMd,
26
26
  _migrationGuideText, _parseContractSpec, _gitignoreMatch,
27
- _featureGraphTemplate, _parseFeatureGraph, _nextFeatureId, _featureBlock } = require('../lib/pure-utils'); // 1.9.318~390 (UR-0025/0053/0075/0086/0087): 순수 유틸 모듈 분리
27
+ _featureGraphTemplate, _parseFeatureGraph, _nextFeatureId, _featureBlock, _featureImpactBfs } = require('../lib/pure-utils'); // 1.9.318~391 (UR-0025/0053/0075/0086/0087): 순수 유틸 모듈 분리
28
28
  // 1.9.304 (UR-0025): 순수 분석/검증 함수 모듈 분리.
29
29
  const { _evidenceQuality, _parseEvidenceStats, _shellGuardAnalyze, _claimFileInGit, _epistemicHonestyCheck } = require('../lib/analyzers');
30
30
  // 1.9.295 (UR-0025 4단계): 정적 데이터 카탈로그 모듈 분리 (비파괴, require-based).
31
31
  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 포함)
32
32
 
33
- const VERSION = '1.9.390';
33
+ const VERSION = '1.9.392';
34
34
 
35
35
  // 1.9.290 (UR-0037, Codex gpt-5.5 #4 수렴): CLI 전용 부작용은 require 시 실행하지 않는다.
36
36
  // 이전: warning listener 제거 / NODE_OPTIONS 변경 / chcp IIFE 가 top-level 즉시 실행 → require('harness') 시 호스트 프로세스 오염.
@@ -2994,6 +2994,8 @@ function _selfTestCases() {
2994
2994
  { name: 'UR-0025 큰핸들러 모듈화: migrate audit/apply/plan → lib/migrate.js + DI 위임 + 동작 (1.9.388)', run: () => { const m = require('../lib/migrate'); const expOk = typeof m.migrateAuditCmd === 'function' && typeof m.migrateApplyCmd === 'function' && typeof m.migratePlanCmd === 'function'; const src = read(__filename); const delegated = src.includes("require('../lib/migrate')") && src.includes('_migrate.migrateAuditCmd(root, opts, _migrateDeps())') && src.includes('_migrate.migratePlanCmd(root, opts, _migrateDeps())'); const movedToLib = read(path.join(path.dirname(__filename), '..', 'lib', 'migrate.js')).includes('leerness-plan-'); let behavOk = false; const tmp = fs.mkdtempSync(path.join(os.tmpdir(), '__leerness_mig_')); const save = process.argv; const _w = process.stdout.write; let out = ''; try { fs.mkdirSync(path.join(tmp, '.harness'), { recursive: true }); fs.writeFileSync(path.join(tmp, '.harness', 'HARNESS_VERSION'), VERSION); process.argv = ['node', 'h', 'migrate', 'audit', tmp, '--json']; process.stdout.write = s => { out += s; return true; }; migrateAuditCmd(tmp, { json: true }); } catch {} finally { process.stdout.write = _w; process.argv = save; try { fs.rmSync(tmp, { recursive: true, force: true }); } catch {} } try { const j = JSON.parse(out); behavOk = j.version === VERSION && typeof j.willChange === 'number' && Array.isArray(j.findings); } catch {} return expOk && delegated && movedToLib && behavOk; } },
2995
2995
  { name: 'UR-0025 큰핸들러 모듈화: teamCmd → lib/team.js + DI 위임 + 동작 (1.9.389)', run: () => { const m = require('../lib/team'); const expOk = typeof m.teamCmd === 'function'; const src = read(__filename); const delegated = src.includes("require('../lib/team')") && src.includes('_team.teamCmd(root, sub, id, opts,'); const teamSrc = read(path.join(path.dirname(__filename), '..', 'lib', 'team.js')); const movedToLib = teamSrc.includes("require('./pure-utils')") && teamSrc.includes('_teamDeployGate') && teamSrc.includes('알 수 없는 team 하위명령'); let behavOk = false; const tmp = fs.mkdtempSync(path.join(os.tmpdir(), '__leerness_tm_')); const save = process.argv; const _w = process.stdout.write; let out = ''; try { fs.mkdirSync(path.join(tmp, '.harness'), { recursive: true }); process.argv = ['node', 'h', 'team', 'list', '--json']; process.stdout.write = s => { out += s; return true; }; teamCmd(tmp, 'list', undefined, { json: true }); } catch {} finally { process.stdout.write = _w; process.argv = save; try { fs.rmSync(tmp, { recursive: true, force: true }); } catch {} } try { const j = JSON.parse(out); behavOk = j.version === VERSION && j.count === 0 && Array.isArray(j.teams); } catch {} return expOk && delegated && movedToLib && behavOk; } },
2996
2996
  { name: 'UR-0025: feature-graph 순수 코어(_featureGraphTemplate/_parseFeatureGraph/_nextFeatureId/_featureBlock) → pure-utils + round-trip (1.9.390)', run: () => { const m = require('../lib/pure-utils'); const refOk = m._parseFeatureGraph === _parseFeatureGraph && m._featureGraphTemplate === _featureGraphTemplate && m._nextFeatureId === _nextFeatureId && m._featureBlock === _featureBlock; const tmpl = m._featureGraphTemplate(); const tmplOk = tmpl.includes('Feature Graph') && tmpl.includes('## Nodes'); const nodes = m._parseFeatureGraph('## F-0001 Auth\n- depends-on: F-0002\n- affects: F-0003\n- files: a.js\n'); const parseOk = nodes.length === 1 && nodes[0].id === 'F-0001' && nodes[0].title === 'Auth' && nodes[0].dependsOn[0] === 'F-0002' && nodes[0].affects[0] === 'F-0003' && nodes[0].files[0] === 'a.js'; const idOk = m._nextFeatureId(nodes) === 'F-0002'; const rt = m._parseFeatureGraph(m._featureBlock(nodes[0])); const rtOk = rt.length === 1 && rt[0].id === 'F-0001' && rt[0].dependsOn[0] === 'F-0002'; const src = read(__filename); const moved = src.includes("require('../lib/pure-utils')") && !/^function _parseFeatureGraph\(text\) \{/m.test(src) && !/^function _featureBlock\(node\) \{/m.test(src); return refOk && tmplOk && parseOk && idOk && rtOk && moved; } },
2997
+ { name: 'UR-0025 큰핸들러 모듈화: feature add/link/impact/list/show → lib/feature.js + DI + _featureImpactBfs pure 공유 (1.9.391)', run: () => { const m = require('../lib/feature'); const p = require('../lib/pure-utils'); const expOk = ['featureAddCmd', 'featureLinkCmd', 'featureImpactCmd', 'featureListCmd', 'featureShowCmd'].every(k => typeof m[k] === 'function'); const bfsRefOk = p._featureImpactBfs === _featureImpactBfs; const nodes = [{ id: 'F-0001', title: 'A', affects: ['F-0002'], dependsOn: [], coChangesWith: [] }, { id: 'F-0002', title: 'B', affects: [], dependsOn: [], coChangesWith: [] }]; const r = p._featureImpactBfs(nodes, 'F-0001'); const bfsWork = r.length === 1 && r[0].id === 'F-0002' && r[0].via === 'affects'; const src = read(__filename); const delegated = src.includes("require('../lib/feature')") && src.includes('_feature.featureImpactCmd(root, fromId, _featureDeps())'); const featSrc = read(path.join(path.dirname(__filename), '..', 'lib', 'feature.js')); const movedToLib = featSrc.includes("require('./pure-utils')") && featSrc.includes('feature added:'); let behavOk = false; const tmp = fs.mkdtempSync(path.join(os.tmpdir(), '__leerness_ft_')); const save = process.argv; const _w = process.stdout.write; let out = ''; try { fs.mkdirSync(path.join(tmp, '.harness'), { recursive: true }); process.argv = ['node', 'h', 'feature', 'list', '--json']; process.stdout.write = s => { out += s; return true; }; featureListCmd(tmp); } catch {} finally { process.stdout.write = _w; process.argv = save; try { fs.rmSync(tmp, { recursive: true, force: true }); } catch {} } try { const j = JSON.parse(out); behavOk = j.total === 0 && Array.isArray(j.features); } catch {} return expOk && bfsRefOk && bfsWork && delegated && movedToLib && behavOk; } },
2998
+ { name: 'UR-0025 큰핸들러 모듈화: doctor/which → lib/diagnostics.js + DI 위임 + 동작 (1.9.392)', run: () => { const m = require('../lib/diagnostics'); const expOk = typeof m.doctorCmd === 'function' && typeof m.whichCmd === 'function'; const src = read(__filename); const delegated = src.includes("require('../lib/diagnostics')") && src.includes('_diag.doctorCmd(opts,') && src.includes('_diag.whichCmd('); const diagSrc = read(path.join(path.dirname(__filename), '..', 'lib', 'diagnostics.js')); const movedToLib = diagSrc.includes('leerness doctor') && diagSrc.includes('_selfTestCases'); let behavOk = false; const _w = process.stdout.write; const savedExit = process.exitCode; try { process.stdout.write = () => true; const rep = m.doctorCmd({ json: true }, { VERSION, _selfTestCases: () => [], _detectShellCtx: () => ({ shell: 'test', psVersion: null }), _mcpToolCount: () => 7, has: () => true, harnessPath: 'h.js' }); behavOk = !!rep && rep.version === VERSION && rep.selftest.total === 0 && rep.healthy === true && rep.mcpTools === 7; } catch {} finally { process.stdout.write = _w; process.exitCode = savedExit; } return expOk && delegated && movedToLib && behavOk; } },
2997
2999
  { name: 'VERSION 형식 (x.y.z)', run: () => /^\d+\.\d+\.\d+$/.test(VERSION) }
2998
3000
  ];
2999
3001
  }
@@ -14524,134 +14526,15 @@ function _writeFeatureGraph(root, nodes) {
14524
14526
  const body = nodes.map(_featureBlock).join('');
14525
14527
  writeUtf8(p, header + body);
14526
14528
  }
14527
- function featureAddCmd(root, title) {
14528
- root = absRoot(root);
14529
- if (!title) return fail('feature add: title 필요 — leerness feature add "<title>"');
14530
- _ensureFeatureGraph(root);
14531
- const { nodes } = _readFeatureGraph(root);
14532
- if (nodes.some(n => n.title.toLowerCase() === title.toLowerCase())) {
14533
- return warn(`이미 존재: "${title}"`);
14534
- }
14535
- const id = _nextFeatureId(nodes);
14536
- const node = {
14537
- id, title,
14538
- dependsOn: [], affects: [], coChangesWith: [],
14539
- files: [], input: '', output: '', errorModes: [], tests: [], notes: ''
14540
- };
14541
- // 옵션 인자 — 한 번에 의존/영향 등록 가능
14542
- const depends = arg('--depends-on', '');
14543
- const affects = arg('--affects', '');
14544
- const coChanges = arg('--co-changes-with', '');
14545
- const files = arg('--files', '');
14546
- if (depends) node.dependsOn = depends.split(/[,\s]+/).filter(Boolean);
14547
- if (affects) node.affects = affects.split(/[,\s]+/).filter(Boolean);
14548
- if (coChanges) node.coChangesWith = coChanges.split(/[,\s]+/).filter(Boolean);
14549
- if (files) node.files = files.split(/[,\s]+/).filter(Boolean);
14550
- nodes.push(node);
14551
- _writeFeatureGraph(root, nodes);
14552
- ok(`feature added: ${id} · ${title}`);
14553
- }
14554
- function featureLinkCmd(root, fromId) {
14555
- root = absRoot(root);
14556
- if (!fromId || !/^F-\d{4}$/.test(fromId)) return fail('feature link: 첫 인자는 F-XXXX 형식 ID');
14557
- const { nodes } = _readFeatureGraph(root);
14558
- const node = nodes.find(n => n.id === fromId);
14559
- if (!node) return fail(`feature ${fromId} 없음 — feature add 먼저`);
14560
- const dep = arg('--depends-on', '');
14561
- const aff = arg('--affects', '');
14562
- const co = arg('--co-changes-with', '');
14563
- let changes = 0;
14564
- if (dep) { const ids = dep.split(/[,\s]+/).filter(Boolean); for (const id of ids) if (!node.dependsOn.includes(id)) { node.dependsOn.push(id); changes++; } }
14565
- if (aff) { const ids = aff.split(/[,\s]+/).filter(Boolean); for (const id of ids) if (!node.affects.includes(id)) { node.affects.push(id); changes++; } }
14566
- if (co) { const ids = co.split(/[,\s]+/).filter(Boolean); for (const id of ids) if (!node.coChangesWith.includes(id)) { node.coChangesWith.push(id); changes++; } }
14567
- if (!changes) return warn('변경 없음 — --depends-on / --affects / --co-changes-with 중 하나 이상 지정');
14568
- _writeFeatureGraph(root, nodes);
14569
- ok(`feature ${fromId} 링크 ${changes}건 추가`);
14570
- }
14571
- function _featureImpactBfs(nodes, startId) {
14572
- // affects + co-changes-with 양방향 transitive closure
14573
- const byId = new Map(nodes.map(n => [n.id, n]));
14574
- const visited = new Set();
14575
- const queue = [{ id: startId, depth: 0, via: 'self' }];
14576
- const result = [];
14577
- while (queue.length) {
14578
- const cur = queue.shift();
14579
- if (visited.has(cur.id)) continue;
14580
- visited.add(cur.id);
14581
- const node = byId.get(cur.id);
14582
- if (!node) continue;
14583
- if (cur.depth > 0) result.push({ id: cur.id, title: node.title, depth: cur.depth, via: cur.via, files: node.files, errorModes: node.errorModes });
14584
- for (const next of node.affects || []) queue.push({ id: next, depth: cur.depth + 1, via: 'affects' });
14585
- for (const next of node.coChangesWith || []) queue.push({ id: next, depth: cur.depth + 1, via: 'co-changes-with' });
14586
- }
14587
- // 역방향: 이 feature에 depends-on 하는 노드도 영향받음
14588
- for (const n of nodes) {
14589
- if (visited.has(n.id)) continue;
14590
- if ((n.dependsOn || []).includes(startId)) {
14591
- result.push({ id: n.id, title: n.title, depth: 1, via: 'depends-on(reverse)', files: n.files, errorModes: n.errorModes });
14592
- visited.add(n.id);
14593
- }
14594
- }
14595
- return result;
14596
- }
14597
- function featureImpactCmd(root, fromId) {
14598
- root = absRoot(root);
14599
- if (!fromId || !/^F-\d{4}$/.test(fromId)) return fail('feature impact: F-XXXX ID 필요');
14600
- const { nodes } = _readFeatureGraph(root);
14601
- const node = nodes.find(n => n.id === fromId);
14602
- if (!node) return fail(`feature ${fromId} 없음`);
14603
- const impacted = _featureImpactBfs(nodes, fromId);
14604
- if (has('--json')) {
14605
- log(JSON.stringify({ feature: { id: node.id, title: node.title }, total: impacted.length, impacted }, null, 2));
14606
- return;
14607
- }
14608
- log(`# Feature Impact: ${node.id} · ${node.title}`);
14609
- if (!impacted.length) { ok('영향받는 다른 feature 없음 (또는 link 미설정)'); return; }
14610
- log(`\n총 ${impacted.length} feature에 영향:\n`);
14611
- for (const it of impacted) {
14612
- log(` ${it.id} · ${it.title} [depth=${it.depth}, via=${it.via}]`);
14613
- if (it.files && it.files.length) log(` files: ${it.files.join(', ')}`);
14614
- if (it.errorModes && it.errorModes.length) log(` error-modes: ${it.errorModes.join(', ')}`);
14615
- }
14616
- log(`\n💡 코드 변경 전 위 ${impacted.length}개 feature의 테스트/계약 확인 권장`);
14617
- }
14618
- function featureListCmd(root) {
14619
- root = absRoot(root);
14620
- const { nodes } = _readFeatureGraph(root);
14621
- if (has('--json')) {
14622
- log(JSON.stringify({ total: nodes.length, features: nodes }, null, 2));
14623
- return;
14624
- }
14625
- log(`# Features (${nodes.length}개)`);
14626
- if (!nodes.length) {
14627
- log(' (없음) — leerness feature add "<title>"');
14628
- return;
14629
- }
14630
- for (const n of nodes) {
14631
- log(` ${n.id} · ${n.title}`);
14632
- if (n.dependsOn.length) log(` ↓ depends-on: ${n.dependsOn.join(', ')}`);
14633
- if (n.affects.length) log(` → affects: ${n.affects.join(', ')}`);
14634
- if (n.coChangesWith.length) log(` ↔ co-changes-with: ${n.coChangesWith.join(', ')}`);
14635
- }
14636
- }
14637
- function featureShowCmd(root, fromId) {
14638
- root = absRoot(root);
14639
- if (!fromId || !/^F-\d{4}$/.test(fromId)) return fail('feature show: F-XXXX ID 필요');
14640
- const { nodes } = _readFeatureGraph(root);
14641
- const node = nodes.find(n => n.id === fromId);
14642
- if (!node) return fail(`feature ${fromId} 없음`);
14643
- if (has('--json')) { log(JSON.stringify(node, null, 2)); return; }
14644
- log(`# ${node.id} · ${node.title}`);
14645
- log(` depends-on: ${node.dependsOn.join(', ') || '(없음)'}`);
14646
- log(` affects: ${node.affects.join(', ') || '(없음)'}`);
14647
- log(` co-changes-with: ${node.coChangesWith.join(', ') || '(없음)'}`);
14648
- log(` files: ${node.files.join(', ') || '(없음)'}`);
14649
- log(` input: ${node.input || '(없음)'}`);
14650
- log(` output: ${node.output || '(없음)'}`);
14651
- log(` error-modes: ${node.errorModes.join(', ') || '(없음)'}`);
14652
- log(` tests: ${node.tests.join(', ') || '(없음)'}`);
14653
- log(` notes: ${node.notes || '(없음)'}`);
14654
- }
14529
+ // 1.9.391 (UR-0025 큰 핸들러 모듈화 3번째): feature add/link/impact/list/show 핸들러를 lib/feature.js 로 분리.
14530
+ // _featureImpactBfs pure-utils 로 이동(handoff/audit 공유). feature-graph I/O 헬퍼(_readFeatureGraph 등)는 공유라 harness 유지+주입.
14531
+ const _feature = require('../lib/feature');
14532
+ function _featureDeps() { return { _ensureFeatureGraph, _readFeatureGraph, _writeFeatureGraph, arg, has }; }
14533
+ function featureAddCmd(root, title) { return _feature.featureAddCmd(root, title, _featureDeps()); }
14534
+ function featureLinkCmd(root, fromId) { return _feature.featureLinkCmd(root, fromId, _featureDeps()); }
14535
+ function featureImpactCmd(root, fromId) { return _feature.featureImpactCmd(root, fromId, _featureDeps()); }
14536
+ function featureListCmd(root) { return _feature.featureListCmd(root, _featureDeps()); }
14537
+ function featureShowCmd(root, fromId) { return _feature.featureShowCmd(root, fromId, _featureDeps()); }
14655
14538
 
14656
14539
  // ===== 1.9.3: Causal / reuse / consistency =====
14657
14540
  const CODE_EXT = new Set(['.js','.ts','.jsx','.tsx','.mjs','.cjs','.css','.scss','.sass','.less','.html','.htm','.vue','.svelte','.md','.json','.py','.rb','.go','.rs','.java','.kt','.swift','.cs','.php']);
@@ -20758,121 +20641,11 @@ function reviewRequestCmd(root, request) {
20758
20641
  // 사용자가 "최신 버전 작동 안 함" 의심 시: 실제 실행 중인 leerness 의 경로 / 버전 / npm 캐시 / PATH 후보 표시.
20759
20642
  // 1.9.315 (UR-0054, 설치리뷰): leerness doctor — 설치/환경 1콜 진단 (selftest 코어 무결성 + 버전/경로 + 셸/PowerShell).
20760
20643
  // 배경: 리뷰에서 doctor 명령 부재 지적("doctor no-op"). health(프로젝트 상태)와 달리 doctor 는 "도구 자체"의 정상성 진단.
20761
- function doctorCmd(opts = {}) {
20762
- const json = opts.json || has('--json');
20763
- // 1) 코어 무결성: selftest 케이스 인라인 실행
20764
- let pass = 0; const failNames = [];
20765
- try {
20766
- for (const c of _selfTestCases()) {
20767
- let okc = false;
20768
- try { okc = !!c.run(); } catch { okc = false; }
20769
- if (okc) pass++; else failNames.push(c.name);
20770
- }
20771
- } catch {}
20772
- const total = pass + failNames.length;
20773
- // 2) 셸/PowerShell 컨텍스트 (UR-0052)
20774
- let shell = null, psVersion = null;
20775
- try { const ctx = _detectShellCtx(); shell = ctx.shell; psVersion = ctx.psVersion; } catch {}
20776
- const mcpCount = (() => { try { return _mcpToolCount(); } catch { return null; } })();
20777
- const report = {
20778
- version: VERSION, node: process.version, platform: process.platform + '/' + process.arch,
20779
- runningFrom: __filename, mcpTools: mcpCount,
20780
- selftest: { pass, total, ok: failNames.length === 0, failed: failNames },
20781
- shell, psVersion, healthy: failNames.length === 0
20782
- };
20783
- if (json) { process.stdout.write(JSON.stringify(report, null, 2) + '\n'); if (!report.healthy) process.exitCode = 1; return report; }
20784
- const isTty = process.stdout && process.stdout.isTTY;
20785
- const gr = s => isTty ? `\x1b[32m${s}\x1b[0m` : s, rd = s => isTty ? `\x1b[31m${s}\x1b[0m` : s, cy = s => isTty ? `\x1b[36m${s}\x1b[0m` : s, dm = s => isTty ? `\x1b[2m${s}\x1b[0m` : s;
20786
- log(cy(`# leerness doctor — 설치/환경 진단`));
20787
- log('');
20788
- log(` ${gr('✓')} version ${VERSION} · node ${process.version} · ${process.platform}/${process.arch}`);
20789
- log(` ${gr('✓')} 설치 경로: ${dm(__filename)}`);
20790
- log(` ${gr('✓')} MCP 도구: ${mcpCount}`);
20791
- log(` ${report.selftest.ok ? gr('✓') : rd('✗')} selftest: ${pass}/${total} ${report.selftest.ok ? '통과' : '실패'}`);
20792
- if (!report.selftest.ok) report.selftest.failed.slice(0, 5).forEach(n => log(rd(` ✗ ${n}`)));
20793
- log(` ${gr('✓')} 셸: ${shell || 'unknown'}${psVersion && shell === 'powershell' ? ` (PowerShell ${psVersion})` : ''}`);
20794
- log('');
20795
- log(report.healthy ? gr(' ✓ leerness 설치 정상') : rd(' ✗ 문제 감지 — 재설치: npm i -g leerness@latest · 진단: leerness which'));
20796
- if (!report.healthy) process.exitCode = 1;
20797
- return report;
20798
- }
20799
- function whichCmd() {
20800
- const out = {
20801
- version: VERSION,
20802
- runningFrom: __filename,
20803
- nodeVersion: process.version,
20804
- platform: process.platform,
20805
- arch: process.arch,
20806
- npm: {},
20807
- pathCandidates: []
20808
- };
20809
- // npm root -g (글로벌 설치 경로)
20810
- try {
20811
- const r = cp.spawnSync('npm', ['root', '-g'], { encoding: 'utf8', timeout: 5000, shell: true });
20812
- if (r.status === 0) out.npm.globalRoot = (r.stdout || '').trim();
20813
- } catch {}
20814
- // npm cache (npx 캐시 경로)
20815
- try {
20816
- const r = cp.spawnSync('npm', ['config', 'get', 'cache'], { encoding: 'utf8', timeout: 5000, shell: true });
20817
- if (r.status === 0) out.npm.cacheDir = (r.stdout || '').trim();
20818
- } catch {}
20819
- // npm 글로벌 leerness 설치 정보
20820
- try {
20821
- const r = cp.spawnSync('npm', ['ls', '-g', 'leerness', '--depth=0', '--json'], { encoding: 'utf8', timeout: 8000, shell: true });
20822
- if (r.stdout) {
20823
- try {
20824
- const j = JSON.parse(r.stdout);
20825
- if (j.dependencies?.leerness) out.npm.globalInstalled = j.dependencies.leerness.version;
20826
- } catch {}
20827
- }
20828
- } catch {}
20829
- // PATH 후보 (Windows: where / Unix: which)
20830
- try {
20831
- const isWin = process.platform === 'win32';
20832
- const tool = isWin ? 'where' : 'which';
20833
- const r = cp.spawnSync(tool, ['-a', 'leerness'], { encoding: 'utf8', timeout: 5000, shell: true });
20834
- if (r.stdout) out.pathCandidates = (r.stdout || '').trim().split(/\r?\n/).filter(Boolean);
20835
- } catch {}
20836
- // 진단: 글로벌 설치된 leerness 와 현재 실행 버전이 다르면 경고
20837
- out.diagnostics = [];
20838
- if (out.npm.globalInstalled && out.npm.globalInstalled !== VERSION) {
20839
- out.diagnostics.push(`⚠ 글로벌 설치 ${out.npm.globalInstalled} ≠ 현재 실행 ${VERSION} — npx 캐시 또는 PATH 충돌 의심`);
20840
- out.diagnostics.push(` → 강제 최신: npm i -g leerness@latest / 또는 npx --yes leerness@latest <command>`);
20841
- }
20842
- if (out.pathCandidates.length > 1) {
20843
- out.diagnostics.push(`⚠ PATH 에 leerness 가 ${out.pathCandidates.length}개 — 우선순위 충돌 가능`);
20844
- out.diagnostics.push(` → 명시적 경로 사용: ${out.runningFrom}`);
20845
- }
20846
- if (has('--json')) { log(JSON.stringify(out, null, 2)); return; }
20847
- log(`# leerness which (1.9.164)`);
20848
- log(`현재 실행: ${out.runningFrom}`);
20849
- log(`버전: v${out.version}`);
20850
- log(`Node: ${out.nodeVersion} (${out.platform}/${out.arch})`);
20851
- log('');
20852
- log(`## npm 환경`);
20853
- if (out.npm.globalRoot) log(` npm root -g: ${out.npm.globalRoot}`);
20854
- if (out.npm.cacheDir) log(` npm cache: ${out.npm.cacheDir} (npx 옛 버전이 여기 캐싱 — 의심 시 \`npm cache clean --force\`)`);
20855
- if (out.npm.globalInstalled) log(` 글로벌 설치: leerness@${out.npm.globalInstalled}`);
20856
- else log(` 글로벌 설치: (없음 — npx 또는 로컬 경로만 사용 중)`);
20857
- if (out.pathCandidates.length) {
20858
- log('');
20859
- log(`## PATH 후보 (${out.pathCandidates.length}개)`);
20860
- for (const p of out.pathCandidates) log(` - ${p}`);
20861
- }
20862
- if (out.diagnostics.length) {
20863
- log('');
20864
- log(`## ⚠ 진단`);
20865
- for (const d of out.diagnostics) log(` ${d}`);
20866
- } else {
20867
- log('');
20868
- log(`✓ 충돌 없음 (현재 실행 버전 = 글로벌 설치 버전)`);
20869
- }
20870
- log('');
20871
- log(`💡 강제 최신 실행 방법:`);
20872
- log(` 1) npx --yes leerness@latest <command> # npx 캐시 무시하고 최신 다운로드`);
20873
- log(` 2) npm i -g leerness@latest # 글로벌 설치 갱신`);
20874
- log(` 3) npm cache clean --force # npx 캐시 강제 비우기 (의심 시)`);
20875
- }
20644
+ // 1.9.392 (UR-0025 핸들러 모듈화 4번째): doctor/which 진단 핸들러를 lib/diagnostics.js 로 분리.
20645
+ // harness deps(VERSION · _selfTestCases · _detectShellCtx · _mcpToolCount · has · harnessPath)를 구성해 위임(thin wrapper). 호출부/동작 무변경.
20646
+ const _diag = require('../lib/diagnostics');
20647
+ function doctorCmd(opts = {}) { return _diag.doctorCmd(opts, { VERSION, _selfTestCases, _detectShellCtx, _mcpToolCount, has, harnessPath: __filename }); }
20648
+ function whichCmd() { return _diag.whichCmd({ VERSION, has, harnessPath: __filename }); }
20876
20649
 
20877
20650
  function help() {
20878
20651
  log(`Leerness v${VERSION}\n\nUsage:\n leerness init [path] [--language auto|ko|en] [--skills recommended|all|a,b]\n leerness migrate [path] [--dry-run] [--force]\n leerness update [path] [--check|--yes|--force|--from <tarball>]\n leerness auto-update install [path]\n leerness status [path]\n leerness verify [path]\n leerness debug [path]\n leerness audit [path]\n leerness check [path]\n leerness scan secrets [path]\n leerness encoding check [path]\n leerness lazy detect [path]\n leerness memory search "query" [--limit 5]\n leerness handoff [path] [--all-apps] [--include p1,p2] [--since 24h|3d] [--compact] [--json] # 1.9.17-22 워크스페이스 (--compact: LLM 시스템 프롬프트용 1줄 요약)\n leerness orchestrate "<목표>" [--agents N] [--model qwen2.5:7b-instruct] [--retry-on-fail K] # 1.9.22 Ollama opt-in (LEERNESS_OLLAMA_BASE_URL 필요)\n leerness llm-bench record --score N --model X [--label L] [--tokens T] # 1.9.22 LLM 벤치 히스토리 누적\n leerness deps <capability> [--run-tests] [--json] # 1.9.24 depends-on 역방향 추적 + 자동 회귀 sweep\n leerness memory search "키" [--include-code] # 1.9.25 소스 코드 본문도 검색 (모순 감지 핵심)\n leerness brainstorm "주제" [--include-code] # 1.9.25 코드 본문 hits 포함\n leerness register-pending "<요청>" [--agent X] [--note Y] # 1.9.25 다중 세션 in-progress 즉시 등록\n leerness optimism-check <T-ID> [--json] # 1.9.26/27 낙관적 표시 감지 (1.9.27: 10 카테고리 + URL/메서드 매핑 + 신뢰도 점수)\n leerness persona list|show <id>|add <id> # 1.9.29 페르소나 카탈로그 (보안/성능/UX/testing/docs 5종 내장)\n leerness review <file> --persona <id1,id2,...> # 1.9.29 도메인 페르소나 리뷰 프롬프트 자동 생성\n leerness agents list|check|quota # 1.9.30/31 외부 AI CLI 가용성 + quota 추정 (claude/codex/agy/copilot)\n leerness agents dispatch "<task>" --to <id> # 1.9.30 활성 CLI 대상 실행 명령 생성 (실 호출 X, 사용자 실행)\n leerness agents multi "<task>" [--only c1,c2] [--write] [--execute] [--timeout 60] # 1.9.152/156 활성 N개 일괄 dispatch (--execute: 실 spawn + consensus)\n leerness provider list|add|remove [args] # 1.9.157 Provider Registry — 사용자 정의 CLI provider 동적 추가 (OpenRouter/Bedrock 흡수)\n leerness agents dispatch "<task>" --multi # 1.9.152 multi 모드 alias (또는 --to all)\n leerness setup-agents [path] [--yes|--no-setup-agents] # 1.9.32 sub-agent CLI 인터랙티브 설정 (.env + 미설치 자동 설치)\n leerness init [path] [--no-stale-check] # 1.9.33 npx 캐시 함정 — 옛 버전 자동 경고 (끄려면 --no-stale-check)\n leerness which [--json] # 1.9.164 진단: 현재 실행 경로/버전 + npm 캐시 + PATH 후보 (구버전 충돌 해결)\n leerness selftest [--json] # 1.9.258 코어 함수 무결성 자가 검증 (설치 손상/부분설치 감지, CI 친화 exit 1)\n leerness shell-guard "<command>" [--json] # 1.9.260 터미널 명령 셸 호환성 린터 (PowerShell 5.1 && 미지원 등 실행 전 감지, UR-0020)\n leerness shell-guard --record --cmd "..." --exit N # 1.9.260 실패한 터미널 명령 기록 → 다음 분석 시 회수\n leerness path-setup [--apply] [--json] # 1.9.254 leerness CLI PATH 자동 등록 (npm global bin 미등록 시)\n leerness web check|screenshot|extract <url> [--out file.png] [--selector "css"] # 1.9.165 playwright bridge (opt-in: npm i -g playwright + permissions.browser)\n leerness pc check|click|type|screenshot [--x N --y N] [--text "s"] [--out f.png] # 1.9.166 robotjs/nut-tree bridge (opt-in: npm i -g robotjs + permissions.mouse/keyboard, ⚠ full 모드 권장)\n leerness lsp check|symbols|references <file/name> [--in dir] [--json] # 1.9.167 LSP 어댑터 MVP (typescript opt-in + regex fallback, 코드 인텔리전스)\n leerness review-request "<request>" [--json] # 1.9.176 사용자 요청 사전 검토 (충돌/재사용/효율/권장 단계 — 사용자 명시)\n leerness contract verify <spec.md> <impl.js> [--json] # 1.9.35 명세 ↔ 구현 일치 검사 (함수/필드)\n leerness reuse autodetect [path] [--apply] [--json] # 1.9.35 src/*.js의 module.exports → reuse-map 후보 등록\n leerness audit [path] [--fix] # 1.9.35 --fix: session-handoff/current-state 자동 갱신\n leerness verify-claim <T-ID> ... [--strict-claims] # 1.9.26 verify-claim에 낙관적 표시 자동 검사 통합\n leerness reuse-map [path] [--all-apps] [--include p1,p2] [--strict-elements] [--json] # 1.9.18 중복/잠재중복/depends-on\n leerness verify-claim <T-ID> [--path .] [--run-tests] [--json] # 1.9.18-20 evidence 자동 검증 (1.9.20: scenes/scripts 등 도메인 폴더 + jest/mocha 파싱)\n leerness verify-code [path] [--build] [--bench] # 1.9.20 --bench: scripts.bench 추가 실행 + evidence 누적\n leerness session close [path]\n leerness route <task-type>\n leerness self check [path]\n leerness readme sync [path]\n leerness consistency check [path]\n leerness consistency merge-design-guide [path]\n leerness plan show|init|add|drop|progress|sync [args]\n leerness task list|add|update|drop|fix-evidence|relink [args]\n leerness skill list|info <name>\n leerness skill learn <id> --doc <url> --command "..." --capability "..." [--note ...]\n leerness skill use <id> [--note ...]\n leerness skill optimize <id> --before "..." --after "..." [--note ...]\n leerness skill remove <id>\n leerness skill consolidate [--threshold 0.3]\n leerness gate [path] # verify+audit+scan+encoding+lazy
@@ -0,0 +1,129 @@
1
+ // lib/diagnostics.js — 설치/환경 진단 핸들러 (doctor / which).
2
+ // 1.9.392 (UR-0025 큰 핸들러 모듈화 4번째): bin/harness.js 에서 doctor/which 분리.
3
+ // - I/O: ./io(log). node: child_process.
4
+ // - harness 고유 의존(VERSION · _selfTestCases · _detectShellCtx · _mcpToolCount · argv 파서 has · harnessPath)은 deps 주입(DI).
5
+ // _selfTestCases 의 각 case.run 클로저는 harness 스코프를 유지하므로 함수 참조 주입만으로 정상 동작.
6
+ 'use strict';
7
+ const cp = require('child_process');
8
+ const { log } = require('./io');
9
+
10
+ function doctorCmd(opts = {}, deps = {}) {
11
+ const { VERSION, _selfTestCases, _detectShellCtx, _mcpToolCount, has, harnessPath } = deps;
12
+ const json = opts.json || has('--json');
13
+ // 1) 코어 무결성: selftest 케이스 인라인 실행
14
+ let pass = 0; const failNames = [];
15
+ try {
16
+ for (const c of _selfTestCases()) {
17
+ let okc = false;
18
+ try { okc = !!c.run(); } catch { okc = false; }
19
+ if (okc) pass++; else failNames.push(c.name);
20
+ }
21
+ } catch {}
22
+ const total = pass + failNames.length;
23
+ // 2) 셸/PowerShell 컨텍스트 (UR-0052)
24
+ let shell = null, psVersion = null;
25
+ try { const ctx = _detectShellCtx(); shell = ctx.shell; psVersion = ctx.psVersion; } catch {}
26
+ const mcpCount = (() => { try { return _mcpToolCount(); } catch { return null; } })();
27
+ const report = {
28
+ version: VERSION, node: process.version, platform: process.platform + '/' + process.arch,
29
+ runningFrom: harnessPath, mcpTools: mcpCount,
30
+ selftest: { pass, total, ok: failNames.length === 0, failed: failNames },
31
+ shell, psVersion, healthy: failNames.length === 0
32
+ };
33
+ if (json) { process.stdout.write(JSON.stringify(report, null, 2) + '\n'); if (!report.healthy) process.exitCode = 1; return report; }
34
+ const isTty = process.stdout && process.stdout.isTTY;
35
+ const gr = s => isTty ? `\x1b[32m${s}\x1b[0m` : s, rd = s => isTty ? `\x1b[31m${s}\x1b[0m` : s, cy = s => isTty ? `\x1b[36m${s}\x1b[0m` : s, dm = s => isTty ? `\x1b[2m${s}\x1b[0m` : s;
36
+ log(cy(`# leerness doctor — 설치/환경 진단`));
37
+ log('');
38
+ log(` ${gr('✓')} version ${VERSION} · node ${process.version} · ${process.platform}/${process.arch}`);
39
+ log(` ${gr('✓')} 설치 경로: ${dm(harnessPath)}`);
40
+ log(` ${gr('✓')} MCP 도구: ${mcpCount}`);
41
+ log(` ${report.selftest.ok ? gr('✓') : rd('✗')} selftest: ${pass}/${total} ${report.selftest.ok ? '통과' : '실패'}`);
42
+ if (!report.selftest.ok) report.selftest.failed.slice(0, 5).forEach(n => log(rd(` ✗ ${n}`)));
43
+ log(` ${gr('✓')} 셸: ${shell || 'unknown'}${psVersion && shell === 'powershell' ? ` (PowerShell ${psVersion})` : ''}`);
44
+ log('');
45
+ log(report.healthy ? gr(' ✓ leerness 설치 정상') : rd(' ✗ 문제 감지 — 재설치: npm i -g leerness@latest · 진단: leerness which'));
46
+ if (!report.healthy) process.exitCode = 1;
47
+ return report;
48
+ }
49
+
50
+ function whichCmd(deps = {}) {
51
+ const { VERSION, has, harnessPath } = deps;
52
+ const out = {
53
+ version: VERSION,
54
+ runningFrom: harnessPath,
55
+ nodeVersion: process.version,
56
+ platform: process.platform,
57
+ arch: process.arch,
58
+ npm: {},
59
+ pathCandidates: []
60
+ };
61
+ // npm root -g (글로벌 설치 경로)
62
+ try {
63
+ const r = cp.spawnSync('npm', ['root', '-g'], { encoding: 'utf8', timeout: 5000, shell: true });
64
+ if (r.status === 0) out.npm.globalRoot = (r.stdout || '').trim();
65
+ } catch {}
66
+ // npm cache (npx 캐시 경로)
67
+ try {
68
+ const r = cp.spawnSync('npm', ['config', 'get', 'cache'], { encoding: 'utf8', timeout: 5000, shell: true });
69
+ if (r.status === 0) out.npm.cacheDir = (r.stdout || '').trim();
70
+ } catch {}
71
+ // npm 글로벌 leerness 설치 정보
72
+ try {
73
+ const r = cp.spawnSync('npm', ['ls', '-g', 'leerness', '--depth=0', '--json'], { encoding: 'utf8', timeout: 8000, shell: true });
74
+ if (r.stdout) {
75
+ try {
76
+ const j = JSON.parse(r.stdout);
77
+ if (j.dependencies?.leerness) out.npm.globalInstalled = j.dependencies.leerness.version;
78
+ } catch {}
79
+ }
80
+ } catch {}
81
+ // PATH 후보 (Windows: where / Unix: which)
82
+ try {
83
+ const isWin = process.platform === 'win32';
84
+ const tool = isWin ? 'where' : 'which';
85
+ const r = cp.spawnSync(tool, ['-a', 'leerness'], { encoding: 'utf8', timeout: 5000, shell: true });
86
+ if (r.stdout) out.pathCandidates = (r.stdout || '').trim().split(/\r?\n/).filter(Boolean);
87
+ } catch {}
88
+ // 진단: 글로벌 설치된 leerness 와 현재 실행 버전이 다르면 경고
89
+ out.diagnostics = [];
90
+ if (out.npm.globalInstalled && out.npm.globalInstalled !== VERSION) {
91
+ out.diagnostics.push(`⚠ 글로벌 설치 ${out.npm.globalInstalled} ≠ 현재 실행 ${VERSION} — npx 캐시 또는 PATH 충돌 의심`);
92
+ out.diagnostics.push(` → 강제 최신: npm i -g leerness@latest / 또는 npx --yes leerness@latest <command>`);
93
+ }
94
+ if (out.pathCandidates.length > 1) {
95
+ out.diagnostics.push(`⚠ PATH 에 leerness 가 ${out.pathCandidates.length}개 — 우선순위 충돌 가능`);
96
+ out.diagnostics.push(` → 명시적 경로 사용: ${out.runningFrom}`);
97
+ }
98
+ if (has('--json')) { log(JSON.stringify(out, null, 2)); return; }
99
+ log(`# leerness which (1.9.164)`);
100
+ log(`현재 실행: ${out.runningFrom}`);
101
+ log(`버전: v${out.version}`);
102
+ log(`Node: ${out.nodeVersion} (${out.platform}/${out.arch})`);
103
+ log('');
104
+ log(`## npm 환경`);
105
+ if (out.npm.globalRoot) log(` npm root -g: ${out.npm.globalRoot}`);
106
+ if (out.npm.cacheDir) log(` npm cache: ${out.npm.cacheDir} (npx 옛 버전이 여기 캐싱 — 의심 시 \`npm cache clean --force\`)`);
107
+ if (out.npm.globalInstalled) log(` 글로벌 설치: leerness@${out.npm.globalInstalled}`);
108
+ else log(` 글로벌 설치: (없음 — npx 또는 로컬 경로만 사용 중)`);
109
+ if (out.pathCandidates.length) {
110
+ log('');
111
+ log(`## PATH 후보 (${out.pathCandidates.length}개)`);
112
+ for (const p of out.pathCandidates) log(` - ${p}`);
113
+ }
114
+ if (out.diagnostics.length) {
115
+ log('');
116
+ log(`## ⚠ 진단`);
117
+ for (const d of out.diagnostics) log(` ${d}`);
118
+ } else {
119
+ log('');
120
+ log(`✓ 충돌 없음 (현재 실행 버전 = 글로벌 설치 버전)`);
121
+ }
122
+ log('');
123
+ log(`💡 강제 최신 실행 방법:`);
124
+ log(` 1) npx --yes leerness@latest <command> # npx 캐시 무시하고 최신 다운로드`);
125
+ log(` 2) npm i -g leerness@latest # 글로벌 설치 갱신`);
126
+ log(` 3) npm cache clean --force # npx 캐시 강제 비우기 (의심 시)`);
127
+ }
128
+
129
+ module.exports = { doctorCmd, whichCmd };
package/lib/feature.js ADDED
@@ -0,0 +1,118 @@
1
+ // lib/feature.js — feature-graph 핸들러 (add/link/impact/list/show).
2
+ // 1.9.391 (UR-0025 큰 핸들러 모듈화 3번째): bin/harness.js 에서 feature 핸들러 분리.
3
+ // - I/O 프리미티브: ./io. 순수 로직: ./pure-utils(_nextFeatureId/_featureImpactBfs).
4
+ // - feature-graph I/O 헬퍼(_readFeatureGraph/_writeFeatureGraph/_ensureFeatureGraph)는 audit/health/handoff 등도 쓰는
5
+ // 공유 함수라 harness 에 유지하고 deps 로 주입(DI). argv 파서 arg/has 도 주입.
6
+ 'use strict';
7
+ const { absRoot, log, ok, warn, fail } = require('./io');
8
+ const { _nextFeatureId, _featureImpactBfs } = require('./pure-utils');
9
+
10
+ function featureAddCmd(root, title, deps = {}) {
11
+ const { _ensureFeatureGraph, _readFeatureGraph, _writeFeatureGraph, arg } = deps;
12
+ root = absRoot(root);
13
+ if (!title) return fail('feature add: title 필요 — leerness feature add "<title>"');
14
+ _ensureFeatureGraph(root);
15
+ const { nodes } = _readFeatureGraph(root);
16
+ if (nodes.some(n => n.title.toLowerCase() === title.toLowerCase())) {
17
+ return warn(`이미 존재: "${title}"`);
18
+ }
19
+ const id = _nextFeatureId(nodes);
20
+ const node = {
21
+ id, title,
22
+ dependsOn: [], affects: [], coChangesWith: [],
23
+ files: [], input: '', output: '', errorModes: [], tests: [], notes: ''
24
+ };
25
+ // 옵션 인자 — 한 번에 의존/영향 등록 가능
26
+ const depends = arg('--depends-on', '');
27
+ const affects = arg('--affects', '');
28
+ const coChanges = arg('--co-changes-with', '');
29
+ const files = arg('--files', '');
30
+ if (depends) node.dependsOn = depends.split(/[,\s]+/).filter(Boolean);
31
+ if (affects) node.affects = affects.split(/[,\s]+/).filter(Boolean);
32
+ if (coChanges) node.coChangesWith = coChanges.split(/[,\s]+/).filter(Boolean);
33
+ if (files) node.files = files.split(/[,\s]+/).filter(Boolean);
34
+ nodes.push(node);
35
+ _writeFeatureGraph(root, nodes);
36
+ ok(`feature added: ${id} · ${title}`);
37
+ }
38
+ function featureLinkCmd(root, fromId, deps = {}) {
39
+ const { _readFeatureGraph, _writeFeatureGraph, arg } = deps;
40
+ root = absRoot(root);
41
+ if (!fromId || !/^F-\d{4}$/.test(fromId)) return fail('feature link: 첫 인자는 F-XXXX 형식 ID');
42
+ const { nodes } = _readFeatureGraph(root);
43
+ const node = nodes.find(n => n.id === fromId);
44
+ if (!node) return fail(`feature ${fromId} 없음 — feature add 먼저`);
45
+ const dep = arg('--depends-on', '');
46
+ const aff = arg('--affects', '');
47
+ const co = arg('--co-changes-with', '');
48
+ let changes = 0;
49
+ if (dep) { const ids = dep.split(/[,\s]+/).filter(Boolean); for (const id of ids) if (!node.dependsOn.includes(id)) { node.dependsOn.push(id); changes++; } }
50
+ if (aff) { const ids = aff.split(/[,\s]+/).filter(Boolean); for (const id of ids) if (!node.affects.includes(id)) { node.affects.push(id); changes++; } }
51
+ if (co) { const ids = co.split(/[,\s]+/).filter(Boolean); for (const id of ids) if (!node.coChangesWith.includes(id)) { node.coChangesWith.push(id); changes++; } }
52
+ if (!changes) return warn('변경 없음 — --depends-on / --affects / --co-changes-with 중 하나 이상 지정');
53
+ _writeFeatureGraph(root, nodes);
54
+ ok(`feature ${fromId} 링크 ${changes}건 추가`);
55
+ }
56
+ function featureImpactCmd(root, fromId, deps = {}) {
57
+ const { _readFeatureGraph, has } = deps;
58
+ root = absRoot(root);
59
+ if (!fromId || !/^F-\d{4}$/.test(fromId)) return fail('feature impact: F-XXXX ID 필요');
60
+ const { nodes } = _readFeatureGraph(root);
61
+ const node = nodes.find(n => n.id === fromId);
62
+ if (!node) return fail(`feature ${fromId} 없음`);
63
+ const impacted = _featureImpactBfs(nodes, fromId);
64
+ if (has('--json')) {
65
+ log(JSON.stringify({ feature: { id: node.id, title: node.title }, total: impacted.length, impacted }, null, 2));
66
+ return;
67
+ }
68
+ log(`# Feature Impact: ${node.id} · ${node.title}`);
69
+ if (!impacted.length) { ok('영향받는 다른 feature 없음 (또는 link 미설정)'); return; }
70
+ log(`\n총 ${impacted.length} feature에 영향:\n`);
71
+ for (const it of impacted) {
72
+ log(` ${it.id} · ${it.title} [depth=${it.depth}, via=${it.via}]`);
73
+ if (it.files && it.files.length) log(` files: ${it.files.join(', ')}`);
74
+ if (it.errorModes && it.errorModes.length) log(` error-modes: ${it.errorModes.join(', ')}`);
75
+ }
76
+ log(`\n💡 코드 변경 전 위 ${impacted.length}개 feature의 테스트/계약 확인 권장`);
77
+ }
78
+ function featureListCmd(root, deps = {}) {
79
+ const { _readFeatureGraph, has } = deps;
80
+ root = absRoot(root);
81
+ const { nodes } = _readFeatureGraph(root);
82
+ if (has('--json')) {
83
+ log(JSON.stringify({ total: nodes.length, features: nodes }, null, 2));
84
+ return;
85
+ }
86
+ log(`# Features (${nodes.length}개)`);
87
+ if (!nodes.length) {
88
+ log(' (없음) — leerness feature add "<title>"');
89
+ return;
90
+ }
91
+ for (const n of nodes) {
92
+ log(` ${n.id} · ${n.title}`);
93
+ if (n.dependsOn.length) log(` ↓ depends-on: ${n.dependsOn.join(', ')}`);
94
+ if (n.affects.length) log(` → affects: ${n.affects.join(', ')}`);
95
+ if (n.coChangesWith.length) log(` ↔ co-changes-with: ${n.coChangesWith.join(', ')}`);
96
+ }
97
+ }
98
+ function featureShowCmd(root, fromId, deps = {}) {
99
+ const { _readFeatureGraph, has } = deps;
100
+ root = absRoot(root);
101
+ if (!fromId || !/^F-\d{4}$/.test(fromId)) return fail('feature show: F-XXXX ID 필요');
102
+ const { nodes } = _readFeatureGraph(root);
103
+ const node = nodes.find(n => n.id === fromId);
104
+ if (!node) return fail(`feature ${fromId} 없음`);
105
+ if (has('--json')) { log(JSON.stringify(node, null, 2)); return; }
106
+ log(`# ${node.id} · ${node.title}`);
107
+ log(` depends-on: ${node.dependsOn.join(', ') || '(없음)'}`);
108
+ log(` affects: ${node.affects.join(', ') || '(없음)'}`);
109
+ log(` co-changes-with: ${node.coChangesWith.join(', ') || '(없음)'}`);
110
+ log(` files: ${node.files.join(', ') || '(없음)'}`);
111
+ log(` input: ${node.input || '(없음)'}`);
112
+ log(` output: ${node.output || '(없음)'}`);
113
+ log(` error-modes: ${node.errorModes.join(', ') || '(없음)'}`);
114
+ log(` tests: ${node.tests.join(', ') || '(없음)'}`);
115
+ log(` notes: ${node.notes || '(없음)'}`);
116
+ }
117
+
118
+ module.exports = { featureAddCmd, featureLinkCmd, featureImpactCmd, featureListCmd, featureShowCmd };
package/lib/pure-utils.js CHANGED
@@ -931,7 +931,9 @@ module.exports = {
931
931
  // 1.9.386 (UR-0087, 5th외부평가): 간이 .gitignore 매칭 + glob (bare .env → .env.* 과잉보호 제거)
932
932
  _gitignoreMatch, _globToRe,
933
933
  // 1.9.390 (UR-0025): feature-graph 순수 코어 (템플릿/파서/ID/블록)
934
- _featureGraphTemplate, _parseFeatureGraph, _nextFeatureId, _featureBlock
934
+ _featureGraphTemplate, _parseFeatureGraph, _nextFeatureId, _featureBlock,
935
+ // 1.9.391 (UR-0025): feature 영향 BFS (순수, 공유)
936
+ _featureImpactBfs
935
937
  };
936
938
 
937
939
  // 1.9.355 (UR-0075 Phase A): AI 에이전트용 크로스버전 마이그레이션 안전 워크플로 가이드 (순수 텍스트). 임시설치 + --path + 백업 + diff 검증.
@@ -1092,3 +1094,29 @@ function _featureBlock(node) {
1092
1094
  `- tests: ${(node.tests || []).join(', ')}\n` +
1093
1095
  `- notes: ${node.notes || ''}\n\n`;
1094
1096
  }
1097
+ // 1.9.391 (UR-0025): feature 영향 BFS — affects + co-changes-with transitive + depends-on 역방향. 순수(nodes,startId→result). harness(handoff/audit)+lib/feature 공유.
1098
+ function _featureImpactBfs(nodes, startId) {
1099
+ const byId = new Map(nodes.map(n => [n.id, n]));
1100
+ const visited = new Set();
1101
+ const queue = [{ id: startId, depth: 0, via: 'self' }];
1102
+ const result = [];
1103
+ while (queue.length) {
1104
+ const cur = queue.shift();
1105
+ if (visited.has(cur.id)) continue;
1106
+ visited.add(cur.id);
1107
+ const node = byId.get(cur.id);
1108
+ if (!node) continue;
1109
+ if (cur.depth > 0) result.push({ id: cur.id, title: node.title, depth: cur.depth, via: cur.via, files: node.files, errorModes: node.errorModes });
1110
+ for (const next of node.affects || []) queue.push({ id: next, depth: cur.depth + 1, via: 'affects' });
1111
+ for (const next of node.coChangesWith || []) queue.push({ id: next, depth: cur.depth + 1, via: 'co-changes-with' });
1112
+ }
1113
+ // 역방향: 이 feature에 depends-on 하는 노드도 영향받음
1114
+ for (const n of nodes) {
1115
+ if (visited.has(n.id)) continue;
1116
+ if ((n.dependsOn || []).includes(startId)) {
1117
+ result.push({ id: n.id, title: n.title, depth: 1, via: 'depends-on(reverse)', files: n.files, errorModes: n.errorModes });
1118
+ visited.add(n.id);
1119
+ }
1120
+ }
1121
+ return result;
1122
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "leerness",
3
- "version": "1.9.390",
3
+ "version": "1.9.392",
4
4
  "description": "Leerness: 비파괴 마이그레이션, 자동 버전 감지·업데이트, 계획/진행/핸드오프 자동화, 게으름·시크릿·인코딩 자동 가드, Claude Code 슬래시 통합을 갖춘 한국어 우선 AI 개발 하네스.",
5
5
  "keywords": [
6
6
  "leerness",