leerness 1.9.421 → 1.9.422
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 +19 -0
- package/README.md +5 -5
- package/bin/leerness.js +25 -323
- package/lib/drift.js +334 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.9.422 — 2026-06-07 — 무거움 점진 해소 3: driftCheckCmd → lib/drift.js 모듈화 (UR-0025/UR-0125)
|
|
4
|
+
|
|
5
|
+
**🪶 `bin/leerness.js` 무거움 점진 해소 3단계 — `drift check` 핸들러(322줄, 내부 재귀 포함)를 lib/ 로 DI 분리.**
|
|
6
|
+
|
|
7
|
+
### 배경
|
|
8
|
+
세 번째 큰 핸들러 추출. driftCheckCmd는 **내부 재귀**(auto-fix 후 재검사) + **self-spawn**(audit --fix/session close) + 의존 16종으로 가장 복잡 → **테스트주도 추출**로 누락 deps를 단계적 포착(harnessPath→fs→taskLogPath/envDiff).
|
|
9
|
+
|
|
10
|
+
### 변경
|
|
11
|
+
- `lib/drift.js` 신설(334줄): `driftCheckCmd(root, opts, deps)` — io는 `./io`, fs/cp/path 빌트인, harness 고유 의존 16종 DI 주입. **내부 재귀 호출에 deps 전달**(`driftCheckCmd(root, opts, deps)`), `__filename`→`harnessPath`(self-spawn) 변환.
|
|
12
|
+
- `bin/leerness.js`: 322줄 → **3줄 thin wrapper**. **20,617 → 20,318줄(−299)**.
|
|
13
|
+
- 동작/출력 무변경(drift 4신호/4레벨 + --auto-fix 재귀 + handoff/health spawn 경로 동일).
|
|
14
|
+
|
|
15
|
+
### 검증 (회귀 0)
|
|
16
|
+
- **selftest 167→168 PASS** (모듈 + DI 위임 + 재귀 deps 전달 + level/score/fired 동작).
|
|
17
|
+
- **E2E 421→422 PASS** (drift check/--auto-fix + handoff·health의 drift spawn 경로).
|
|
18
|
+
|
|
19
|
+
### 누적 효과 (UR-0125)
|
|
20
|
+
3회 추출로 bin **21,177 → 20,318줄(−859, 4.1%)**. lib/ 모듈 14개. 다음 후보: healthCmd(~24) → handoff(1434).
|
|
21
|
+
|
|
3
22
|
## 1.9.421 — 2026-06-07 — 무거움 점진 해소 2: audit → lib/audit.js 모듈화 (UR-0025/UR-0125)
|
|
4
23
|
|
|
5
24
|
**🪶 `bin/leerness.js` 무거움 점진 해소 2단계 — `audit` 핸들러(310줄)를 lib/ 로 DI 분리.**
|
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
|
-
[](https://www.npmjs.com/package/leerness) [](https://www.npmjs.com/package/leerness) []() []() []() []() []() []()
|
|
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.
|
|
474
|
+
이 프로젝트는 Leerness v1.9.422 하네스를 사용합니다. 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.
|
|
528
|
+
Leerness v1.9.422는 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.421는 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.
|
|
549
|
+
현재 누적: **70 라운드 (1.9.40 → 1.9.422)** · 매 라운드 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.
|
|
587
|
+
Last synced by Leerness v1.9.422: 2026-06-07
|
|
588
588
|
<!-- leerness:project-readme:end -->
|
|
589
589
|
|
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.
|
|
34
|
+
const VERSION = '1.9.422';
|
|
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') 시 호스트 프로세스 오염.
|
|
@@ -3073,6 +3073,27 @@ 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 큰핸들러 모듈화 7번째: driftCheckCmd → lib/drift.js + DI 위임 + 재귀/동작 (1.9.422)', run: () => {
|
|
3077
|
+
const m = require('../lib/drift');
|
|
3078
|
+
const expOk = typeof m.driftCheckCmd === 'function';
|
|
3079
|
+
const src = read(__filename);
|
|
3080
|
+
const delegated = src.includes("require('../lib/drift')") && src.includes('_drift.driftCheckCmd(root, opts,');
|
|
3081
|
+
const modSrc = read(path.join(path.dirname(__filename), '..', 'lib', 'drift.js'));
|
|
3082
|
+
const bodyMarker = 'auto-fix 활성 ' + '(1.9.82)'; // drift 본문 고유(split-literal 자기참조 회피)
|
|
3083
|
+
const recursionWired = modSrc.includes('driftCheckCmd(root, opts, deps)'); // 재귀에 deps 전달
|
|
3084
|
+
const movedToLib = modSrc.includes("require('./io')") && recursionWired && modSrc.includes(bodyMarker) && !src.includes(bodyMarker);
|
|
3085
|
+
let behavOk = false;
|
|
3086
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), '__leerness_drift_'));
|
|
3087
|
+
const _w = process.stdout.write; let out = '';
|
|
3088
|
+
try {
|
|
3089
|
+
fs.mkdirSync(path.join(tmp, '.harness'), { recursive: true });
|
|
3090
|
+
process.stdout.write = s => { out += s; return true; };
|
|
3091
|
+
// has: --json 만 true(JSON 출력) → --auto-fix false 라 spawn 없음.
|
|
3092
|
+
m.driftCheckCmd(tmp, { json: true }, { VERSION, has: f => f === '--json', arg: (k, d) => d, harnessPath: __filename, readProgressRows, planPath, handoffPath, currentStatePath, taskLogPath, envDiff, _usageStatsPath, _readUsageStats, _updateUserRequest, _scanShellScriptsEncoding, _readFeatureGraph, _detectDeliveredRequests, _autoFixIdempotency });
|
|
3093
|
+
} catch (e) { out = 'ERR:' + e.message; } finally { process.stdout.write = _w; try { fs.rmSync(tmp, { recursive: true, force: true }); } catch {} }
|
|
3094
|
+
try { const j = JSON.parse(out); behavOk = typeof j.score === 'number' && 'level' in j && Array.isArray(j.fired); } catch {}
|
|
3095
|
+
return expOk && delegated && movedToLib && behavOk;
|
|
3096
|
+
} },
|
|
3076
3097
|
{ name: 'UR-0025 큰핸들러 모듈화 6번째: audit → lib/audit.js + DI 위임 + 동작 (1.9.421)', run: () => {
|
|
3077
3098
|
const m = require('../lib/audit');
|
|
3078
3099
|
const expOk = typeof m.audit === 'function';
|
|
@@ -14792,328 +14813,9 @@ function autoUpdateInstall(root) {
|
|
|
14792
14813
|
// 기존 프로젝트의 .viewwork/ 폴더는 그대로 유지 (leerness 가 삭제하지 않음 — 사용자 책임).
|
|
14793
14814
|
|
|
14794
14815
|
// 1.9.37: drift detection — 메타파일 staleness 측정으로 "leerness 점점 안 쓰는" 현상 감지
|
|
14795
|
-
|
|
14796
|
-
|
|
14797
|
-
|
|
14798
|
-
const _ageDays = (p) => {
|
|
14799
|
-
if (!exists(p)) return null;
|
|
14800
|
-
return (now - fs.statSync(p).mtimeMs) / 86400000;
|
|
14801
|
-
};
|
|
14802
|
-
// 각 메타파일의 마지막 갱신
|
|
14803
|
-
const signals = [];
|
|
14804
|
-
// 1. session-handoff.md - "Last generated" 라인 우선, 없으면 mtime
|
|
14805
|
-
const shPath = handoffPath(root);
|
|
14806
|
-
if (exists(shPath)) {
|
|
14807
|
-
const txt = read(shPath);
|
|
14808
|
-
// 1.9.316 (drift 마커 버그): 최신(마지막) 'Last generated' 사용 — 구 블록 중복 시 첫(구) 매치를 읽던 오발화 방어.
|
|
14809
|
-
const allGen = [...txt.matchAll(/Last generated:\s*([\d\-T:.Z]+)/g)];
|
|
14810
|
-
const m = allGen.length ? allGen[allGen.length - 1] : null;
|
|
14811
|
-
let ageDays;
|
|
14812
|
-
if (m) {
|
|
14813
|
-
ageDays = (now - new Date(m[1]).getTime()) / 86400000;
|
|
14814
|
-
} else {
|
|
14815
|
-
ageDays = _ageDays(shPath);
|
|
14816
|
-
}
|
|
14817
|
-
signals.push({ file: 'session-handoff.md', ageDays, threshold: 1, weight: 30, label: 'session close 누락' });
|
|
14818
|
-
}
|
|
14819
|
-
// 2. current-state.md - "Updated: YYYY-MM-DD" 라인
|
|
14820
|
-
const csPath = currentStatePath(root);
|
|
14821
|
-
if (exists(csPath)) {
|
|
14822
|
-
const m = read(csPath).match(/Updated:\s*(\d{4}-\d{2}-\d{2})/);
|
|
14823
|
-
const ageDays = m ? (now - new Date(m[1]).getTime()) / 86400000 : _ageDays(csPath);
|
|
14824
|
-
signals.push({ file: 'current-state.md', ageDays, threshold: 2, weight: 20, label: 'current-state 갱신 없음' });
|
|
14825
|
-
}
|
|
14826
|
-
// 3. progress-tracker.md 마지막 row의 updated 컬럼
|
|
14827
|
-
const rows = readProgressRows(root);
|
|
14828
|
-
if (rows.length) {
|
|
14829
|
-
const dates = rows.map(r => (r.updated || '').match(/\d{4}-\d{2}-\d{2}/)).filter(Boolean).map(m => m[0]);
|
|
14830
|
-
if (dates.length) {
|
|
14831
|
-
dates.sort();
|
|
14832
|
-
const latest = dates[dates.length - 1];
|
|
14833
|
-
const ageDays = (now - new Date(latest).getTime()) / 86400000;
|
|
14834
|
-
signals.push({ file: 'progress-tracker.md', ageDays, threshold: 1, weight: 30, label: 'task update 없음' });
|
|
14835
|
-
}
|
|
14836
|
-
} else {
|
|
14837
|
-
signals.push({ file: 'progress-tracker.md', ageDays: 999, threshold: 1, weight: 25, label: 'progress-tracker 비어있음' });
|
|
14838
|
-
}
|
|
14839
|
-
// 4. task-log.md 마지막 entry "## YYYY-MM-DD"
|
|
14840
|
-
const tlPath = taskLogPath(root);
|
|
14841
|
-
if (exists(tlPath)) {
|
|
14842
|
-
const dates = Array.from(read(tlPath).matchAll(/^## (\d{4}-\d{2}-\d{2})/gm)).map(m => m[1]);
|
|
14843
|
-
if (dates.length) {
|
|
14844
|
-
dates.sort();
|
|
14845
|
-
const latest = dates[dates.length - 1];
|
|
14846
|
-
const ageDays = (now - new Date(latest).getTime()) / 86400000;
|
|
14847
|
-
signals.push({ file: 'task-log.md', ageDays, threshold: 2, weight: 20, label: 'task-log 갱신 없음' });
|
|
14848
|
-
}
|
|
14849
|
-
}
|
|
14850
|
-
// 점수 계산
|
|
14851
|
-
let totalScore = 0;
|
|
14852
|
-
const fired = [];
|
|
14853
|
-
for (const s of signals) {
|
|
14854
|
-
if (s.ageDays > s.threshold) {
|
|
14855
|
-
totalScore += s.weight;
|
|
14856
|
-
fired.push(s);
|
|
14857
|
-
}
|
|
14858
|
-
}
|
|
14859
|
-
// 1.9.78: 보안 신호 (env / .gitignore 누락) — 5번째 신호
|
|
14860
|
-
try {
|
|
14861
|
-
const envPath = path.join(root, '.env');
|
|
14862
|
-
if (exists(envPath)) {
|
|
14863
|
-
let secScore = 0;
|
|
14864
|
-
const secIssues = [];
|
|
14865
|
-
// (a) .env vs .env.example 동기화
|
|
14866
|
-
try {
|
|
14867
|
-
const d = envDiff(root);
|
|
14868
|
-
if (d.inEnvOnly.length) {
|
|
14869
|
-
secIssues.push(`.env→.env.example 누락 ${d.inEnvOnly.length}건`);
|
|
14870
|
-
secScore += 15;
|
|
14871
|
-
}
|
|
14872
|
-
} catch {}
|
|
14873
|
-
// (b) .gitignore 시크릿 패턴
|
|
14874
|
-
try {
|
|
14875
|
-
const giText = exists(path.join(root, '.gitignore')) ? read(path.join(root, '.gitignore')) : '';
|
|
14876
|
-
const giLines = giText.split('\n').map(l => l.trim());
|
|
14877
|
-
const SECRET_PATTERNS = ['.env', '.env.local', '.env.production', '.env.*.local', '*.pem', 'credentials.json'];
|
|
14878
|
-
const missing = SECRET_PATTERNS.filter(p => !giLines.some(l => l === p || l === '/' + p));
|
|
14879
|
-
if (missing.length) {
|
|
14880
|
-
secIssues.push(`.gitignore 시크릿 누락 ${missing.length}건`);
|
|
14881
|
-
// 누락이 .env 자체면 최우선 위험 — 15점 가중
|
|
14882
|
-
if (missing.includes('.env')) secScore += 30;
|
|
14883
|
-
else secScore += Math.min(20, missing.length * 5);
|
|
14884
|
-
}
|
|
14885
|
-
} catch {}
|
|
14886
|
-
if (secScore > 0) {
|
|
14887
|
-
totalScore += secScore;
|
|
14888
|
-
fired.push({ file: '.env / .gitignore', ageDays: null, threshold: 0, weight: secScore, label: `보안 위험 (1.9.78): ${secIssues.join(' · ')}` });
|
|
14889
|
-
}
|
|
14890
|
-
}
|
|
14891
|
-
} catch {}
|
|
14892
|
-
// 1.9.143: Feature Graph 미사용 신호 — 노드는 있는데 edges 비율 낮으면 인과관계 정리 미진
|
|
14893
|
-
try {
|
|
14894
|
-
const { nodes: fGraphNodes } = _readFeatureGraph(root);
|
|
14895
|
-
if (fGraphNodes.length >= 3) {
|
|
14896
|
-
const edgeCount = fGraphNodes.reduce((s, n) => s + (n.dependsOn?.length || 0) + (n.affects?.length || 0) + (n.coChangesWith?.length || 0), 0);
|
|
14897
|
-
const linkedSet = new Set();
|
|
14898
|
-
for (const n of fGraphNodes) {
|
|
14899
|
-
for (const x of [...(n.dependsOn||[]), ...(n.affects||[]), ...(n.coChangesWith||[])]) { linkedSet.add(n.id); linkedSet.add(x); }
|
|
14900
|
-
}
|
|
14901
|
-
const isolatedCount = Math.max(0, fGraphNodes.length - linkedSet.size);
|
|
14902
|
-
const isolatedRatio = isolatedCount / fGraphNodes.length;
|
|
14903
|
-
if (edgeCount === 0 || isolatedRatio >= 0.5) {
|
|
14904
|
-
const fgScore = edgeCount === 0 ? 25 : 15;
|
|
14905
|
-
totalScore += fgScore;
|
|
14906
|
-
fired.push({ file: '.harness/feature-graph.md', ageDays: null, threshold: 0, weight: fgScore, label: `Feature Graph 미정리 (1.9.143): ${fGraphNodes.length} 노드, edges=${edgeCount}, isolated=${isolatedCount}` });
|
|
14907
|
-
}
|
|
14908
|
-
}
|
|
14909
|
-
} catch {}
|
|
14910
|
-
// 신규 _apps/* 에서 task 0건도 신호로
|
|
14911
|
-
const appsDir = path.join(root, '_apps');
|
|
14912
|
-
let appsZeroTask = [];
|
|
14913
|
-
if (exists(appsDir)) {
|
|
14914
|
-
for (const d of fs.readdirSync(appsDir)) {
|
|
14915
|
-
const sub = path.join(appsDir, d);
|
|
14916
|
-
if (!exists(path.join(sub, '.harness'))) continue;
|
|
14917
|
-
const subRows = readProgressRows(sub);
|
|
14918
|
-
if (!subRows.length) appsZeroTask.push(d);
|
|
14919
|
-
}
|
|
14920
|
-
if (appsZeroTask.length) {
|
|
14921
|
-
const w = Math.min(50, appsZeroTask.length * 10);
|
|
14922
|
-
totalScore += w;
|
|
14923
|
-
fired.push({ file: `_apps/* (${appsZeroTask.length}개)`, ageDays: null, threshold: 0, weight: w, label: `task 0건 sub-app: ${appsZeroTask.slice(0, 3).join(', ')}${appsZeroTask.length > 3 ? '...' : ''}` });
|
|
14924
|
-
}
|
|
14925
|
-
}
|
|
14926
|
-
// 레벨 판정
|
|
14927
|
-
let level = '🟢 healthy';
|
|
14928
|
-
if (totalScore >= 100) level = '🔴 critical';
|
|
14929
|
-
else if (totalScore >= 50) level = '🟡 warning';
|
|
14930
|
-
else if (totalScore >= 20) level = '🟠 attention';
|
|
14931
|
-
|
|
14932
|
-
// 1.9.38 (D): drift critical 등급은 누적 카운트 (학습 신호)
|
|
14933
|
-
try {
|
|
14934
|
-
if (level === '🔴 critical') {
|
|
14935
|
-
const stats = _readUsageStats(root);
|
|
14936
|
-
stats.drift = stats.drift || {};
|
|
14937
|
-
stats.drift.criticalSeen = (stats.drift.criticalSeen || 0) + 1;
|
|
14938
|
-
const p = _usageStatsPath(root);
|
|
14939
|
-
mkdirp(path.dirname(p));
|
|
14940
|
-
writeUtf8(p, JSON.stringify(stats, null, 2) + '\n');
|
|
14941
|
-
}
|
|
14942
|
-
} catch {}
|
|
14943
|
-
// 1.9.39: --auto-fix — critical 시 session close 자동 실행
|
|
14944
|
-
// 1.9.82: --auto-fix가 보안 신호도 자동 회복 (audit --fix 호출)
|
|
14945
|
-
const autoFix = has('--auto-fix');
|
|
14946
|
-
// 1.9.82: 보안 신호가 fired에 있으면 우선 audit --fix 호출
|
|
14947
|
-
const hasSecurityFired = fired.some(f => /보안 위험 \(1\.9\.78\)/.test(f.label));
|
|
14948
|
-
if (autoFix && hasSecurityFired) {
|
|
14949
|
-
log('');
|
|
14950
|
-
log(`🔒 --auto-fix 활성 (1.9.82) — 보안 신호 회복: audit --fix 자동 실행 중...`);
|
|
14951
|
-
try {
|
|
14952
|
-
const r = cp.spawnSync(process.execPath, [__filename, 'audit', root, '--fix'],
|
|
14953
|
-
{ encoding: 'utf8', timeout: 30000, env: { ...process.env, LEERNESS_INTERNAL: '1', LEERNESS_NO_PROMPT: '1', LEERNESS_NO_DRIFT_CHECK: '1' } });
|
|
14954
|
-
if (r.status === 0) {
|
|
14955
|
-
log(`✓ audit --fix 완료 — .gitignore + .env.example 동기화`);
|
|
14956
|
-
// 재검사 (보안 신호 회복 확인)
|
|
14957
|
-
log('');
|
|
14958
|
-
log(`재검사 중...`);
|
|
14959
|
-
return driftCheckCmd(root); // 재귀 1회 (auto-fix 없이)
|
|
14960
|
-
} else {
|
|
14961
|
-
log(`⚠ audit --fix 실패 (exit ${r.status}) — 수동 \`leerness audit --fix\` 권장`);
|
|
14962
|
-
}
|
|
14963
|
-
} catch (e) {
|
|
14964
|
-
log(`⚠ auto-fix 보안 회복 오류: ${e.message}`);
|
|
14965
|
-
}
|
|
14966
|
-
}
|
|
14967
|
-
// 1.9.242: drift check --auto-fix 에 env encoding BOM 자동 추가 통합 (사용자 명시 UR-0014 2단계)
|
|
14968
|
-
// 1.9.82 패턴 확장 — drift 회복 시 셸 스크립트 인코딩 위험도 자동 해결
|
|
14969
|
-
if (autoFix) {
|
|
14970
|
-
try {
|
|
14971
|
-
const encScan = _scanShellScriptsEncoding(root);
|
|
14972
|
-
if (encScan.atRisk && encScan.atRisk.length > 0) {
|
|
14973
|
-
log('');
|
|
14974
|
-
log(`🌐 --auto-fix 활성 (1.9.242) — 셸 스크립트 인코딩 위험 ${encScan.atRisk.length}건 BOM 자동 추가 중...`);
|
|
14975
|
-
let ok = 0;
|
|
14976
|
-
for (const r of encScan.atRisk) {
|
|
14977
|
-
try {
|
|
14978
|
-
const fullPath = path.join(root, r.file);
|
|
14979
|
-
const orig = fs.readFileSync(fullPath);
|
|
14980
|
-
const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
|
|
14981
|
-
const fixed = Buffer.concat([bom, orig]);
|
|
14982
|
-
fs.writeFileSync(fullPath, fixed);
|
|
14983
|
-
ok++;
|
|
14984
|
-
} catch {}
|
|
14985
|
-
}
|
|
14986
|
-
log(`✓ UTF-8 BOM 추가 ${ok}/${encScan.atRisk.length}건 (1.9.242 UR-0014)`);
|
|
14987
|
-
}
|
|
14988
|
-
} catch (e) {
|
|
14989
|
-
log(`⚠ env encoding auto-fix 오류 (1.9.242): ${e.message}`);
|
|
14990
|
-
}
|
|
14991
|
-
}
|
|
14992
|
-
// 1.9.225: drift check --auto-fix 에 delivered 패턴 자동 적용 통합 (1.9.223/224 시스템 회수)
|
|
14993
|
-
// 사용자 요청에 "구현 완료" 패턴이 누적되면 가짜 미답 신호가 drift score 를 가중시킬 수 있음 → 자동 정리.
|
|
14994
|
-
// 1.9.82 audit --fix 패턴과 동일: --auto-fix 시 즉시 적용, 적용 후 재검사.
|
|
14995
|
-
if (autoFix) {
|
|
14996
|
-
try {
|
|
14997
|
-
const delivered = _detectDeliveredRequests(root);
|
|
14998
|
-
if (delivered.candidates && delivered.candidates.length > 0) {
|
|
14999
|
-
log('');
|
|
15000
|
-
log(`📥 --auto-fix 활성 (1.9.225) — delivered 패턴 ${delivered.candidates.length}건 자동 완료 중...`);
|
|
15001
|
-
let ok = 0;
|
|
15002
|
-
for (const c of delivered.candidates) {
|
|
15003
|
-
const u = _updateUserRequest(root, c.id, { status: 'completed', autoCompletedAt: new Date().toISOString(), autoCompleteReason: 'drift-auto-fix-1.9.225' });
|
|
15004
|
-
if (u) ok++;
|
|
15005
|
-
}
|
|
15006
|
-
log(`✓ delivered 자동 완료 ${ok}/${delivered.candidates.length}건`);
|
|
15007
|
-
}
|
|
15008
|
-
} catch (e) {
|
|
15009
|
-
log(`⚠ delivered auto-apply 오류 (1.9.225): ${e.message}`);
|
|
15010
|
-
}
|
|
15011
|
-
}
|
|
15012
|
-
// 1.9.293: drift check --auto-fix 에 idempotency task/user-request 중복 자동 정리 통합
|
|
15013
|
-
// 누적 중복 task/요청이 idempotency 위반(medium)을 가중 → drift/handoff 노이즈. 안전: 완전중복 행 제거 + 동일텍스트 dropped 보존(id 유지).
|
|
15014
|
-
if (autoFix) {
|
|
15015
|
-
try {
|
|
15016
|
-
const idemFixes = _autoFixIdempotency(root);
|
|
15017
|
-
const totalFixed = idemFixes.reduce((n, f) => n + (f.removedExact || 0) + (f.droppedSameText || 0) + (f.count || 0), 0);
|
|
15018
|
-
if (totalFixed > 0) {
|
|
15019
|
-
log('');
|
|
15020
|
-
log(`🔁 --auto-fix 활성 (1.9.293) — idempotency 중복 ${totalFixed}건 자동 정리 (task/user-request dedup)`);
|
|
15021
|
-
}
|
|
15022
|
-
} catch (e) {
|
|
15023
|
-
log(`⚠ idempotency auto-fix 오류 (1.9.293): ${e.message}`);
|
|
15024
|
-
}
|
|
15025
|
-
}
|
|
15026
|
-
// 1.9.236: drift check --auto-fix 에 release cleanup 통합 (1.9.235 회수)
|
|
15027
|
-
// 누적된 50개+ release/* branches → abnormal-shutdown release-branch-pending 신호 가중
|
|
15028
|
-
// 안전: keep 10 (최근 10개 유지), merged 만 삭제 (1.9.235 안전 가드)
|
|
15029
|
-
// 임계: 50개 초과 시만 자동 정리 (소량 누적은 정상 운영)
|
|
15030
|
-
if (autoFix) {
|
|
15031
|
-
try {
|
|
15032
|
-
const branchR = cp.spawnSync('git', ['branch', '--merged', 'main', '--list', 'release/*'], { cwd: root, encoding: 'utf8' });
|
|
15033
|
-
if (branchR.status === 0) {
|
|
15034
|
-
const merged = (branchR.stdout || '').split('\n')
|
|
15035
|
-
.map(l => l.replace(/^\*?\s+/, '').trim())
|
|
15036
|
-
.filter(l => l && /^release\/\d+\.\d+\.\d+$/.test(l));
|
|
15037
|
-
if (merged.length > 50) {
|
|
15038
|
-
log('');
|
|
15039
|
-
log(`🗑 --auto-fix 활성 (1.9.236) — release/* merged ${merged.length}개 (50+) 자동 정리 (keep 10)...`);
|
|
15040
|
-
// 정렬 (semver desc)
|
|
15041
|
-
merged.sort((a, b) => {
|
|
15042
|
-
const va = a.replace('release/', '').split('.').map(n => parseInt(n, 10) || 0);
|
|
15043
|
-
const vb = b.replace('release/', '').split('.').map(n => parseInt(n, 10) || 0);
|
|
15044
|
-
for (let i = 0; i < 3; i++) if (va[i] !== vb[i]) return vb[i] - va[i];
|
|
15045
|
-
return 0;
|
|
15046
|
-
});
|
|
15047
|
-
const currentBranchR = cp.spawnSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: root, encoding: 'utf8' });
|
|
15048
|
-
const currentBranch = (currentBranchR.stdout || '').trim();
|
|
15049
|
-
const toDelete = merged.slice(10).filter(b => b !== currentBranch);
|
|
15050
|
-
let ok = 0;
|
|
15051
|
-
for (const b of toDelete) {
|
|
15052
|
-
const r = cp.spawnSync('git', ['branch', '-d', b], { cwd: root, encoding: 'utf8' });
|
|
15053
|
-
if (r.status === 0) ok++;
|
|
15054
|
-
}
|
|
15055
|
-
log(`✓ release cleanup 자동 완료 ${ok}/${toDelete.length}건 (keep 10)`);
|
|
15056
|
-
}
|
|
15057
|
-
}
|
|
15058
|
-
} catch (e) {
|
|
15059
|
-
log(`⚠ release cleanup auto-fix 오류 (1.9.236): ${e.message}`);
|
|
15060
|
-
}
|
|
15061
|
-
}
|
|
15062
|
-
if (autoFix && level === '🔴 critical' && !hasSecurityFired) {
|
|
15063
|
-
log('');
|
|
15064
|
-
log(`🔧 --auto-fix 활성 — session close 자동 실행 중...`);
|
|
15065
|
-
try {
|
|
15066
|
-
const r = cp.spawnSync(process.execPath, [__filename, 'session', 'close', root], { encoding: 'utf8', timeout: 60000, env: { ...process.env, LEERNESS_INTERNAL: '1' } });
|
|
15067
|
-
if (r.status === 0) {
|
|
15068
|
-
log(`✓ session close 자동 완료`);
|
|
15069
|
-
// autoResolved 카운트
|
|
15070
|
-
const stats = _readUsageStats(root);
|
|
15071
|
-
stats.drift = stats.drift || {};
|
|
15072
|
-
stats.drift.autoResolved = (stats.drift.autoResolved || 0) + 1;
|
|
15073
|
-
const p = _usageStatsPath(root);
|
|
15074
|
-
mkdirp(path.dirname(p));
|
|
15075
|
-
writeUtf8(p, JSON.stringify(stats, null, 2) + '\n');
|
|
15076
|
-
// 재검사
|
|
15077
|
-
log('');
|
|
15078
|
-
log(`재검사 중...`);
|
|
15079
|
-
return driftCheckCmd(root); // 재귀 1회 (auto-fix 없이)
|
|
15080
|
-
} else {
|
|
15081
|
-
log(`⚠ session close 실패 (exit ${r.status}) — 수동 실행 필요`);
|
|
15082
|
-
}
|
|
15083
|
-
} catch (e) {
|
|
15084
|
-
log(`⚠ auto-fix 오류: ${e.message}`);
|
|
15085
|
-
}
|
|
15086
|
-
}
|
|
15087
|
-
if (has('--json')) {
|
|
15088
|
-
log(JSON.stringify({ root, score: totalScore, level, signals, fired, appsZeroTask }, null, 2));
|
|
15089
|
-
return;
|
|
15090
|
-
}
|
|
15091
|
-
log(`# leerness drift check (1.9.37)`);
|
|
15092
|
-
log(`경로: ${root}`);
|
|
15093
|
-
log('');
|
|
15094
|
-
log(`상태: ${level} · 점수 ${totalScore}/200`);
|
|
15095
|
-
log('');
|
|
15096
|
-
log(`| 신호 | age | 임계 | 가중치 | 발화 |`);
|
|
15097
|
-
log(`|---|---:|---:|---:|---|`);
|
|
15098
|
-
for (const s of signals) {
|
|
15099
|
-
const fire = s.ageDays > s.threshold ? '🔥' : '✓';
|
|
15100
|
-
const age = s.ageDays === null ? '-' : `${s.ageDays.toFixed(1)}d`;
|
|
15101
|
-
log(`| ${s.label} | ${age} | ${s.threshold}d | ${s.weight} | ${fire} |`);
|
|
15102
|
-
}
|
|
15103
|
-
if (appsZeroTask.length) {
|
|
15104
|
-
log('');
|
|
15105
|
-
log(`task 0건 sub-app (${appsZeroTask.length}개): ${appsZeroTask.join(', ')}`);
|
|
15106
|
-
}
|
|
15107
|
-
if (totalScore >= 50) {
|
|
15108
|
-
log('');
|
|
15109
|
-
log(`💡 권장 조치:`);
|
|
15110
|
-
log(` - 즉시: leerness session close . (handoff/current-state 갱신)`);
|
|
15111
|
-
log(` - 또는: leerness audit . --fix (자동 갱신 가능 항목 적용)`);
|
|
15112
|
-
log(` - sub-app에 task 등록: cd _apps/X && leerness task add "..."`);
|
|
15113
|
-
log(` - 이 검사 끄기: --no-drift-check 또는 LEERNESS_NO_DRIFT_CHECK=1`);
|
|
15114
|
-
}
|
|
15115
|
-
if (level === '🔴 critical') process.exitCode = 1;
|
|
15116
|
-
}
|
|
14816
|
+
const _drift = require('../lib/drift');
|
|
14817
|
+
// 1.9.422 (UR-0025/UR-0125 큰 핸들러 모듈화 7번째): driftCheckCmd → lib/drift.js (DI 위임, thin wrapper)
|
|
14818
|
+
function driftCheckCmd(root, opts = {}) { return _drift.driftCheckCmd(root, opts, { VERSION, has, arg, harnessPath: __filename, readProgressRows, planPath, handoffPath, currentStatePath, taskLogPath, envDiff, _usageStatsPath, _readUsageStats, _updateUserRequest, _scanShellScriptsEncoding, _readFeatureGraph, _detectDeliveredRequests, _autoFixIdempotency }); }
|
|
15117
14819
|
|
|
15118
14820
|
// 1.9.69: skill-suggestions.md rolling history 인덱스 — mtime 기반 캐시
|
|
15119
14821
|
// handoff에서 같은 키워드 과거 추천 결과를 즉시 노출 (재매칭 불필요)
|
package/lib/drift.js
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
// lib/drift.js — drift check 핸들러 (UR-0025/UR-0125 큰 핸들러 모듈화 7번째, 1.9.422)
|
|
2
|
+
// bin/leerness.js 에서 driftCheckCmd(322줄) 분리. DI: harness 고유 의존(VERSION, has, arg, harnessPath, readProgressRows, planPath, handoffPath, currentStatePath, _usageStatsPath, _readUsageStats, _updateUserRequest, _scanShellScriptsEncoding, _readFeatureGraph, _detectDeliveredRequests, _autoFixIdempotency) 주입.
|
|
3
|
+
// io 프리미티브는 ./io, cp/path 빌트인. 내부 재귀(auto-fix 후 재검사)는 deps 전달. 동작/출력 무변경.
|
|
4
|
+
'use strict';
|
|
5
|
+
const cp = require('child_process');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const { log, ok, warn, fail, failJson, today, now, absRoot, exists, read, readBuf, mkdirp, writeUtf8, append, rel } = require('./io');
|
|
9
|
+
|
|
10
|
+
function driftCheckCmd(root, opts = {}, deps = {}) {
|
|
11
|
+
const { VERSION, has, arg, harnessPath, readProgressRows, planPath, handoffPath, currentStatePath, taskLogPath, envDiff, _usageStatsPath, _readUsageStats, _updateUserRequest, _scanShellScriptsEncoding, _readFeatureGraph, _detectDeliveredRequests, _autoFixIdempotency } = deps;
|
|
12
|
+
root = absRoot(root || process.cwd());
|
|
13
|
+
const now = Date.now();
|
|
14
|
+
const _ageDays = (p) => {
|
|
15
|
+
if (!exists(p)) return null;
|
|
16
|
+
return (now - fs.statSync(p).mtimeMs) / 86400000;
|
|
17
|
+
};
|
|
18
|
+
// 각 메타파일의 마지막 갱신
|
|
19
|
+
const signals = [];
|
|
20
|
+
// 1. session-handoff.md - "Last generated" 라인 우선, 없으면 mtime
|
|
21
|
+
const shPath = handoffPath(root);
|
|
22
|
+
if (exists(shPath)) {
|
|
23
|
+
const txt = read(shPath);
|
|
24
|
+
// 1.9.316 (drift 마커 버그): 최신(마지막) 'Last generated' 사용 — 구 블록 중복 시 첫(구) 매치를 읽던 오발화 방어.
|
|
25
|
+
const allGen = [...txt.matchAll(/Last generated:\s*([\d\-T:.Z]+)/g)];
|
|
26
|
+
const m = allGen.length ? allGen[allGen.length - 1] : null;
|
|
27
|
+
let ageDays;
|
|
28
|
+
if (m) {
|
|
29
|
+
ageDays = (now - new Date(m[1]).getTime()) / 86400000;
|
|
30
|
+
} else {
|
|
31
|
+
ageDays = _ageDays(shPath);
|
|
32
|
+
}
|
|
33
|
+
signals.push({ file: 'session-handoff.md', ageDays, threshold: 1, weight: 30, label: 'session close 누락' });
|
|
34
|
+
}
|
|
35
|
+
// 2. current-state.md - "Updated: YYYY-MM-DD" 라인
|
|
36
|
+
const csPath = currentStatePath(root);
|
|
37
|
+
if (exists(csPath)) {
|
|
38
|
+
const m = read(csPath).match(/Updated:\s*(\d{4}-\d{2}-\d{2})/);
|
|
39
|
+
const ageDays = m ? (now - new Date(m[1]).getTime()) / 86400000 : _ageDays(csPath);
|
|
40
|
+
signals.push({ file: 'current-state.md', ageDays, threshold: 2, weight: 20, label: 'current-state 갱신 없음' });
|
|
41
|
+
}
|
|
42
|
+
// 3. progress-tracker.md 마지막 row의 updated 컬럼
|
|
43
|
+
const rows = readProgressRows(root);
|
|
44
|
+
if (rows.length) {
|
|
45
|
+
const dates = rows.map(r => (r.updated || '').match(/\d{4}-\d{2}-\d{2}/)).filter(Boolean).map(m => m[0]);
|
|
46
|
+
if (dates.length) {
|
|
47
|
+
dates.sort();
|
|
48
|
+
const latest = dates[dates.length - 1];
|
|
49
|
+
const ageDays = (now - new Date(latest).getTime()) / 86400000;
|
|
50
|
+
signals.push({ file: 'progress-tracker.md', ageDays, threshold: 1, weight: 30, label: 'task update 없음' });
|
|
51
|
+
}
|
|
52
|
+
} else {
|
|
53
|
+
signals.push({ file: 'progress-tracker.md', ageDays: 999, threshold: 1, weight: 25, label: 'progress-tracker 비어있음' });
|
|
54
|
+
}
|
|
55
|
+
// 4. task-log.md 마지막 entry "## YYYY-MM-DD"
|
|
56
|
+
const tlPath = taskLogPath(root);
|
|
57
|
+
if (exists(tlPath)) {
|
|
58
|
+
const dates = Array.from(read(tlPath).matchAll(/^## (\d{4}-\d{2}-\d{2})/gm)).map(m => m[1]);
|
|
59
|
+
if (dates.length) {
|
|
60
|
+
dates.sort();
|
|
61
|
+
const latest = dates[dates.length - 1];
|
|
62
|
+
const ageDays = (now - new Date(latest).getTime()) / 86400000;
|
|
63
|
+
signals.push({ file: 'task-log.md', ageDays, threshold: 2, weight: 20, label: 'task-log 갱신 없음' });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// 점수 계산
|
|
67
|
+
let totalScore = 0;
|
|
68
|
+
const fired = [];
|
|
69
|
+
for (const s of signals) {
|
|
70
|
+
if (s.ageDays > s.threshold) {
|
|
71
|
+
totalScore += s.weight;
|
|
72
|
+
fired.push(s);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
// 1.9.78: 보안 신호 (env / .gitignore 누락) — 5번째 신호
|
|
76
|
+
try {
|
|
77
|
+
const envPath = path.join(root, '.env');
|
|
78
|
+
if (exists(envPath)) {
|
|
79
|
+
let secScore = 0;
|
|
80
|
+
const secIssues = [];
|
|
81
|
+
// (a) .env vs .env.example 동기화
|
|
82
|
+
try {
|
|
83
|
+
const d = envDiff(root);
|
|
84
|
+
if (d.inEnvOnly.length) {
|
|
85
|
+
secIssues.push(`.env→.env.example 누락 ${d.inEnvOnly.length}건`);
|
|
86
|
+
secScore += 15;
|
|
87
|
+
}
|
|
88
|
+
} catch {}
|
|
89
|
+
// (b) .gitignore 시크릿 패턴
|
|
90
|
+
try {
|
|
91
|
+
const giText = exists(path.join(root, '.gitignore')) ? read(path.join(root, '.gitignore')) : '';
|
|
92
|
+
const giLines = giText.split('\n').map(l => l.trim());
|
|
93
|
+
const SECRET_PATTERNS = ['.env', '.env.local', '.env.production', '.env.*.local', '*.pem', 'credentials.json'];
|
|
94
|
+
const missing = SECRET_PATTERNS.filter(p => !giLines.some(l => l === p || l === '/' + p));
|
|
95
|
+
if (missing.length) {
|
|
96
|
+
secIssues.push(`.gitignore 시크릿 누락 ${missing.length}건`);
|
|
97
|
+
// 누락이 .env 자체면 최우선 위험 — 15점 가중
|
|
98
|
+
if (missing.includes('.env')) secScore += 30;
|
|
99
|
+
else secScore += Math.min(20, missing.length * 5);
|
|
100
|
+
}
|
|
101
|
+
} catch {}
|
|
102
|
+
if (secScore > 0) {
|
|
103
|
+
totalScore += secScore;
|
|
104
|
+
fired.push({ file: '.env / .gitignore', ageDays: null, threshold: 0, weight: secScore, label: `보안 위험 (1.9.78): ${secIssues.join(' · ')}` });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
} catch {}
|
|
108
|
+
// 1.9.143: Feature Graph 미사용 신호 — 노드는 있는데 edges 비율 낮으면 인과관계 정리 미진
|
|
109
|
+
try {
|
|
110
|
+
const { nodes: fGraphNodes } = _readFeatureGraph(root);
|
|
111
|
+
if (fGraphNodes.length >= 3) {
|
|
112
|
+
const edgeCount = fGraphNodes.reduce((s, n) => s + (n.dependsOn?.length || 0) + (n.affects?.length || 0) + (n.coChangesWith?.length || 0), 0);
|
|
113
|
+
const linkedSet = new Set();
|
|
114
|
+
for (const n of fGraphNodes) {
|
|
115
|
+
for (const x of [...(n.dependsOn||[]), ...(n.affects||[]), ...(n.coChangesWith||[])]) { linkedSet.add(n.id); linkedSet.add(x); }
|
|
116
|
+
}
|
|
117
|
+
const isolatedCount = Math.max(0, fGraphNodes.length - linkedSet.size);
|
|
118
|
+
const isolatedRatio = isolatedCount / fGraphNodes.length;
|
|
119
|
+
if (edgeCount === 0 || isolatedRatio >= 0.5) {
|
|
120
|
+
const fgScore = edgeCount === 0 ? 25 : 15;
|
|
121
|
+
totalScore += fgScore;
|
|
122
|
+
fired.push({ file: '.harness/feature-graph.md', ageDays: null, threshold: 0, weight: fgScore, label: `Feature Graph 미정리 (1.9.143): ${fGraphNodes.length} 노드, edges=${edgeCount}, isolated=${isolatedCount}` });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
} catch {}
|
|
126
|
+
// 신규 _apps/* 에서 task 0건도 신호로
|
|
127
|
+
const appsDir = path.join(root, '_apps');
|
|
128
|
+
let appsZeroTask = [];
|
|
129
|
+
if (exists(appsDir)) {
|
|
130
|
+
for (const d of fs.readdirSync(appsDir)) {
|
|
131
|
+
const sub = path.join(appsDir, d);
|
|
132
|
+
if (!exists(path.join(sub, '.harness'))) continue;
|
|
133
|
+
const subRows = readProgressRows(sub);
|
|
134
|
+
if (!subRows.length) appsZeroTask.push(d);
|
|
135
|
+
}
|
|
136
|
+
if (appsZeroTask.length) {
|
|
137
|
+
const w = Math.min(50, appsZeroTask.length * 10);
|
|
138
|
+
totalScore += w;
|
|
139
|
+
fired.push({ file: `_apps/* (${appsZeroTask.length}개)`, ageDays: null, threshold: 0, weight: w, label: `task 0건 sub-app: ${appsZeroTask.slice(0, 3).join(', ')}${appsZeroTask.length > 3 ? '...' : ''}` });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
// 레벨 판정
|
|
143
|
+
let level = '🟢 healthy';
|
|
144
|
+
if (totalScore >= 100) level = '🔴 critical';
|
|
145
|
+
else if (totalScore >= 50) level = '🟡 warning';
|
|
146
|
+
else if (totalScore >= 20) level = '🟠 attention';
|
|
147
|
+
|
|
148
|
+
// 1.9.38 (D): drift critical 등급은 누적 카운트 (학습 신호)
|
|
149
|
+
try {
|
|
150
|
+
if (level === '🔴 critical') {
|
|
151
|
+
const stats = _readUsageStats(root);
|
|
152
|
+
stats.drift = stats.drift || {};
|
|
153
|
+
stats.drift.criticalSeen = (stats.drift.criticalSeen || 0) + 1;
|
|
154
|
+
const p = _usageStatsPath(root);
|
|
155
|
+
mkdirp(path.dirname(p));
|
|
156
|
+
writeUtf8(p, JSON.stringify(stats, null, 2) + '\n');
|
|
157
|
+
}
|
|
158
|
+
} catch {}
|
|
159
|
+
// 1.9.39: --auto-fix — critical 시 session close 자동 실행
|
|
160
|
+
// 1.9.82: --auto-fix가 보안 신호도 자동 회복 (audit --fix 호출)
|
|
161
|
+
const autoFix = has('--auto-fix');
|
|
162
|
+
// 1.9.82: 보안 신호가 fired에 있으면 우선 audit --fix 호출
|
|
163
|
+
const hasSecurityFired = fired.some(f => /보안 위험 \(1\.9\.78\)/.test(f.label));
|
|
164
|
+
if (autoFix && hasSecurityFired) {
|
|
165
|
+
log('');
|
|
166
|
+
log(`🔒 --auto-fix 활성 (1.9.82) — 보안 신호 회복: audit --fix 자동 실행 중...`);
|
|
167
|
+
try {
|
|
168
|
+
const r = cp.spawnSync(process.execPath, [harnessPath, 'audit', root, '--fix'],
|
|
169
|
+
{ encoding: 'utf8', timeout: 30000, env: { ...process.env, LEERNESS_INTERNAL: '1', LEERNESS_NO_PROMPT: '1', LEERNESS_NO_DRIFT_CHECK: '1' } });
|
|
170
|
+
if (r.status === 0) {
|
|
171
|
+
log(`✓ audit --fix 완료 — .gitignore + .env.example 동기화`);
|
|
172
|
+
// 재검사 (보안 신호 회복 확인)
|
|
173
|
+
log('');
|
|
174
|
+
log(`재검사 중...`);
|
|
175
|
+
return driftCheckCmd(root, opts, deps); // 재귀 1회 (auto-fix 없이)
|
|
176
|
+
} else {
|
|
177
|
+
log(`⚠ audit --fix 실패 (exit ${r.status}) — 수동 \`leerness audit --fix\` 권장`);
|
|
178
|
+
}
|
|
179
|
+
} catch (e) {
|
|
180
|
+
log(`⚠ auto-fix 보안 회복 오류: ${e.message}`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// 1.9.242: drift check --auto-fix 에 env encoding BOM 자동 추가 통합 (사용자 명시 UR-0014 2단계)
|
|
184
|
+
// 1.9.82 패턴 확장 — drift 회복 시 셸 스크립트 인코딩 위험도 자동 해결
|
|
185
|
+
if (autoFix) {
|
|
186
|
+
try {
|
|
187
|
+
const encScan = _scanShellScriptsEncoding(root);
|
|
188
|
+
if (encScan.atRisk && encScan.atRisk.length > 0) {
|
|
189
|
+
log('');
|
|
190
|
+
log(`🌐 --auto-fix 활성 (1.9.242) — 셸 스크립트 인코딩 위험 ${encScan.atRisk.length}건 BOM 자동 추가 중...`);
|
|
191
|
+
let ok = 0;
|
|
192
|
+
for (const r of encScan.atRisk) {
|
|
193
|
+
try {
|
|
194
|
+
const fullPath = path.join(root, r.file);
|
|
195
|
+
const orig = fs.readFileSync(fullPath);
|
|
196
|
+
const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
|
|
197
|
+
const fixed = Buffer.concat([bom, orig]);
|
|
198
|
+
fs.writeFileSync(fullPath, fixed);
|
|
199
|
+
ok++;
|
|
200
|
+
} catch {}
|
|
201
|
+
}
|
|
202
|
+
log(`✓ UTF-8 BOM 추가 ${ok}/${encScan.atRisk.length}건 (1.9.242 UR-0014)`);
|
|
203
|
+
}
|
|
204
|
+
} catch (e) {
|
|
205
|
+
log(`⚠ env encoding auto-fix 오류 (1.9.242): ${e.message}`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
// 1.9.225: drift check --auto-fix 에 delivered 패턴 자동 적용 통합 (1.9.223/224 시스템 회수)
|
|
209
|
+
// 사용자 요청에 "구현 완료" 패턴이 누적되면 가짜 미답 신호가 drift score 를 가중시킬 수 있음 → 자동 정리.
|
|
210
|
+
// 1.9.82 audit --fix 패턴과 동일: --auto-fix 시 즉시 적용, 적용 후 재검사.
|
|
211
|
+
if (autoFix) {
|
|
212
|
+
try {
|
|
213
|
+
const delivered = _detectDeliveredRequests(root);
|
|
214
|
+
if (delivered.candidates && delivered.candidates.length > 0) {
|
|
215
|
+
log('');
|
|
216
|
+
log(`📥 --auto-fix 활성 (1.9.225) — delivered 패턴 ${delivered.candidates.length}건 자동 완료 중...`);
|
|
217
|
+
let ok = 0;
|
|
218
|
+
for (const c of delivered.candidates) {
|
|
219
|
+
const u = _updateUserRequest(root, c.id, { status: 'completed', autoCompletedAt: new Date().toISOString(), autoCompleteReason: 'drift-auto-fix-1.9.225' });
|
|
220
|
+
if (u) ok++;
|
|
221
|
+
}
|
|
222
|
+
log(`✓ delivered 자동 완료 ${ok}/${delivered.candidates.length}건`);
|
|
223
|
+
}
|
|
224
|
+
} catch (e) {
|
|
225
|
+
log(`⚠ delivered auto-apply 오류 (1.9.225): ${e.message}`);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
// 1.9.293: drift check --auto-fix 에 idempotency task/user-request 중복 자동 정리 통합
|
|
229
|
+
// 누적 중복 task/요청이 idempotency 위반(medium)을 가중 → drift/handoff 노이즈. 안전: 완전중복 행 제거 + 동일텍스트 dropped 보존(id 유지).
|
|
230
|
+
if (autoFix) {
|
|
231
|
+
try {
|
|
232
|
+
const idemFixes = _autoFixIdempotency(root);
|
|
233
|
+
const totalFixed = idemFixes.reduce((n, f) => n + (f.removedExact || 0) + (f.droppedSameText || 0) + (f.count || 0), 0);
|
|
234
|
+
if (totalFixed > 0) {
|
|
235
|
+
log('');
|
|
236
|
+
log(`🔁 --auto-fix 활성 (1.9.293) — idempotency 중복 ${totalFixed}건 자동 정리 (task/user-request dedup)`);
|
|
237
|
+
}
|
|
238
|
+
} catch (e) {
|
|
239
|
+
log(`⚠ idempotency auto-fix 오류 (1.9.293): ${e.message}`);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
// 1.9.236: drift check --auto-fix 에 release cleanup 통합 (1.9.235 회수)
|
|
243
|
+
// 누적된 50개+ release/* branches → abnormal-shutdown release-branch-pending 신호 가중
|
|
244
|
+
// 안전: keep 10 (최근 10개 유지), merged 만 삭제 (1.9.235 안전 가드)
|
|
245
|
+
// 임계: 50개 초과 시만 자동 정리 (소량 누적은 정상 운영)
|
|
246
|
+
if (autoFix) {
|
|
247
|
+
try {
|
|
248
|
+
const branchR = cp.spawnSync('git', ['branch', '--merged', 'main', '--list', 'release/*'], { cwd: root, encoding: 'utf8' });
|
|
249
|
+
if (branchR.status === 0) {
|
|
250
|
+
const merged = (branchR.stdout || '').split('\n')
|
|
251
|
+
.map(l => l.replace(/^\*?\s+/, '').trim())
|
|
252
|
+
.filter(l => l && /^release\/\d+\.\d+\.\d+$/.test(l));
|
|
253
|
+
if (merged.length > 50) {
|
|
254
|
+
log('');
|
|
255
|
+
log(`🗑 --auto-fix 활성 (1.9.236) — release/* merged ${merged.length}개 (50+) 자동 정리 (keep 10)...`);
|
|
256
|
+
// 정렬 (semver desc)
|
|
257
|
+
merged.sort((a, b) => {
|
|
258
|
+
const va = a.replace('release/', '').split('.').map(n => parseInt(n, 10) || 0);
|
|
259
|
+
const vb = b.replace('release/', '').split('.').map(n => parseInt(n, 10) || 0);
|
|
260
|
+
for (let i = 0; i < 3; i++) if (va[i] !== vb[i]) return vb[i] - va[i];
|
|
261
|
+
return 0;
|
|
262
|
+
});
|
|
263
|
+
const currentBranchR = cp.spawnSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: root, encoding: 'utf8' });
|
|
264
|
+
const currentBranch = (currentBranchR.stdout || '').trim();
|
|
265
|
+
const toDelete = merged.slice(10).filter(b => b !== currentBranch);
|
|
266
|
+
let ok = 0;
|
|
267
|
+
for (const b of toDelete) {
|
|
268
|
+
const r = cp.spawnSync('git', ['branch', '-d', b], { cwd: root, encoding: 'utf8' });
|
|
269
|
+
if (r.status === 0) ok++;
|
|
270
|
+
}
|
|
271
|
+
log(`✓ release cleanup 자동 완료 ${ok}/${toDelete.length}건 (keep 10)`);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
} catch (e) {
|
|
275
|
+
log(`⚠ release cleanup auto-fix 오류 (1.9.236): ${e.message}`);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
if (autoFix && level === '🔴 critical' && !hasSecurityFired) {
|
|
279
|
+
log('');
|
|
280
|
+
log(`🔧 --auto-fix 활성 — session close 자동 실행 중...`);
|
|
281
|
+
try {
|
|
282
|
+
const r = cp.spawnSync(process.execPath, [harnessPath, 'session', 'close', root], { encoding: 'utf8', timeout: 60000, env: { ...process.env, LEERNESS_INTERNAL: '1' } });
|
|
283
|
+
if (r.status === 0) {
|
|
284
|
+
log(`✓ session close 자동 완료`);
|
|
285
|
+
// autoResolved 카운트
|
|
286
|
+
const stats = _readUsageStats(root);
|
|
287
|
+
stats.drift = stats.drift || {};
|
|
288
|
+
stats.drift.autoResolved = (stats.drift.autoResolved || 0) + 1;
|
|
289
|
+
const p = _usageStatsPath(root);
|
|
290
|
+
mkdirp(path.dirname(p));
|
|
291
|
+
writeUtf8(p, JSON.stringify(stats, null, 2) + '\n');
|
|
292
|
+
// 재검사
|
|
293
|
+
log('');
|
|
294
|
+
log(`재검사 중...`);
|
|
295
|
+
return driftCheckCmd(root, opts, deps); // 재귀 1회 (auto-fix 없이)
|
|
296
|
+
} else {
|
|
297
|
+
log(`⚠ session close 실패 (exit ${r.status}) — 수동 실행 필요`);
|
|
298
|
+
}
|
|
299
|
+
} catch (e) {
|
|
300
|
+
log(`⚠ auto-fix 오류: ${e.message}`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (has('--json')) {
|
|
304
|
+
log(JSON.stringify({ root, score: totalScore, level, signals, fired, appsZeroTask }, null, 2));
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
log(`# leerness drift check (1.9.37)`);
|
|
308
|
+
log(`경로: ${root}`);
|
|
309
|
+
log('');
|
|
310
|
+
log(`상태: ${level} · 점수 ${totalScore}/200`);
|
|
311
|
+
log('');
|
|
312
|
+
log(`| 신호 | age | 임계 | 가중치 | 발화 |`);
|
|
313
|
+
log(`|---|---:|---:|---:|---|`);
|
|
314
|
+
for (const s of signals) {
|
|
315
|
+
const fire = s.ageDays > s.threshold ? '🔥' : '✓';
|
|
316
|
+
const age = s.ageDays === null ? '-' : `${s.ageDays.toFixed(1)}d`;
|
|
317
|
+
log(`| ${s.label} | ${age} | ${s.threshold}d | ${s.weight} | ${fire} |`);
|
|
318
|
+
}
|
|
319
|
+
if (appsZeroTask.length) {
|
|
320
|
+
log('');
|
|
321
|
+
log(`task 0건 sub-app (${appsZeroTask.length}개): ${appsZeroTask.join(', ')}`);
|
|
322
|
+
}
|
|
323
|
+
if (totalScore >= 50) {
|
|
324
|
+
log('');
|
|
325
|
+
log(`💡 권장 조치:`);
|
|
326
|
+
log(` - 즉시: leerness session close . (handoff/current-state 갱신)`);
|
|
327
|
+
log(` - 또는: leerness audit . --fix (자동 갱신 가능 항목 적용)`);
|
|
328
|
+
log(` - sub-app에 task 등록: cd _apps/X && leerness task add "..."`);
|
|
329
|
+
log(` - 이 검사 끄기: --no-drift-check 또는 LEERNESS_NO_DRIFT_CHECK=1`);
|
|
330
|
+
}
|
|
331
|
+
if (level === '🔴 critical') process.exitCode = 1;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
module.exports = { driftCheckCmd };
|