leerness 1.36.167 → 1.36.169

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,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.36.169 — 2026-08-27
4
+
5
+ - 멀티세션 lost-update 방지: plan/anchors canonical lock, decisions·lessons migration transaction, rule baseline verification serialization, 11-pair forced-interleaving regressions
6
+ - 외부 Codex 교차 검수에서 재현한 자동 next-action 오류를 수정했습니다. decision/plan 제안은 실제 지원 명령만 안내하고, 일반 적용 프로젝트에 없는 `scripts/e2e.js` 대신 `leerness verify-code .`를 사용하며, 아직 생성되지 않은 stress 파일 실행을 제거합니다.
7
+ - next-action에 시간·버전과 무관한 안정 키를 도입해 stress 버전 및 progress 경과시간 중복을 하나로 갱신합니다. 업그레이드 직후 list/take도 legacy 큐를 즉시 정규화하고, take의 선택·정규화·제거를 한 잠금 트랜잭션으로 묶어 동시 handoff가 제목을 바꿔도 task와 큐 상태가 갈라지지 않게 했습니다.
8
+
9
+ ## 1.36.168 — 2026-08-26
10
+
11
+ - Windows which가 동일 npm 설치의 extensionless/.cmd/.ps1 shim을 실제 package bin target과 npm 실행문까지 검증한 뒤 한 설치로 그룹화하고, pathCandidates 원문은 유지한 채 pathInstallations를 추가해 PATH 충돌 오탐을 제거. 독립 검토에서 잡힌 주석·더미 인자 우회까지 막아 변조·미증명·다른 디렉터리·비표준 .bat·POSIX 후보를 보수적으로 분리하며 15개 회귀 프로브와 제품 배선 가드 추가.
12
+
3
13
  ## 1.36.167 — 2026-08-26
4
14
 
5
15
  - T-0145: 장기 운영 프로젝트의 레거시 완료 증거를 소급 수정하지 않고 명시적 tracker 경계 이전의 현재 실패만 exact 행+사유 SHA-256 지문으로 격리하는 claims baseline을 추가했습니다. verify-claim --all과 gate --claims는 원판정 실패·baseline 부채·현재 차단 및 진단 상세를 분리해 보고하고, --raw/개별 검증은 원판정을 유지합니다. 행 변경·신규 실패·경계 밖 항목·손상 baseline은 fail-closed하며, 생성 명령은 기존 baseline을 덮어쓰지 않아 변경 행의 재승인을 차단합니다. CLI·MCP·클린룸 프로브로 검증합니다.
package/README.md CHANGED
@@ -138,7 +138,7 @@ MIT
138
138
  <!-- leerness:project-readme:start -->
139
139
  ## Leerness Project Harness
140
140
 
141
- 이 프로젝트는 Leerness v1.36.167 하네스를 사용합니다. AI 에이전트는 작업 전 `leerness handoff`로 컨텍스트를 적재하고, 작업 후 `leerness check`/`leerness audit`/`leerness session close`를 수행해야 합니다.
141
+ 이 프로젝트는 Leerness v1.36.169 하네스를 사용합니다. AI 에이전트는 작업 전 `leerness handoff`로 컨텍스트를 적재하고, 작업 후 `leerness check`/`leerness audit`/`leerness session close`를 수행해야 합니다.
142
142
 
143
143
  ### 정체성 — AI 에이전트 운영 레이어 (UR-0030)
144
144
 
@@ -192,7 +192,7 @@ leerness memory restore decision <date|title>
192
192
 
193
193
  ### MCP server (외부 AI 통합)
194
194
 
195
- Leerness v1.36.167는 stdio JSON-RPC MCP server를 내장합니다 — Claude Code · Cursor · Codex CLI 등 외부 AI에 **89개 도구**를 노출:
195
+ Leerness v1.36.169는 stdio JSON-RPC MCP server를 내장합니다 — Claude Code · Cursor · Codex CLI 등 외부 AI에 **89개 도구**를 노출:
196
196
 
