leerness 1.9.366 → 1.9.368

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,37 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.9.368 — 2026-06-06 — UR-0025 모듈화: README/managed 머지 + MERGE_OVERWRITE_FILES 분리
4
+
5
+ **🧩 마이그레이션 머지 안전 핵심을 모듈화 — README/관리파일 머지 순수 코어 → pure-utils, overwrite 파일목록 → catalogs.**
6
+
7
+ ### 구현
8
+ 1. **`_mergeReadmeSection(existing, block, START, END)`**(pure-utils): README 관리섹션 마커 사이 교체/append. 마커는 인자 주입(harness 상수 비결합).
9
+ 2. **`_managedMerge(file, next, previous, archiveRel, overwriteSet)`**(pure-utils): 관리 파일 마이그레이션 머지 — 이전 내용을 `<!-- leerness:migration-preserved -->` 블록으로 보존(데이터/인덱스 파일은 overwrite). archiveRel(사전계산)+overwriteSet 주입 → path/process/상수 비결합(순수).
10
+ 3. **`MERGE_OVERWRITE_FILES`** → lib/catalogs (데이터 응집).
11
+ 4. **harness**: `mergeReadmeSection`/`managedMerge` 은 마커/archiveRel/set 만 주입하는 얇은 래퍼.
12
+
13
+ ### 검증 (회귀 0)
14
+ - **selftest 113→114 PASS** (행위: `_mergeReadmeSection('','BLOCK',..)`==='# Project\n\nBLOCK' / `_managedMerge` preserved 블록 생성 / overwrite-set→NEW만 / 동일내용→NEW / 모듈 reference equality).
15
+ - **E2E 313→314 PASS** (행위: init → AGENTS.md 사용자 편집 → migrate → migration-preserved 블록에 편집 보존).
16
+ - 실측: AGENTS.md 편집 후 migrate → marker + preserved 블록 보존. init/migrate/check smoke 정상.
17
+
18
+ ## 1.9.367 — 2026-06-06 — UR-0025 모듈화: env/line 머지 순수 코어 분리
19
+
20
+ **🧩 안정화 마일스톤 이후 모듈화(UR-0025) 재개 — `.env`/라인 머지 순수 코어를 lib/pure-utils 로 분리, harness 는 얇은 I/O 래퍼.**
21
+
22
+ ### 배경
23
+ 외부 리뷰가 지목한 코드 품질(5.8) 개선 방향 = 21k줄 단일 harness.js 모듈화. 비파괴 추출 패턴(데이터→catalogs, 순수 로직→pure-utils, harness 얇은 래퍼) 지속.
24
+
25
+ ### 구현
26
+ 1. **`_mergeLines(currentText, lines)`**(pure-utils): 기존 텍스트에 없는 라인만 append (substring 중복 방지).
27
+ 2. **`_mergeEnvLines(currentText, lines)`**(pure-utils): `.env` key-aware 머지 — 기존 KEY 값 보존(덮어쓰기 X), 신규 KEY/주석만 append. 사용자가 편집한 토큰을 절대 덮어쓰지 않는 핵심 로직.
28
+ 3. **harness `mergeLinesFile`/`mergeEnvFile`**: 순수 코어 + `read`/`writeUtf8` 만 남긴 얇은 I/O 래퍼.
29
+
30
+ ### 검증 (회귀 0)
31
+ - **selftest 112→113 PASS** (행위: `_mergeLines('a\n',['a','b'])==='a\nb\n'` / `_mergeEnvLines('FOO=keep\n',['FOO=new'])==='FOO=keep\n'`(보존) / 신규 KEY append + 모듈 reference equality).
32
+ - **E2E 312→313 PASS** (행위: init → `.env` 토큰 편집 → migrate → 사용자 값 key-aware 보존).
33
+ - 실측: init→토큰편집→migrate→`LEERNESS_NPM_TOKEN` 사용자 값 보존.
34
+
3
35
  ## 1.9.366 — 2026-06-06 — 안정화⑥(완결) 외부리뷰 CV-5: selftest 행위화 + 외부리뷰 7 finding 전량 해소 🎉
4
36
 
5
37
  **🛠 외부 멀티모델 리뷰 안정화 시리즈 최종 6탄 — selftest 동어반복 source-grep 핵심 케이스를 행위 검증으로 전환. CV-1~7 + 4번째 외부평가 전량 해소로 안정화 마일스톤.**
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.366-green)]() [![tests](https://img.shields.io/badge/e2e-312%2F312-success)]() [![selftest](https://img.shields.io/badge/selftest-112-success)]() [![mcp](https://img.shields.io/badge/MCP--tools-83-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.368-green)]() [![tests](https://img.shields.io/badge/e2e-314%2F314-success)]() [![selftest](https://img.shields.io/badge/selftest-114-success)]() [![mcp](https://img.shields.io/badge/MCP--tools-83-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.366 하네스를 사용합니다. AI 에이전트는 작업 전 `leerness handoff`로 컨텍스트를 적재하고, 작업 후 `leerness check`/`leerness audit`/`leerness session close`를 수행해야 합니다.
474
+ 이 프로젝트는 Leerness v1.9.368 하네스를 사용합니다. 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.366는 stdio JSON-RPC MCP server를 내장합니다 — Claude Code · Cursor · Codex CLI 등 외부 AI에 **83개 도구**를 노출:
528
+ Leerness v1.9.368는 stdio JSON-RPC MCP server를 내장합니다 — Claude Code · Cursor · Codex CLI 등 외부 AI에 **83개 도구**를 노출:
529
529
 
530
530
  ```jsonc
531
531
  // 카테고리별
@@ -546,7 +546,7 @@ Leerness v1.9.366는 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.366)** · 매 라운드 GitHub release/태그 생성 · _reports/는 비공개 보존.
549
+ 현재 누적: **70 라운드 (1.9.40 → 1.9.368)** · 매 라운드 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.366: 2026-06-06
587
+ Last synced by Leerness v1.9.368: 2026-06-06
588
588
  <!-- leerness:project-readme:end -->
589
589
 
package/bin/harness.js CHANGED
@@ -7,7 +7,7 @@ const cp = require('child_process');
7
7
  const os = require('os'); // 1.9.178: _publishToNpm 에서 os.tmpdir() 사용 (전역 import)
8
8
  const readline = require('readline');
9
9
  // 1.9.274 (UR-0025 1단계): 순수 유틸 함수 모듈 분리 (require-based, 비파괴). selftest 7종이 동작 검증.
10
- const { _isSecretKey, _isPlaceholderSecret, _looksSecretLike, compareVer, parseHarnessVersion, _classifyCJK, _riskLabel, _detectSystemLang, _parseSlashFromHelp,
10
+ const { _isSecretKey, _isPlaceholderSecret, _looksSecretLike, _mergeLines, _mergeEnvLines, _mergeReadmeSection, _managedMerge, compareVer, parseHarnessVersion, _classifyCJK, _riskLabel, _detectSystemLang, _parseSlashFromHelp,
11
11
  PERMISSION_TIERS, _tierRank, _requiredTier, _policyAllows, _resolveNpmTag, _mcpJsonContent, _newRunRecord,
12
12
  _htmlToText, _extractTitle, _extractLinks,
13
13
  _countDatedBlocks, _extractDecisionBlocks, _classifyIntent,
@@ -26,9 +26,9 @@ const { _isSecretKey, _isPlaceholderSecret, _looksSecretLike, compareVer, parseH
26
26
  // 1.9.304 (UR-0025): 순수 분석/검증 함수 모듈 분리.
27
27
  const { _evidenceQuality, _parseEvidenceStats, _shellGuardAnalyze, _claimFileInGit, _epistemicHonestyCheck } = require('../lib/analyzers');
28
28
  // 1.9.295 (UR-0025 4단계): 정적 데이터 카탈로그 모듈 분리 (비파괴, require-based).
29
- 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, SKILL_CATALOG_PRESETS } = require('../lib/catalogs'); // 1.9.344 (UR-0025): SKILL_CATALOG_PRESETS 분리
29
+ 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, SKILL_CATALOG_PRESETS } = require('../lib/catalogs'); // 1.9.344/368 (UR-0025): SKILL_CATALOG_PRESETS + MERGE_OVERWRITE_FILES 분리
30
30
 
31
- const VERSION = '1.9.366';
31
+ const VERSION = '1.9.368';
32
32
 
33
33
  // 1.9.290 (UR-0037, Codex gpt-5.5 #4 수렴): CLI 전용 부작용은 require 시 실행하지 않는다.
34
34
  // 이전: warning listener 제거 / NODE_OPTIONS 변경 / chcp IIFE 가 top-level 즉시 실행 → require('harness') 시 호스트 프로세스 오염.
@@ -427,11 +427,9 @@ function managedReadmeBlock(project) {
427
427
  ].join('\n');
428
428
  }
429
429
 
430
+ // 1.9.368 (UR-0025): 순수 코어 _mergeReadmeSection (lib/pure-utils) + 마커 주입 래퍼.
430
431
  function mergeReadmeSection(existing, block) {
431
- if (!existing) return `# Project\n\n${block}`;
432
- const s = existing.indexOf(README_START); const e = existing.indexOf(README_END);
433
- if (s >= 0 && e >= s) return existing.slice(0, s).trimEnd() + '\n\n' + block + '\n' + existing.slice(e + README_END.length).trimStart();
434
- return existing.trimEnd() + '\n\n' + block;
432
+ return _mergeReadmeSection(existing, block, README_START, README_END);
435
433
  }
436
434
 
437
435
  function skillLock(skills) {
@@ -738,21 +736,10 @@ function createBackup(root, reason, files, dry = false) {
738
736
  return { archiveDir: ar, candidates, pruned };
739
737
  }
740
738
 
741
- // 1.9.1 P2: 데이터/인덱스 파일은 preserved 블록 없이 overwrite (누적 방지).
742
- const MERGE_OVERWRITE_FILES = new Set([
743
- '.harness/skill-index.md',
744
- '.harness/manifest.json',
745
- '.harness/skills-lock.json',
746
- '.harness/HARNESS_VERSION',
747
- '.harness/LANGUAGE',
748
- '.harness/context-routing.md'
749
- ]);
739
+ // 1.9.1 P2 / 1.9.368 (UR-0025): MERGE_OVERWRITE_FILES lib/catalogs, managedMerge 순수 코어 lib/pure-utils. 얇은 래퍼.
750
740
  function managedMerge(file, next, previous, archiveDir) {
751
- if (!previous || previous.trim() === next.trim()) return next;
752
- const tag = '<!-- leerness:migration-preserved -->';
753
- if (previous.includes(tag)) return next;
754
- if (MERGE_OVERWRITE_FILES.has(file.replace(/\\/g, '/'))) return next;
755
- return next.trimEnd() + `\n\n---\n${tag}\n## Preserved previous content\n\nPrevious content was backed up before migration. Archive reference:\n\n\`${archiveDir ? path.relative(process.cwd(), archiveDir).replace(/\\/g, '/') : '.harness/archive'}\`\n\n<details>\n<summary>Previous ${file}</summary>\n\n\`\`\`md\n${previous.replace(/```/g, '\\`\\`\\`')}\n\`\`\`\n\n</details>\n`;
741
+ const archiveRel = archiveDir ? path.relative(process.cwd(), archiveDir).replace(/\\/g, '/') : '.harness/archive';
742
+ return _managedMerge(file, next, previous, archiveRel, MERGE_OVERWRITE_FILES);
756
743
  }