197
197
  ```jsonc
198
198
  // 카테고리별
@@ -213,7 +213,7 @@ Leerness v1.36.167는 stdio JSON-RPC MCP server를 내장합니다 — Claude Co
213
213
  `<<autonomous-loop-dynamic>>` 신호만 보내면 AI가:
214
214
  1) 다음 라운드 후보 선정 → 2) 코드 변경 → 3) 회귀 테스트 갱신 → 4) 전체 e2e 스위트 통과 → 5) npm publish + git tag → 6) main push → 7) session close → 8) 다음 라운드 예약.
215
215
 
216
- 현재 누적: **v1.9.x → 1.36.167 릴리스 태그 이력** (수백 라운드) · _reports/는 비공개 보존.
216
+ 현재 누적: **v1.9.x → 1.36.169 릴리스 태그 이력** (수백 라운드) · _reports/는 비공개 보존.
217
217
 
218
218
  ### 성능 가이드
219
219
 
@@ -251,5 +251,5 @@ leerness release pack --close --auto-main-push
251
251
  - `.leerness/session-handoff.md`: 다음 세션 인수인계 (자동 작성)
252
252
  - `.leerness/lessons.md` / `decisions.md` / `rules.md`: 영구 메모리 (5 surface)
253
253
 
254
- Last synced by Leerness v1.36.167: 2026-08-26
254
+ Last synced by Leerness v1.36.169: 2026-08-27
255
255
  <!-- leerness:project-readme:end -->
package/bin/leerness.js CHANGED
@@ -48,7 +48,7 @@ const {
48
48
  migrateLegacyWorkspace,
49
49
  } = require('../lib/workspace-dir');
50
50
 
51
- const VERSION = '1.36.167';
51
+ const VERSION = '1.36.169';
52
52
 
53
53
  // 1.9.290 (UR-0037, Codex gpt-5.5 #4 수렴): CLI 전용 부작용은 require 시 실행하지 않는다.
54
54
  // 이전: warning listener 제거 / NODE_OPTIONS 변경 / chcp IIFE 가 top-level 즉시 실행 → require('harness') 시 호스트 프로세스 오염.
@@ -4384,9 +4384,26 @@ function _selfTestCases() {
4384
4384
  // 1.36.47: 어색 조사 병기 소거 + 장문은 단어 경계 절단(…) — 실적용에서 발견된 품질 결함 회귀 방지
4385
4385
  const dLong = p._draftAnchors({ pkgDescription: '가나다 라마바사 아자차카 타파하 '.repeat(20) });
4386
4386
  const phraseOk = !dLong.goal.join('').includes('를(을)') && dLong.goal.some(l => l.includes('…')) && !/[가-힣]{2}…[가-힣]/.test(dLong.goal.join(''));
4387
- // 재초안: draft 마커 잔존 섹션은 gap 취급 (배선 소스가드)
4388
- const s47 = read(__filename);
4389
- const redraftOk = s47.includes("_mdSectionBody(briefTxt, 'Purpose') || '').includes(_draftM)");
4387
+ // 재초안: draft 마커 잔존 섹션은 gap 취급 — 실제 CLI 핸들러가 두 파일을 교체하는지 검증한다.
4388
+ const redraw = fs.mkdtempSync(path.join(os.tmpdir(), '__leerness_anchor_redraft_'));
4389
+ let redraftOk = false;
4390
+ const savedArgv = process.argv, savedWrite = process.stdout.write;
4391
+ try {
4392
+ mkdirp(path.join(redraw, '.leerness'));
4393
+ writeUtf8(path.join(redraw, 'package.json'), JSON.stringify({ name: 'probe', version: '1.0.0', description: '새 정체성 신호' }));
4394
+ writeUtf8(path.join(redraw, '.leerness', 'project-brief.md'), '# Brief\n\n## Purpose\n<!-- draft: leerness anchors old -->\n- OLD_PURPOSE_SENTINEL\n');
4395
+ writeUtf8(path.join(redraw, '.leerness', 'plan.md'), '# Plan\n\n## Goal\n<!-- draft: leerness anchors old -->\n- OLD_GOAL_SENTINEL\n');
4396
+ process.argv = ['node', 'leerness', 'anchors', 'draft', '--apply'];
4397
+ process.stdout.write = () => true;
4398
+ anchorsCmd(redraw, 'draft');
4399
+ const rb = read(path.join(redraw, '.leerness', 'project-brief.md'));
4400
+ const rp = read(path.join(redraw, '.leerness', 'plan.md'));
4401
+ redraftOk = !rb.includes('OLD_PURPOSE_SENTINEL') && !rp.includes('OLD_GOAL_SENTINEL')
4402
+ && rb.includes('새 정체성 신호') && rp.includes('새 정체성 신호');
4403
+ } catch {} finally {
4404
+ process.argv = savedArgv; process.stdout.write = savedWrite;
4405
+ try { fs.rmSync(redraw, { recursive: true, force: true }); } catch {}
4406
+ }
4390
4407
  if (!(phraseOk && redraftOk)) return false;
4391
4408
  // 무신호 시 발명 금지
4392
4409
  const empty = p._draftAnchors({});
@@ -4401,6 +4418,60 @@ function _selfTestCases() {
4401
4418
  const wired = typeof anchorsCmd === 'function' && s.includes("cmd === 'anchors'") && s.includes('→ leerness anchors draft');
4402
4419
  return draftOk && noInvent && secOk && noSec && wired;
4403
4420
  } },
4421
+ { name: 'next-action 자동 제안 실행 가능성 (1.36.169/Codex P2): 일반 프로젝트 명령 + stable-key 마이그레이션/중복 갱신', run: () => {
4422
+ const arena = fs.mkdtempSync(path.join(os.tmpdir(), '__leerness_next_action_'));
4423
+ const root = path.join(arena, 'project');
4424
+ try {
4425
+ const hd = path.join(root, '.leerness');
4426
+ const stressDir = path.join(arena, '_apps', 'leerness-stress', 'bin');
4427
+ mkdirp(hd); mkdirp(stressDir);
4428
+ writeUtf8(path.join(hd, 'plan.md'), '# Plan\n\n### M-0001. install release\nStatus: planned\n');
4429
+ writeUtf8(path.join(hd, 'decisions.md'), '# Decisions\n\n### 2026-08-27 — install policy\n- Reason: probe\n');
4430
+ writeUtf8(path.join(hd, 'review-evidence.md'), 'verified\n'.repeat(20));
4431
+ const stressFile = path.join(stressDir, 'stress-v211.js');
4432
+ writeUtf8(stressFile, '// existing baseline\n');
4433
+ const old = new Date(Date.now() - 48 * 3600000); fs.utimesSync(stressFile, old, old);
4434
+
4435
+ const actions = _suggestNextActions(root, { id: 'T-0001', request: 'install 기능 보강' }, 'install');
4436
+ const plan = actions.find(a => a.icon === '🎯');
4437
+ const decision = actions.find(a => a.icon === '💭');
4438
+ const stress = actions.find(a => a.icon === '🧬');
4439
+ const generatedOk = plan?.command === 'leerness plan list --path .'
4440
+ && decision?.command === 'leerness decision list --query "install"'
4441
+ && stress?.title === 'stress-v211 오래됨 — 새 stress test 작성 권장'
4442
+ && !Object.prototype.hasOwnProperty.call(stress, 'command')
4443
+ && plan?.actionKey === 'plan:M-0001' && decision?.actionKey === 'decision:install'
4444
+ && stress?.actionKey === 'stress-refresh';
4445
+
4446
+ const legacy = [
4447
+ { icon: '🧬', title: 'stress-v210 마지막 갱신 46h 전 — 새 stress test 작성 권장', command: 'node _apps/leerness-stress/bin/stress-v211.js' },
4448
+ { icon: '🧬', title: 'stress-v211 마지막 갱신 48h 전 — 새 stress test 작성 권장', command: 'node _apps/leerness-stress/bin/stress-v212.js' },
4449
+ { icon: '🎯', title: plan.title, command: 'leerness plan list --filter "install"' },
4450
+ { icon: '💭', title: decision.title, command: 'leerness decision list --filter "install"' },
4451
+ { icon: '🧪', title: 'review-evidence.md 비어있음 — e2e 또는 verify-code 실행', command: 'node ./scripts/e2e.js' },
4452
+ { icon: '🔄', title: 'progress-tracker 24h 정체 — task T-0001 status 갱신', command: 'leerness task update T-0001 --status completed' },
4453
+ { icon: '🔄', title: 'progress-tracker 25h 정체 — task T-0001 status 갱신', command: 'leerness task update T-0001 --status completed' }
4454
+ ];
4455
+ writeUtf8(_nextActionQueuePath(root), JSON.stringify({ queue: legacy, at: new Date().toISOString() }, null, 2));
4456
+ _enqueueNextActions(root, []); // 새 제안이 없는 handoff도 legacy 큐를 고쳐야 한다.
4457
+ _enqueueNextActions(root, [{ actionKey: 'stress-refresh', icon: '🧬', title: 'stress-v212 오래됨 — 새 stress test 작성 권장' }]);
4458
+ const migrated = JSON.parse(read(_nextActionQueuePath(root))).queue;
4459
+ const migratedStress = migrated.filter(a => a.icon === '🧬');
4460
+ const migratedPlan = migrated.find(a => a.icon === '🎯');
4461
+ const migratedDecision = migrated.find(a => a.icon === '💭');
4462
+ const migratedEvidence = migrated.find(a => a.icon === '🧪');
4463
+ const migratedProgress = migrated.find(a => a.icon === '🔄');
4464
+ return generatedOk && migrated.length === 5 && migratedStress.length === 1
4465
+ && migratedStress[0].title === 'stress-v212 오래됨 — 새 stress test 작성 권장'
4466
+ && !Object.prototype.hasOwnProperty.call(migratedStress[0], 'command')
4467
+ && migratedPlan.command === plan.command && migratedDecision.command === decision.command
4468
+ && migratedEvidence.command === 'leerness verify-code .'
4469
+ && migratedProgress.title === 'progress-tracker 정체 — task T-0001 상태 검토'
4470
+ && migratedProgress.command === 'leerness task list --path .'
4471
+ && migrated.every(a => typeof a.actionKey === 'string' && a.actionKey.length > 0);
4472
+ } catch { return false; }
4473
+ finally { try { fs.rmSync(arena, { recursive: true, force: true }); } catch {} }
4474
+ } },
4404
4475
  { name: 'managed 파일 force 병합 (1.36.37, 1.9.441 드리프트 실측): writeIfSafe 가 --force 여도 managed 는 라인-diff 병합 — CLAUDE 커스텀 보존 (행위검사)', run: () => {
4405
4476
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), '__leerness_wif_'));
4406
4477
  let ok1 = false, ok2 = false, ok3 = false;
@@ -8393,8 +8464,10 @@ function anchorsCmd(root, sub) {
8393
8464
  const _draftM = '<!-- draft: leerness anchors';
8394
8465
  // 1.36.49 (codex 6차 #4): 헤딩 자체가 없는 파일도 gap — 종전 _sectionUnfilled 는 "섹션 없음→미플래그"(감지용 보수 기본)라
8395
8466
  // ## Goal 이 아예 없는 plan.md 가 "작성됨"으로 보고되고 draft --apply 도 무동작이었다. apply 시 헤딩을 신설한다.
8396
- const briefGap = !!briefTxt && !briefTxt.includes(naM) && (_briefUnfilled(briefTxt) || _mdSectionBody(briefTxt, 'Purpose') == null || (_mdSectionBody(briefTxt, 'Purpose') || '').includes(_draftM));
8397
- const planGap = !!planTxt && !planTxt.includes(naM) && (_planGoalUnfilled(planTxt) || _mdSectionBody(planTxt, 'Goal') == null || (_mdSectionBody(planTxt, 'Goal') || '').includes(_draftM));
8467
+ const _briefHasGap = txt => !!txt && !txt.includes(naM) && (_briefUnfilled(txt) || _mdSectionBody(txt, 'Purpose') == null || (_mdSectionBody(txt, 'Purpose') || '').includes(_draftM));
8468
+ const _planHasGap = txt => !!txt && !txt.includes(naM) && (_planGoalUnfilled(txt) || _mdSectionBody(txt, 'Goal') == null || (_mdSectionBody(txt, 'Goal') || '').includes(_draftM));
8469
+ const briefGap = _briefHasGap(briefTxt);
8470
+ const planGap = _planHasGap(planTxt);
8398
8471
  if (!sub || sub === 'status') {
8399
8472
  if (json) { log(JSON.stringify({ briefUnfilled: briefGap, planGoalUnfilled: planGap }, null, 2)); return; }
8400
8473
  log(`# leerness anchors — 정체성앵커 상태`);
@@ -8416,16 +8489,31 @@ function anchorsCmd(root, sub) {
8416
8489
  const apply = has('--apply');
8417
8490
  const applied = [];
8418
8491
  if (briefGap && draft.purpose.length) {
8419
- if (apply) { writeUtf8(bf, _replaceMdSection(briefTxt, 'Purpose', draft.purpose, { appendIfMissing: true })); applied.push('project-brief.md#Purpose'); }
8492
+ if (apply) {
8493
+ // 1.36.169 (T-0108): 초안 계산 뒤 다른 세션이 채운 내용을 낡은 snapshot으로 덮지 않는다.
8494
+ _withLock(bf, () => {
8495
+ const current = exists(bf) ? read(bf) : '';
8496
+ if (!_briefHasGap(current)) return;
8497
+ writeUtf8(bf, _replaceMdSection(current, 'Purpose', draft.purpose, { appendIfMissing: true }));
8498
+ applied.push('project-brief.md#Purpose');
8499
+ });
8500
+ }
8420
8501
  }
8421
8502
  if (planGap && draft.goal.length) {
8422
- if (apply) { writeUtf8(pf, _replaceMdSection(planTxt, 'Goal', draft.goal, { appendIfMissing: true })); applied.push('plan.md#Goal'); }
8503
+ if (apply) {
8504
+ _withPlanLock(root, () => {
8505
+ const current = exists(pf) ? read(pf) : '';
8506
+ if (!_planHasGap(current)) return;
8507
+ writeUtf8(pf, _replaceMdSection(current, 'Goal', draft.goal, { appendIfMissing: true }));
8508
+ applied.push('plan.md#Goal');
8509
+ });
8510
+ }
8423
8511
  }
8424
8512
  if (json) { log(JSON.stringify({ briefUnfilled: briefGap, planGoalUnfilled: planGap, draft: { purpose: draft.purpose, goal: draft.goal }, applied, dryRun: !apply }, null, 2)); return; }
8425
8513
  log(`# leerness anchors draft ${apply ? '(적용)' : '(dry-run — 적용: --apply)'}`);
8426
- if (briefGap) { log(`\n## project-brief Purpose ${apply ? '← 적용됨' : '초안'}`); draft.purpose.forEach(l => log(' ' + l)); }
8514
+ if (briefGap) { log(`\n## project-brief Purpose ${apply ? (applied.includes('project-brief.md#Purpose') ? '← 적용됨' : '← 다른 세션 변경 감지로 건드리지 않음') : '초안'}`); draft.purpose.forEach(l => log(' ' + l)); }
8427
8515
  else log(`\n ✓ project-brief Purpose 는 이미 작성됨 — 건드리지 않음`);
8428
- if (planGap) { log(`\n## plan Goal ${apply ? '← 적용됨' : '초안'}`); draft.goal.forEach(l => log(' ' + l)); }
8516
+ if (planGap) { log(`\n## plan Goal ${apply ? (applied.includes('plan.md#Goal') ? '← 적용됨' : '← 다른 세션 변경 감지로 건드리지 않음') : '초안'}`); draft.goal.forEach(l => log(' ' + l)); }
8429
8517
  else log(` ✓ plan Goal 은 이미 작성됨 — 건드리지 않음`);
8430
8518
  if (apply && applied.length) log(`\n✓ 적용: ${applied.join(', ')} (초안 표식 주석 포함 — 검토 후 주석 제거로 확정)`);
8431
8519
  return;
@@ -13686,24 +13774,102 @@ function _writeNextActionQueue(root, queue) {
13686
13774
  return false;
13687
13775
  }
13688
13776
  }