757
744
 
758
745
  function writeIfSafe(root, file, content, opts = {}) {
@@ -768,36 +755,17 @@ function writeIfSafe(root, file, content, opts = {}) {
768
755
  return { action: already ? 'updated' : 'created', file };
769
756
  }
770
757
 
758
+ // 1.9.367 (UR-0025): 순수 코어 _mergeLines (lib/pure-utils) + 얇은 I/O 래퍼.
771
759
  function mergeLinesFile(p, lines) {
772
760
  const current = exists(p) ? read(p) : '';
773
- let next = current;
774
- for (const line of lines) if (!next.includes(line)) next += (next.endsWith('\n') || !next ? '' : '\n') + line + '\n';
775
- writeUtf8(p, next);
761
+ writeUtf8(p, _mergeLines(current, lines));
776
762
  }
777
763
 
778
- // 1.9.153: env 파일 전용 key-aware merge — KEY=VALUE 줄을 기준 처리 (기존 보존, 키만 추가)
764
+ // 1.9.153/1.9.367: env 파일 전용 key-aware merge — 기존 보존(덮어쓰기 X). 순수 코어 _mergeEnvLines (lib/pure-utils) + 얇은 I/O 래퍼.
779
765
  // 사용자가 .env 의 LEERNESS_NPM_TOKEN=abc123 처럼 직접 편집한 값을 절대 덮어쓰지 않음.
780
- // 주석 / 빈 줄은 substring includes 로 중복 방지 (mergeLinesFile 와 동일).
781
766
  function mergeEnvFile(p, lines) {
782
767
  const current = exists(p) ? read(p) : '';
783
- const existingKeys = new Set();
784
- for (const ln of current.split(/\r?\n/)) {
785
- const m = ln.match(/^\s*([A-Z][A-Z0-9_]+)\s*=/);
786
- if (m) existingKeys.add(m[1]);
787
- }
788
- let next = current;
789
- for (const line of lines) {
790
- const km = line.match(/^\s*([A-Z][A-Z0-9_]+)\s*=/);
791
- if (km) {
792
- if (existingKeys.has(km[1])) continue; // 기존 키 값 보존 (덮어쓰기 X)
793
- next += (next.endsWith('\n') || !next ? '' : '\n') + line + '\n';
794
- existingKeys.add(km[1]);
795
- } else {
796
- // 주석 또는 빈 줄 — substring 미포함 시만 append
797
- if (!next.includes(line)) next += (next.endsWith('\n') || !next ? '' : '\n') + line + '\n';
798
- }
799
- }
800
- writeUtf8(p, next);
768
+ writeUtf8(p, _mergeEnvLines(current, lines));
801
769
  }
802
770
 
803
771
  function writeMigrationReport(root, backup, actions, opts = {}) {
@@ -3099,6 +3067,8 @@ function _selfTestCases() {
3099
3067
  { name: 'CV-7/UR-0082: commands 카탈로그 + help 에 누락 명령군 등재 (표면 drift 가드)', run: () => { const src = read(__filename); const ci = src.indexOf('function commandsCmd'); const hi = src.indexOf('function help('); if (ci < 0 || hi < 0) return false; const cbody = src.slice(ci, ci + 8000); const hbody = src.slice(hi, hi + 7000); const must = ['install-safety', 'feature add', 'creds list', 'incident list', 'webhook serve', 'deploy auto', 'runs list', 'permissions list', 'whats-new', 'migrate audit']; return must.every(c => cbody.includes(c)) && hbody.includes('install-safety') && hbody.includes('feature add'); } },
3100
3068
  { name: 'UR-0083(4th외부평가 9.3): auto-update hook 비침투 (update --quiet 모드 + hook --check --quiet + 업그레이드)', run: () => { const src = read(__filename); const quietMode = /const quiet = !!opts\.quiet \|\| has\('--quiet'\)/.test(src); const hookQuiet = src.includes("command: 'leerness update --check --quiet'"); const upgrade = /includes\('leerness update --check'\) && !h\.command\.includes\('--quiet'\)/.test(src); return quietMode && hookQuiet && upgrade; } },
3101
3069
  { name: 'CV-6/UR-0081: 시크릿 스캐너 FP/FN — _isPlaceholderSecret + _looksSecretLike 행위', run: () => { if (typeof _isPlaceholderSecret !== 'function' || typeof _looksSecretLike !== 'function') return false; const fp = _isPlaceholderSecret('change-me') && _isPlaceholderSecret('your-api-key-here') && _isPlaceholderSecret('<token>') && _isPlaceholderSecret('') && !_isPlaceholderSecret('hunter2realpass'); const fn = _looksSecretLike('secret123') && _looksSecretLike('a'.repeat(24)) && !_looksSecretLike('processEnv') && !_looksSecretLike('reqBodyPassword'); return fp && fn; } },
3070
+ { name: 'UR-0025: _mergeLines/_mergeEnvLines 순수 코어 모듈 분리 + 행위 (1.9.367)', run: () => { if (typeof _mergeLines !== 'function' || typeof _mergeEnvLines !== 'function') return false; const m = require('../lib/pure-utils'); const moved = m._mergeLines === _mergeLines && m._mergeEnvLines === _mergeEnvLines; const ml = _mergeLines('a\n', ['a', 'b']) === 'a\nb\n'; const meKeep = _mergeEnvLines('FOO=keep\n', ['FOO=new']) === 'FOO=keep\n'; const meAdd = _mergeEnvLines('FOO=keep\n', ['BAR=add']).includes('BAR=add'); return moved && ml && meKeep && meAdd; } },
3071
+ { name: 'UR-0025: _mergeReadmeSection/_managedMerge + MERGE_OVERWRITE_FILES 모듈 분리 + 행위 (1.9.368)', run: () => { const m = require('../lib/pure-utils'); const c = require('../lib/catalogs'); if (typeof _mergeReadmeSection !== 'function' || typeof _managedMerge !== 'function') return false; const moved = m._mergeReadmeSection === _mergeReadmeSection && m._managedMerge === _managedMerge && MERGE_OVERWRITE_FILES === c.MERGE_OVERWRITE_FILES; const rd = _mergeReadmeSection('', 'BLOCK', '<s>', '<e>') === '# Project\n\nBLOCK'; const mm = _managedMerge('a.md', 'NEW', 'OLD', '.h', new Set()).includes('migration-preserved'); const ow = _managedMerge('.harness/manifest.json', 'NEW', 'OLD', '.h', c.MERGE_OVERWRITE_FILES) === 'NEW'; const same = _managedMerge('a.md', 'X', 'X', '.h', new Set()) === 'X'; return moved && rd && mm && ow && same; } },
3102
3072
  { name: 'VERSION 형식 (x.y.z)', run: () => /^\d+\.\d+\.\d+$/.test(VERSION) }
3103
3073
  ];
3104
3074
  }
package/lib/catalogs.js CHANGED
@@ -388,6 +388,16 @@ const SECRET_PATTERNS = [
388
388
  { name: 'Hardcoded Bearer token', re: /\bBearer\s+[A-Za-z0-9_\-.=]{20,}/g },
389
389
  ];
390
390
 
391
+ // 1.9.367/1.9.368 (UR-0025): 데이터/인덱스 파일은 migration-preserved 블록 없이 overwrite (누적 방지) — harness 에서 분리.
392
+ const MERGE_OVERWRITE_FILES = new Set([
393
+ '.harness/skill-index.md',
394
+ '.harness/manifest.json',
395
+ '.harness/skills-lock.json',
396
+ '.harness/HARNESS_VERSION',
397
+ '.harness/LANGUAGE',
398
+ '.harness/context-routing.md'
399
+ ]);
400
+
391
401
  // 1.9.344 (UR-0025 심층): skill discover GitHub preset catalog (vercel/anthropic) — harness 에서 분리.
392
402
  const SKILL_CATALOG_PRESETS = {
393
403
  'vercel': { owner: 'vercel-labs', repo: 'agent-skills', branch: 'main', path: 'skills',
@@ -396,4 +406,4 @@ const SKILL_CATALOG_PRESETS = {
396
406
  homepage: 'https://github.com/anthropics/skills' }
397
407
  };
398
408
 
399
- module.exports = { 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, SKILL_CATALOG_PRESETS };
409
+ module.exports = { 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, SKILL_CATALOG_PRESETS };
package/lib/pure-utils.js CHANGED
@@ -635,9 +635,48 @@ function _looksSecretLike(value) {
635
635
  return (/\d/.test(v) && v.length >= 8) || v.length >= 24;
636
636
  }
637
637
 
638
+ // 1.9.367 (UR-0025): 라인 머지 순수 코어 — 기존 텍스트에 없는 라인만 append (substring 중복 방지). mergeLinesFile 의 I/O 분리.
639
+ function _mergeLines(currentText, lines) {
640
+ let next = currentText || '';
641
+ for (const line of (lines || [])) if (!next.includes(line)) next += (next.endsWith('\n') || !next ? '' : '\n') + line + '\n';
642
+ return next;
643
+ }
644
+ // 1.9.367 (UR-0025): .env key-aware 머지 순수 코어 — 기존 KEY 값 보존(덮어쓰기 X), 신규 KEY/주석만 append. mergeEnvFile 의 I/O 분리.
645
+ function _mergeEnvLines(currentText, lines) {
646
+ const current = currentText || '';
647
+ const existingKeys = new Set();
648
+ for (const ln of current.split(/\r?\n/)) { const m = ln.match(/^\s*([A-Z][A-Z0-9_]+)\s*=/); if (m) existingKeys.add(m[1]); }
649
+ let next = current;
650
+ for (const line of (lines || [])) {
651
+ const km = line.match(/^\s*([A-Z][A-Z0-9_]+)\s*=/);
652
+ if (km) { if (existingKeys.has(km[1])) continue; next += (next.endsWith('\n') || !next ? '' : '\n') + line + '\n'; existingKeys.add(km[1]); }
653
+ else { if (!next.includes(line)) next += (next.endsWith('\n') || !next ? '' : '\n') + line + '\n'; }
654
+ }
655
+ return next;
656
+ }
657
+
658
+ // 1.9.368 (UR-0025): README 관리섹션 머지 순수 코어 — 마커 사이 교체, 없으면 append. 마커는 인자로 주입(harness 상수 비결합).
659
+ function _mergeReadmeSection(existing, block, START, END) {
660
+ if (!existing) return `# Project\n\n${block}`;
661
+ const s = existing.indexOf(START); const e = existing.indexOf(END);
662
+ if (s >= 0 && e >= s) return existing.slice(0, s).trimEnd() + '\n\n' + block + '\n' + existing.slice(e + END.length).trimStart();
663
+ return existing.trimEnd() + '\n\n' + block;
664
+ }
665
+ // 1.9.368 (UR-0025): 관리 파일 마이그레이션 머지 순수 코어 — 이전 내용을 migration-preserved 블록으로 보존(데이터/인덱스 파일은 overwrite).
666
+ // archiveRel(사전 계산된 표시 경로) + overwriteSet 을 인자로 주입 → path/process/상수 비결합(순수).
667
+ function _managedMerge(file, next, previous, archiveRel, overwriteSet) {
668
+ if (!previous || previous.trim() === next.trim()) return next;
669
+ const tag = '<!-- leerness:migration-preserved -->';
670
+ if (previous.includes(tag)) return next;
671
+ if (overwriteSet && overwriteSet.has(String(file).replace(/\\/g, '/'))) return next;
672
+ const ar = archiveRel || '.harness/archive';
673
+ return next.trimEnd() + `\n\n---\n${tag}\n## Preserved previous content\n\nPrevious content was backed up before migration. Archive reference:\n\n\`${ar}\`\n\n<details>\n<summary>Previous ${file}</summary>\n\n\`\`\`md\n${previous.replace(/```/g, '\\`\\`\\`')}\n\`\`\`\n\n</details>\n`;
674
+ }
675
+
638
676
  module.exports = {
639
677
  _isSecretKey, compareVer, parseHarnessVersion,
640
678
  _isPlaceholderSecret, _looksSecretLike,
679
+ _mergeLines, _mergeEnvLines, _mergeReadmeSection, _managedMerge,
641
680
  _classifyCJK, _riskLabel, _detectSystemLang, _parseSlashFromHelp,
642
681
  // 1.9.283 (UR-0025 2단계)
643
682
  PERMISSION_TIERS, _tierRank, _requiredTier, _policyAllows, _resolveNpmTag, _mcpJsonContent, _newRunRecord,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "leerness",
3
- "version": "1.9.366",
3
+ "version": "1.9.368",
4
4
  "description": "Leerness: 비파괴 마이그레이션, 자동 버전 감지·업데이트, 계획/진행/핸드오프 자동화, 게으름·시크릿·인코딩 자동 가드, Claude Code 슬래시 통합을 갖춘 한국어 우선 AI 개발 하네스.",
5
5
  "keywords": [
6
6
  "leerness",
package/scripts/e2e.js CHANGED
@@ -5017,5 +5017,41 @@ total++;
5017
5017
  if (!ok) failed++;
5018
5018
  }
5019
5019
 
5020
+ // 1.9.367 회귀 (UR-0025): _mergeEnvLines 모듈 분리 — migrate 가 사용자 .env 값을 key-aware 로 보존 (덮어쓰기 X)
5021
+ total++;
5022
+ {
5023
+ let ok = false;
5024
+ try {
5025
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'leerness-envm-'));
5026
+ cp.spawnSync(process.execPath, [CLI, 'init', d, '--yes', '--language', 'ko'], { encoding: 'utf8', timeout: 30000 });
5027
+ const envPath = path.join(d, '.env');
5028
+ fs.writeFileSync(envPath, fs.readFileSync(envPath, 'utf8').replace('LEERNESS_NPM_TOKEN=', 'LEERNESS_NPM_TOKEN=user_kept_value_777'));
5029
+ cp.spawnSync(process.execPath, [CLI, 'migrate', d], { encoding: 'utf8', timeout: 30000 });
5030
+ const after = fs.readFileSync(envPath, 'utf8');
5031
+ fs.rmSync(d, { recursive: true, force: true });
5032
+ ok = after.includes('LEERNESS_NPM_TOKEN=user_kept_value_777');
5033
+ } catch {}
5034
+ console.log(ok ? '✓ B(1.9.367) UR-0025: _mergeEnvLines 분리 — migrate 가 사용자 .env 값 key-aware 보존' : '✗ env merge 보존 실패');
5035
+ if (!ok) failed++;
5036
+ }
5037
+
5038
+ // 1.9.368 회귀 (UR-0025): _managedMerge 모듈 분리 — migrate 가 사용자 편집(AGENTS.md)을 migration-preserved 블록으로 보존
5039
+ total++;
5040
+ {
5041
+ let ok = false;
5042
+ try {
5043
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'leerness-mm-'));
5044
+ cp.spawnSync(process.execPath, [CLI, 'init', d, '--yes', '--language', 'ko'], { encoding: 'utf8', timeout: 30000 });
5045
+ const agents = path.join(d, 'AGENTS.md');
5046
+ fs.writeFileSync(agents, fs.readFileSync(agents, 'utf8') + '\nCUSTOM_USER_EDIT_MARKER_42\n');
5047
+ cp.spawnSync(process.execPath, [CLI, 'migrate', d], { encoding: 'utf8', timeout: 30000 });
5048
+ const after = fs.readFileSync(agents, 'utf8');
5049
+ fs.rmSync(d, { recursive: true, force: true });
5050
+ ok = after.includes('CUSTOM_USER_EDIT_MARKER_42') && after.includes('migration-preserved');
5051
+ } catch {}
5052
+ console.log(ok ? '✓ B(1.9.368) UR-0025: _managedMerge 분리 — migrate 가 사용자 편집 preserved 블록 보존' : '✗ managedMerge 보존 실패');
5053
+ if (!ok) failed++;
5054
+ }
5055
+
5020
5056
  console.log(`\nE2E result: ${total - failed}/${total} passed · ${((Date.now() - _e2eStart) / 1000).toFixed(0)}s`);
5021
5057
  if (failed > 0) process.exit(1);