13689
- // handoff 에서 제안된 next-action 들을 큐에 자동 저장 (중복 방지: 이미 있는 title 은 skip)
13777
+ // handoff 에서 제안된 next-action 들을 큐에 자동 저장 (중복 방지: 안정된 actionKey 는 갱신)
13690
13778
  // 1.36.108 (T-0097): 읽기~쓰기를 락으로 직렬화. 이 큐는 handoff 가 자동으로도 채우기 때문에
13691
13779
  // 사용자가 `next-action add` 하는 순간 handoff 가 겹칠 수 있다 — 실사용에서 가장 겹치기 쉬운 조합이다.
13780
+ function _normalizeSuggestedAction(action) {
13781
+ const a = { ...(action || {}) };
13782
+ // 1.36.169 (Codex 교차검수 P2): 예전 생성기는 존재하지 않는 --filter를 안내했다.
13783
+ // 이미 큐에 들어간 항목도 다음 enqueue 때 실행 가능한 현재 CLI 문법으로 마이그레이션한다.
13784
+ if (a.icon === '💭' && /^leerness decision list --filter\s+/.test(String(a.command || ''))) {
13785
+ a.command = String(a.command).replace('decision list --filter', 'decision list --query');
13786
+ }
13787
+ if (a.icon === '🎯' && /^leerness plan list --filter\s+/.test(String(a.command || ''))) {
13788
+ a.command = 'leerness plan list --path .';
13789
+ }
13790
+ const plan = String(a.title || '').match(/plan\.md milestone (M-\d{4,})/);
13791
+ if (a.icon === '🎯' && plan) a.actionKey = `plan:${plan[1]}`;
13792
+ const decision = String(a.command || '').match(/decision list --(?:query|filter)\s+"([^"]+)"/)
13793
+ || String(a.title || '').match(/decisions\.md "([^"]+)"/);
13794
+ if (a.icon === '💭' && decision) a.actionKey = `decision:${decision[1]}`;
13795
+ const lesson = String(a.title || '').match(/lessons\.md 에 "([^"]+)" 관련/);
13796
+ if (a.icon === '🛡' && lesson) a.actionKey = `lessons:${lesson[1]}`;
13797
+ // 패키지를 적용한 일반 프로젝트에는 leerness 자체의 scripts/e2e.js가 없다. 이전 제안도
13798
+ // 업그레이드 직후 list/take에서 바로 실행 가능한 공개 CLI로 바꾼다.
13799
+ if (a.icon === '🧪' && (/review-evidence\.md/.test(String(a.title || ''))
13800
+ || String(a.command || '') === 'node ./scripts/e2e.js')) {
13801
+ a.command = 'leerness verify-code .';
13802
+ a.actionKey = 'verification:evidence';
13803
+ }
13804
+ // 경과 시간이 제목에 들어가면 24h/25h가 서로 다른 큐 항목이 된다. 상태를 단정해 done으로
13805
+ // 바꾸는 명령 대신 현재 task 목록을 확인하는 안전한 명령을 안내한다.
13806
+ const stalled = String(a.title || '').match(/^progress-tracker(?: \d+h)? 정체 — task (T-\d{4,}) (?:status 갱신|상태 검토)$/);
13807
+ if (a.icon === '🔄' && stalled) {
13808
+ a.title = `progress-tracker 정체 — task ${stalled[1]} 상태 검토`;
13809
+ a.command = 'leerness task list --path .';
13810
+ a.actionKey = `task-status:${stalled[1]}`;
13811
+ }
13812
+ if (a.icon === '📝' && /버전 변동 task — CHANGELOG\.md \/ README\.md 갱신 확인/.test(String(a.title || ''))) {
13813
+ a.actionKey = 'release-docs';
13814
+ }
13815
+ // 시간값이 제목에 들어가 매 handoff마다 같은 제안이 새 항목으로 쌓였고, command는 아직 만들지
13816
+ // 않은 stress-v(N+1)를 실행해 항상 ENOENT였다. 작업 제안은 유지하되 안정된 제목으로 합치고
13817
+ // 실행 명령은 싣지 않는다(next-action take가 이 제목으로 추적 task를 만든다).
13818
+ const stress = String(a.title || '').match(/^stress-v(\d+) (?:마지막 갱신 \d+h 전 — |오래됨 — )새 stress test 작성 권장$/);
13819
+ if (a.icon === '🧬' && stress) {
13820
+ a.title = `stress-v${stress[1]} 오래됨 — 새 stress test 작성 권장`;
13821
+ delete a.command;
13822
+ a.actionKey = 'stress-refresh';
13823
+ }
13824
+ return a;
13825
+ }
13826
+ function _nextActionIdentity(action) {
13827
+ const key = String(action && action.actionKey || '').trim();
13828
+ if (key) return `key:${key}`;
13829
+ return `title:${String(action && action.icon || '')}\u0000${String(action && action.title || '')}`;
13830
+ }
13831
+ function _compactNextActionQueue(queue) {
13832
+ const compacted = [];
13833
+ const seen = new Set();
13834
+ // 최신 항목을 보존한다. stress 버전/경과 시간처럼 표시값이 달라도 actionKey가 같으면 하나다.
13835
+ for (let i = (Array.isArray(queue) ? queue.length : 0) - 1; i >= 0; i--) {
13836
+ const action = _normalizeSuggestedAction(queue[i]);
13837
+ const identity = _nextActionIdentity(action);
13838
+ if (seen.has(identity)) continue;
13839
+ seen.add(identity);
13840
+ compacted.unshift(action);
13841
+ }
13842
+ return compacted;
13843
+ }
13844
+ function _normalizedNextActionState(root) {
13845
+ const state = _loadNextActionQueue(root);
13846
+ return { ...state, queue: _compactNextActionQueue(state.queue) };
13847
+ }
13692
13848
  function _enqueueNextActions(root, actions) {
13693
- if (!Array.isArray(actions) || actions.length === 0) return 0;
13849
+ if (!Array.isArray(actions)) return 0;
13694
13850
  return _withLock(_nextActionQueuePath(root), () => {
13695
13851
  const state = _loadNextActionQueue(root);
13696
- const existingTitles = new Set(state.queue.map(a => a.title));
13852
+ const before = JSON.stringify(state.queue);
13853
+ state.queue = _compactNextActionQueue(state.queue);
13854
+ const existing = new Map(state.queue.map((a, i) => [_nextActionIdentity(a), i]));
13697
13855
  let added = 0;
13698
- for (const a of actions) {
13699
- if (existingTitles.has(a.title)) continue;
13700
- state.queue.push({ ...a, addedAt: new Date().toISOString() });
13701
- existingTitles.add(a.title);
13702
- added++;
13856
+ for (const raw of actions) {
13857
+ const a = _normalizeSuggestedAction(raw);
13858
+ const identity = _nextActionIdentity(a);
13859
+ if (existing.has(identity)) {
13860
+ const i = existing.get(identity);
13861
+ const previous = state.queue[i];
13862
+ // 새 관측값(최신 stress 버전/결정 hit 수)은 같은 위치에서 갱신하되 최초 추가 시각은 보존한다.
13863
+ state.queue[i] = { ...previous, ...a, addedAt: previous.addedAt || a.addedAt || new Date().toISOString() };
13864
+ } else {
13865
+ state.queue.push({ ...a, addedAt: new Date().toISOString() });
13866
+ existing.set(identity, state.queue.length - 1);
13867
+ added++;
13868
+ }
13703
13869
  }
13704
13870
  // 최근 20개만 유지
13705
13871
  if (state.queue.length > 20) state.queue = state.queue.slice(-20);
13706
- if (added > 0) _writeNextActionQueue(root, state.queue);
13872
+ if (added > 0 || before !== JSON.stringify(state.queue)) _writeNextActionQueue(root, state.queue);
13707
13873
  return added;
13708
13874
  });
13709
13875
  }
@@ -13711,8 +13877,9 @@ function _enqueueNextActions(root, actions) {
13711
13877
  // 1.9.201: next-action CLI 명령 — handoff 가 저장한 queue 에서 take/list/clear
13712
13878
  async function nextActionCmd(root, sub, ...rest) {
13713
13879
  root = absRoot(root);
13714
- const state = _loadNextActionQueue(root);
13715
13880
  if (!sub || sub === 'list') {
13881
+ // 조회 자체는 쓰지 않지만, 업그레이드 직후에도 legacy 명령/중복을 노출하지 않는다.
13882
+ const state = _normalizedNextActionState(root);
13716
13883
  if (has('--json')) { log(JSON.stringify(state, null, 2)); return; }
13717
13884
  log(`# leerness next-action list (1.9.201)`);
13718
13885
  if (state.queue.length === 0) {
@@ -13732,28 +13899,41 @@ async function nextActionCmd(root, sub, ...rest) {
13732
13899
  return;
13733
13900
  }
13734
13901
  if (sub === 'take') {
13735
- const n = rest[0] !== undefined ? Number(rest[0]) : state.queue.length - 1;
13736
- // 1.36.114 (검수 #3, 재현됨): 로더가 손상 파일을 **빈 큐**로 폴백해 "큐 비어있음 — handoff 먼저 실행" 이라고
13737
- // 오진했다. 사용자는 큐가 비었다고 믿고 handoff 를 다시 돌린다 — 원인(손상)은 끝까지 안 보인다.
13738
- // 읽기 자체는 종전대로 resilient 하게 두고, **판정 지점에서만** 빈 것과 손상된 것을 가른다.
13739
- if (state.queue.length === 0) { _assertStoreParsable(_nextActionQueuePath(root), 'next-action-queue'); fail('큐 비어있음 — handoff 먼저 실행'); return process.exit(1); }
13740
- if (isNaN(n) || n < 0 || n >= state.queue.length) { fail(`잘못된 index: ${n} (0~${state.queue.length - 1})`); return process.exit(1); }
13741
- const action = state.queue[n];
13902
+ let taken;
13903
+ try {
13904
+ // 1.36.169 (Codex 재검수 P2): 선택을 락 밖에서 하고 제목으로 다시 찾으면, 그 사이 legacy
13905
+ // 정규화가 제목을 바꿨을 때 task는 만들면서 큐에는 항목을 남겼다. 정규화·선택·제거를 한
13906
+ // canonical queue transaction으로 묶고 index도 그 스냅샷에서 해석한다.
13907
+ taken = _withLock(_nextActionQueuePath(root), () => {
13908
+ const fresh = _loadNextActionQueue(root);
13909
+ const queue = _compactNextActionQueue(fresh.queue);
13910
+ // 1.36.114: 로더의 손상→빈 배열 fallback과 실제 빈 큐를 판정 지점에서 구분한다.
13911
+ if (queue.length === 0) {
13912
+ _assertStoreParsable(_nextActionQueuePath(root), 'next-action-queue');
13913
+ return { error: 'empty' };
13914
+ }
13915
+ const n = rest[0] !== undefined ? Number(rest[0]) : queue.length - 1;
13916
+ if (isNaN(n) || n < 0 || n >= queue.length) return { error: 'index', n, max: queue.length - 1 };
13917
+ const action = queue[n];
13918
+ queue.splice(n, 1);
13919
+ if (!_writeNextActionQueue(root, queue)) throw new Error('next-action 큐 저장 실패 — task를 만들지 않습니다');
13920
+ return { action, n };
13921
+ });
13922
+ } catch (e) {
13923
+ if (e && e.code === 'E_STORE_CORRUPT') throw e;
13924
+ fail(`next-action take 실패: ${_lineSafe(e && e.message ? e.message : e)}`);
13925
+ process.exitCode = 1;
13926
+ return;
13927
+ }
13928
+ if (taken.error === 'empty') { fail('큐 비어있음 — handoff 먼저 실행'); process.exitCode = 1; return; }
13929
+ if (taken.error === 'index') { fail(`잘못된 index: ${taken.n} (0~${taken.max})`); process.exitCode = 1; return; }
13930
+ const { action, n } = taken;
13742
13931
  log(`# leerness next-action take [${n}] (1.9.201)`);
13743
13932
  log(` ${action.icon || '•'} ${_lineSafe(action.title)}`);
13744
13933
  if (action.command) log(` \`${_lineSafe(action.command)}\``);
13745
13934
  // task add 자동 호출
13746
13935
  try {
13747
13936
  const taskTitle = action.title.replace(/^[^\w가-힣]+/, '').slice(0, 100);
13748
- // 큐에서 제거 → write
13749
- // 1.36.108 (T-0097): 락 안에서 **다시 읽고** 제거한다. 함수 머리에서 읽은 state 로 지우면
13750
- // 그 사이에 handoff 가 큐에 넣은 항목이 통째로 사라진다(handoff 는 자동으로 이 큐를 채운다).
13751
- _withLock(_nextActionQueuePath(root), () => {
13752
- const fresh = _loadNextActionQueue(root);
13753
- const idx = fresh.queue.findIndex(a => a && a.title === action.title);
13754
- if (idx >= 0) fresh.queue.splice(idx, 1);
13755
- _writeNextActionQueue(root, fresh.queue);
13756
- });
13757
13937
  // leerness task add 호출
13758
13938
  const taskResult = cp.spawnSync(process.execPath, [__filename, 'task', 'add', taskTitle, '--path', root], { encoding: 'utf8', timeout: 8000, env: { ...process.env, LEERNESS_INTERNAL: '1' } });
13759
13939
  if (taskResult.status === 0) {
@@ -13773,8 +13953,12 @@ async function nextActionCmd(root, sub, ...rest) {
13773
13953
  return;
13774
13954
  }
13775
13955
  if (sub === 'clear') {
13776
- _writeNextActionQueue(root, []);
13777
- ok(`next-action 큐 초기화 (${state.queue.length}건 제거)`);
13956
+ const removed = _withLock(_nextActionQueuePath(root), () => {
13957
+ const fresh = _loadNextActionQueue(root);
13958
+ if (!_writeNextActionQueue(root, [])) throw new Error('next-action 큐 저장 실패');
13959
+ return fresh.queue.length;
13960
+ });
13961
+ ok(`next-action 큐 초기화 (${removed}건 제거)`);
13778
13962
  return;
13779
13963
  }
13780
13964
  if (sub === 'add') {
@@ -13811,7 +13995,7 @@ function _suggestNextActions(root, latestRow, keyword) {
13811
13995
  const blocks = lt.split(/\n### /);
13812
13996
  const hits = blocks.filter(b => fuzzyRe.test(b) && /(실패|fail|롤백|버그|incomplete)/i.test(b));
13813
13997
  if (hits.length > 0) {
13814
- actions.push({ icon: '🛡', title: `과거 실패 회피 — lessons.md 에 "${keyword}" 관련 ${hits.length}건`, command: `leerness lessons --auto --path .` });
13998
+ actions.push({ actionKey: `lessons:${keyword}`, icon: '🛡', title: `과거 실패 회피 — lessons.md 에 "${keyword}" 관련 ${hits.length}건`, command: `leerness lessons --auto --path .` });
13815
13999
  }
13816
14000
  }
13817
14001
  } catch {}
@@ -13823,7 +14007,7 @@ function _suggestNextActions(root, latestRow, keyword) {
13823
14007
  const milestones = (pt.match(/^### (M-\d{4,})\..*$/gm) || []).filter(l => fuzzyRe.test(l));
13824
14008
  if (milestones.length > 0) {
13825
14009
  const m = milestones[0].match(/M-\d{4,}/);
13826
- if (m) actions.push({ icon: '🎯', title: `plan.md milestone ${m[0]} 검증 — "${keyword}" 관련`, command: `leerness plan list --filter "${keyword}"` });
14010
+ if (m) actions.push({ actionKey: `plan:${m[0]}`, icon: '🎯', title: `plan.md milestone ${m[0]} 검증 — "${keyword}" 관련`, command: 'leerness plan list --path .' });
13827
14011
  }
13828
14012
  }
13829
14013
  } catch {}
@@ -13835,7 +14019,7 @@ function _suggestNextActions(root, latestRow, keyword) {
13835
14019
  const blocks = _extractDecisionBlocks(dt);
13836
14020
  const hits = blocks.filter(b => fuzzyRe.test(b));
13837
14021
  if (hits.length > 0) {
13838
- actions.push({ icon: '💭', title: `decisions.md "${keyword}" 관련 결정 ${hits.length}건 영향 확인`, command: `leerness decision list --filter "${keyword}"` });
14022
+ actions.push({ actionKey: `decision:${keyword}`, icon: '💭', title: `decisions.md "${keyword}" 관련 결정 ${hits.length}건 영향 확인`, command: `leerness decision list --query "${keyword}"` });
13839
14023
  }
13840
14024
  }
13841
14025
  } catch {}
@@ -13843,7 +14027,7 @@ function _suggestNextActions(root, latestRow, keyword) {
13843
14027
  // 4) review-evidence.md 부재 → e2e
13844
14028
  try {
13845
14029
  if (!exists(evidencePath(root)) || fs.statSync(evidencePath(root)).size < 100) {
13846
- actions.push({ icon: '🧪', title: `review-evidence.md 비어있음 — e2e 또는 verify-code 실행`, command: `node ./scripts/e2e.js` });
14030
+ actions.push({ actionKey: 'verification:evidence', icon: '🧪', title: `review-evidence.md 비어있음 — verify-code 실행`, command: `leerness verify-code .` });
13847
14031
  }
13848
14032
  } catch {}
13849
14033
 
@@ -13853,7 +14037,7 @@ function _suggestNextActions(root, latestRow, keyword) {
13853
14037
  if (exists(pp)) {
13854
14038
  const ageHours = Math.floor((Date.now() - fs.statSync(pp).mtimeMs) / 3600000);
13855
14039
  if (ageHours >= 24 && latestRow.id) {
13856
- actions.push({ icon: '🔄', title: `progress-tracker ${ageHours}h 정체 — task ${latestRow.id} status 갱신`, command: `leerness task update ${latestRow.id} --status completed` });
14040
+ actions.push({ actionKey: `task-status:${latestRow.id}`, icon: '🔄', title: `progress-tracker 정체 — task ${latestRow.id} 상태 검토`, command: `leerness task list --path .` });
13857
14041
  }
13858
14042
  }
13859
14043
  } catch {}
@@ -13861,7 +14045,7 @@ function _suggestNextActions(root, latestRow, keyword) {
13861
14045
  // 6) CHANGELOG / README 버전 일치 확인 (1.9.X bump 후 자주 누락되는 단계)
13862
14046
  try {
13863
14047
  if (/(\d\.\d\.\d+)/.test(taskText) || /(bump|version|release)/i.test(taskText)) {
13864
- actions.push({ icon: '📝', title: `버전 변동 task — CHANGELOG.md / README.md 갱신 확인`, command: `leerness whats-new .` });
14048
+ actions.push({ actionKey: 'release-docs', icon: '📝', title: `버전 변동 task — CHANGELOG.md / README.md 갱신 확인`, command: `leerness whats-new .` });
13865
14049
  }
13866
14050
  } catch {}
13867
14051
 
@@ -13877,16 +14061,16 @@ function _suggestNextActions(root, latestRow, keyword) {
13877
14061
  const latestFile = path.join(stressDir, `stress-v${latest}.js`);
13878
14062
  const ageHours = Math.floor((Date.now() - fs.statSync(latestFile).mtimeMs) / 3600000);
13879
14063
  if (ageHours >= 24 && /(bump|version|보강|추가|기능)/.test(taskText)) {
13880
- actions.push({ icon: '🧬', title: `stress-v${latest} 마지막 갱신 ${ageHours}h 전 — 새 stress test 작성 권장`, command: `node _apps/leerness-stress/bin/stress-v${latest+1}.js` });
14064
+ actions.push({ actionKey: 'stress-refresh', icon: '🧬', title: `stress-v${latest} 오래됨 — 새 stress test 작성 권장` });
13881
14065
  }
13882
14066
  }
13883
14067
  }
13884
14068
  } catch {}
13885
14069
 
13886
- // 중복 제거 (icon+title 기준) + top 3
14070
+ // 중복 제거 (시간/버전과 무관한 actionKey 기준) + top 3
13887
14071
  const seen = new Set();
13888
14072
  return actions.filter(a => {
13889
- const key = a.icon + a.title.slice(0, 30);
14073
+ const key = _nextActionIdentity(a);
13890
14074
  if (seen.has(key)) return false;
13891
14075
  seen.add(key);
13892
14076
  return true;
@@ -14207,10 +14391,20 @@ function upsertProgress(root, row) {
14207
14391
  }
14208
14392
 
14209
14393
  function planShow(root) { const p = planPath(root); const has_ = exists(p); const content = has_ ? read(p) : ''; if (has('--json')) { const milestones = (content.match(/^### (M-\d{4,})\b.*$/gm) || []).map(l => l.replace(/^###\s*/, '').trim()); log(JSON.stringify({ exists: has_, milestones, raw: content }, null, 2)); return; } log(has_ ? content : 'plan.md not found'); } // 1.9.428 (UR-0128): plan show --json 구조화
14210
- // plan.md와 progress-tracker.md를 함께 다루는 모든 RMW의 공통 키. plan restore도 이 키를 써야
14211
- // plan add/drop/remove과 같은 스냅샷을 본다 (1.36.152/T-0115).
14212
- function _withPlanTransaction(root, fn) { return _withLock(progressPath(root), fn); }
14213
- function planInit(root) { const goal = arg('--goal', ''); if (!exists(planPath(root))) return install(root); append(planPath(root), `\n## User Goal\n- ${goal || '사용자 목적을 작성하세요.'}\n`); ok('plan goal appended'); }
14394
+ // plan.md 단독 RMW의 canonical lock. plan/progress를 함께 바꾸는 경로는 항상
14395
+ // progress → plan 순서로 잡아 역순 교착과 서로 다른 락 아래의 lost-update를 함께 막는다.
14396
+ function _withPlanLock(root, fn) { return _withLock(planPath(root), fn); }
14397
+ function _withPlanTransaction(root, fn) {
14398
+ return _withLock(progressPath(root), () => _withPlanLock(root, fn));
14399
+ }
14400
+ function planInit(root) {
14401
+ const goal = arg('--goal', '');
14402
+ if (!exists(planPath(root))) return install(root);
14403
+ // 1.36.169 (T-0108): plan add/drop/remove/restore와 같은 plan.md 락을 쓴다.
14404
+ // 종전 append는 성공했어도 동시에 진행된 plan remove의 낡은 전체파일 rename에 지워졌다.
14405
+ _withPlanLock(root, () => append(planPath(root), `\n## User Goal\n- ${goal || '사용자 목적을 작성하세요.'}\n`));
14406
+ ok('plan goal appended');
14407
+ }
14214
14408
  // 1.9.119: plan list — plan.md 의 모든 milestone (M-XXXX) 조회 (CLI + --json + MCP)
14215
14409
  function planListCmd(root, opts = {}) {
14216
14410
  root = absRoot(root);
@@ -14895,10 +15089,11 @@ function memoryRestoreCmd(root, surface, target) {
14895
15089
  : surface === 'lessons' ? lessonsPath(root)
14896
15090
  : planPath(root);
14897
15091
  // 1.36.152 (T-0115): restore는 active canonical store와 archive를 함께 RMW한다.
14898
- // decisions/lessons는 add/drop의 JSON 키, plan은 plan add/drop의 progress 키를 공유해야 한다.
15092
+ // 1.36.169 (T-0108): plan 전용 경로는 progress의 대리 락이 아니라 plan.md canonical 락을 쓴다.
15093
+ // plan+progress 동시 변경은 _withPlanTransaction이 progress → plan 순서로 같은 락에 합류한다.
14899
15094
  const memoryLockPath = surface === 'decisions' ? decisionsJsonPath(root)
14900
15095
  : surface === 'lessons' ? lessonsJsonPath(root)
14901
- : progressPath(root);
15096
+ : planPath(root);
14902
15097
  const restoredCount = _withLock(memoryLockPath, () => {
14903
15098
  if (!exists(archivePath)) return fail(`${surface}.archive.md 없음 — 복원할 항목 없음`);
14904
15099
  // 1.36.76 (9차 헌트 #3 P1) → (검수 #2): 잘린/깨진 UTF-8 아카이브가 손상 데이터를 active 로 유입시키던 것.
@@ -15378,7 +15573,7 @@ function verify(root) {
15378
15573
  // harness 는 deps(VERSION·canonical 메모리 함수·카탈로그·compareVer·harness 경로)를 1회 구성해 위임(thin wrapper). 호출부/동작 무변경.
15379
15574
  const _migrate = require('../lib/migrate');
15380
15575
  function _migrateDeps() {
15381
- return { VERSION, compareVer, REQUIRED_WORKSPACE_FILES, decisionsPath, decisionsJsonPath, lessonsPath, lessonsJsonPath, _loadDecisions, _saveDecisions, _loadLessons, _saveLessons, harnessPath: __filename };
15576
+ return { VERSION, compareVer, REQUIRED_WORKSPACE_FILES, decisionsPath, decisionsJsonPath, lessonsPath, lessonsJsonPath, _loadDecisions, _saveDecisions, _loadLessons, _saveLessons, _withLock, harnessPath: __filename };
15382
15577
  }
15383
15578
  function migrateAuditCmd(root, opts = {}) { return _migrate.migrateAuditCmd(root, opts, _migrateDeps()); }
15384
15579
  function migrateApplyCmd(root, opts = {}) { return _migrate.migrateApplyCmd(root, opts, _migrateDeps()); }
@@ -17170,6 +17365,8 @@ function handoff(root) {
17170
17365
  if (!has('--no-next-actions') && !has('--quiet') && process.env.LEERNESS_NO_NEXT_ACTIONS !== '1') {
17171
17366
  try {
17172
17367
  const actions = _suggestNextActions(root, latestRow, keyword);
17368
+ // 새 제안이 없어도 legacy queue의 잘못된 명령/시간가변 중복은 정규화한다.
17369
+ const added = _enqueueNextActions(root, actions);
17173
17370
  if (actions.length > 0) {
17174
17371
  const isTty = process.stdout && process.stdout.isTTY;
17175
17372
  const grn = s => isTty ? `\x1b[32m${s}\x1b[0m` : s;
@@ -17183,10 +17380,7 @@ function handoff(root) {
17183
17380
  }
17184
17381
  }
17185
17382
  // 1.9.201: queue 자동 저장 — `leerness next-action take` 로 즉시 task add 가능 (토글과 무관: 상태다)
17186
- try {
17187
- const added = _enqueueNextActions(root, actions);
17188
- if (added > 0 && _showAdvice) log(dim(` → 즉시 task add: leerness next-action take (큐 +${added}건 저장됨, 1.9.201)`));
17189
- } catch {}
17383
+ if (added > 0 && _showAdvice) log(dim(` → 즉시 task add: leerness next-action take (큐 +${added}건 저장됨, 1.9.201)`));
17190
17384
  if (_showAdvice) { log(dim(` → 직접 입력: leerness next-action add "<text>"`)); log(''); }
17191
17385
  }
17192
17386
  } catch {}
@@ -22581,6 +22775,15 @@ function captureProjectState(root) {
22581
22775
 
22582
22776
  function verifyRules(root) {
22583
22777
  root = absRoot(root);
22778
+ // 활성 룰이 없으면 읽기 전용으로 끝낸다. cache 디렉터리를 잠금 부작용만으로 만들지 않는다.
22779
+ if (!readRules(root).some(r => r.status === 'active')) return [];
22780
+ // 1.36.169 (T-0108): baseline read → project capture → rule merge → baseline write를 한
22781
+ // cache transaction으로 직렬화한다. 종전에는 오래된 verify가 늦게 끝나 최신 baseline을
22782
+ // 되돌려 다음 세션이 이미 수행한 version/changelog 변경을 다시 pass로 오인할 수 있었다.
22783
+ return _withLock(rulesCachePath(root), () => _verifyRulesLocked(root));
22784
+ }
22785
+
22786
+ function _verifyRulesLocked(root) {
22584
22787
  const rules = readRules(root);
22585
22788
  const active = rules.filter(r => r.status === 'active');
22586
22789
  if (!active.length) return [];