specthread 0.1.0

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.
Files changed (77) hide show
  1. package/README.md +139 -0
  2. package/dist/bin/check.d.ts +1 -0
  3. package/dist/bin/check.js +67 -0
  4. package/dist/bin/cli.d.ts +2 -0
  5. package/dist/bin/cli.js +26 -0
  6. package/dist/bin/generate.d.ts +1 -0
  7. package/dist/bin/generate.js +55 -0
  8. package/dist/checks/changelog.d.ts +8 -0
  9. package/dist/checks/changelog.js +30 -0
  10. package/dist/checks/headings.d.ts +3 -0
  11. package/dist/checks/headings.js +54 -0
  12. package/dist/checks/links.d.ts +8 -0
  13. package/dist/checks/links.js +66 -0
  14. package/dist/checks/markers.d.ts +2 -0
  15. package/dist/checks/markers.js +60 -0
  16. package/dist/checks/pending.d.ts +2 -0
  17. package/dist/checks/pending.js +200 -0
  18. package/dist/checks/references.d.ts +2 -0
  19. package/dist/checks/references.js +41 -0
  20. package/dist/checks/sections.d.ts +3 -0
  21. package/dist/checks/sections.js +137 -0
  22. package/dist/checks/style.d.ts +10 -0
  23. package/dist/checks/style.js +61 -0
  24. package/dist/checks/timestamps.d.ts +2 -0
  25. package/dist/checks/timestamps.js +58 -0
  26. package/dist/checks/toc.d.ts +2 -0
  27. package/dist/checks/toc.js +41 -0
  28. package/dist/commands/init.d.ts +1 -0
  29. package/dist/commands/init.js +115 -0
  30. package/dist/config-loader.d.ts +2 -0
  31. package/dist/config-loader.js +106 -0
  32. package/dist/config.schema.d.ts +96 -0
  33. package/dist/config.schema.js +27 -0
  34. package/dist/constants/docs.d.ts +15 -0
  35. package/dist/constants/docs.js +16 -0
  36. package/dist/constants/patterns.d.ts +24 -0
  37. package/dist/constants/patterns.js +24 -0
  38. package/dist/constants/rules.d.ts +101 -0
  39. package/dist/constants/rules.js +97 -0
  40. package/dist/gen/pending-section.d.ts +19 -0
  41. package/dist/gen/pending-section.js +102 -0
  42. package/dist/gen/references.d.ts +13 -0
  43. package/dist/gen/references.js +144 -0
  44. package/dist/gen/summary.d.ts +27 -0
  45. package/dist/gen/summary.js +125 -0
  46. package/dist/gen/toc.d.ts +25 -0
  47. package/dist/gen/toc.js +66 -0
  48. package/dist/types.d.ts +125 -0
  49. package/dist/types.js +1 -0
  50. package/dist/utils/anchor.d.ts +20 -0
  51. package/dist/utils/anchor.js +24 -0
  52. package/dist/utils/ignore.d.ts +11 -0
  53. package/dist/utils/ignore.js +20 -0
  54. package/dist/utils/parse.d.ts +50 -0
  55. package/dist/utils/parse.js +272 -0
  56. package/dist/utils/report.d.ts +17 -0
  57. package/dist/utils/report.js +38 -0
  58. package/dist/utils/resolve.d.ts +21 -0
  59. package/dist/utils/resolve.js +157 -0
  60. package/dist/utils/scan.d.ts +11 -0
  61. package/dist/utils/scan.js +111 -0
  62. package/dist/utils/scope.d.ts +51 -0
  63. package/dist/utils/scope.js +55 -0
  64. package/package.json +29 -0
  65. package/scaffold/AGENTS.md +67 -0
  66. package/scaffold/CLAUDE.md +1 -0
  67. package/scaffold/claude/skills/check.md +43 -0
  68. package/scaffold/claude/skills/gen.md +41 -0
  69. package/scaffold/claude/skills/plan-close.md +57 -0
  70. package/scaffold/claude/skills/plan-open.md +50 -0
  71. package/scaffold/claude/skills/plan-run.md +51 -0
  72. package/scaffold/config.jsonc +71 -0
  73. package/scaffold/pending.md +34 -0
  74. package/scaffold/project.md +47 -0
  75. package/scaffold/rules.md +421 -0
  76. package/scaffold/templates/plan.md +159 -0
  77. package/scaffold/templates/spec.md +96 -0
package/README.md ADDED
@@ -0,0 +1,139 @@
1
+ # specthread
2
+
3
+ Spec-Driven Development (SDD) 도구. 문서가 단일 진실 원천이고, 검사/생성 도구가 문서 체계를 유지한다.
4
+
5
+ ## 시작하기
6
+
7
+ ```bash
8
+ npm install -D specthread
9
+ npx specthread init
10
+ npx specthread check
11
+ ```
12
+
13
+ `init`이 프로젝트에 SDD 체계를 세팅한다:
14
+
15
+ ```
16
+ specthread/ ← 문서 규칙·설정·미확정 사항
17
+ config.jsonc
18
+ rules.md
19
+ project.md
20
+ pending.md
21
+ docs/templates/ ← 문서 골격 (수정 가능, check 대상)
22
+ spec.md
23
+ plan.md
24
+ AGENTS.md ← AI 도구 진입점
25
+ CLAUDE.md ← Claude Code용 (@AGENTS.md)
26
+ .claude/skills/ ← Claude Code 스킬
27
+ ```
28
+
29
+ 기존 `AGENTS.md`가 있으면 `<!-- specthread:start/end -->` 마커로 섹션만 삽입한다. 기존 `CLAUDE.md`가 있으면 `@AGENTS.md` 줄만 추가한다.
30
+
31
+ ## 명령어
32
+
33
+ ```bash
34
+ npx specthread init [--tools claude,cursor] # 프로젝트 초기화
35
+ npx specthread check # 문서 정합성 검사
36
+ npx specthread gen # 참조 절·목차·요약 표 미리보기
37
+ npx specthread gen --write # 실제 적용
38
+ ```
39
+
40
+ ### check
41
+
42
+ 28개 규칙으로 문서 형식을 검사한다. 목차, 헤딩, 링크, 참조 절, 변경 이력, 미확정 마커 등.
43
+
44
+ ### gen
45
+
46
+ 본문 링크와 헤딩을 기반으로 목차·참조 절·미확정 사항 요약을 생성한다. `--write` 없이 실행하면 변경 대상만 보여준다.
47
+
48
+ ## 설정
49
+
50
+ `specthread/config.jsonc`로 프로젝트별 동작을 제어한다. 개인 오버라이드는 `specthread/config.local.jsonc` (gitignore 대상).
51
+
52
+ ```
53
+ Core defaults (도구 내부 기본값)
54
+ ↓ deep merge
55
+ specthread/config.jsonc (프로젝트 공유)
56
+ ↓ deep merge
57
+ specthread/config.local.jsonc (개인)
58
+ ```
59
+
60
+ 설정이 없으면 기본값으로 동작한다. init이 생성하는 `config.jsonc`에 모든 옵션이 주석으로 설명되어 있다.
61
+
62
+ | 키 | 역할 |
63
+ |---|---|
64
+ | `path` | 스캔 대상 경로 (자유 KV) |
65
+ | `features` | 기능 플래그 (`markers`, `emDash`, `references`) |
66
+ | `markers` | 마커 종류·시점 라벨 |
67
+ | `docTypes` | 경로별 템플릿·프론트매터 스키마 |
68
+ | `skipCheck` | 검사 건너뛸 경로 |
69
+ | `skipRefs` | 참조 절 생성 건너뛸 경로 |
70
+
71
+ ## SDD 작업 흐름
72
+
73
+ ```
74
+ 스펙 확인 → 현황 점검(check) → 계획 수립 → 구현 → 검증(check) → 문서 갱신
75
+ ```
76
+
77
+ 구현 전에 spec을 읽고, 구현 후에 spec을 갱신한다. 진행 중 모호함을 발견하면 `PENDING` 마커를 남기고 작업을 계속한다.
78
+
79
+ ### 예시: 기존 인증 spec에 소셜 로그인 추가
80
+
81
+ `docs/spec/auth.md`가 이미 있는 프로젝트에서 소셜 로그인을 추가한다:
82
+
83
+ ```
84
+ You: 소셜 로그인 기능 계획 세워줘
85
+ AI: docs/spec/auth.md 를 읽고, plan 템플릿 기반으로
86
+ docs/work/social-login.md 생성.
87
+ 목표, 작업 단계, 영향 파일을 함께 채운다.
88
+ 문서 정합성 검사 통과.
89
+ ```
90
+
91
+ ```
92
+ You: 진행해줘
93
+ AI: 작업 단계 1 "OAuth 프로바이더 연동" 구현.
94
+ 세션 관리 방식이 미확정이라
95
+ PENDING::design::oauth-session 마커를 남긴다.
96
+ 단계 상태를 "완료"로 갱신.
97
+ ```
98
+
99
+ ```
100
+ You: 전부 끝났어, 정리해줘
101
+ AI: 종료 게이트 점검 후,
102
+ 작업 내용을 docs/spec/auth.md §3 에 흡수.
103
+ docs/work/social-login.md 삭제.
104
+ 문서 정합성 검사 통과.
105
+ ```
106
+
107
+ 결과: `docs/spec/auth.md`에 소셜 로그인 절이 추가되고, work 문서는 사라진다. spec이 항상 현재 시스템의 정본으로 남는다.
108
+
109
+ AI는 작업 중에 `check`와 `gen`을 자동으로 호출한다. `AGENTS.md`가 이 워크플로우를 AI에게 전달하고, `check`가 문서와 코드의 어긋남을 잡는다.
110
+
111
+ ## AI 도구 지원
112
+
113
+ `AGENTS.md`가 본체. 대부분의 AI 코딩 도구가 이 파일을 읽는다.
114
+
115
+ | 도구 | 동작 |
116
+ |------|------|
117
+ | Claude Code | `CLAUDE.md`의 `@AGENTS.md`가 자동 확장 |
118
+ | Cursor / Copilot / Codex / Gemini | `AGENTS.md`를 네이티브로 읽음 |
119
+
120
+ `--tools claude` (기본값)로 init하면 Claude Code 스킬이 함께 설치된다:
121
+
122
+ | 스킬 | 역할 |
123
+ |------|------|
124
+ | `/check` | 문서 검사 실행 + 결과 해석 |
125
+ | `/gen` | 참조 절·목차 생성 + 적용 안내 |
126
+ | `/plan-open` | 작업 계획 문서 작성·검수·확정 |
127
+ | `/plan-run` | 계획에 따라 실행·기록 |
128
+ | `/plan-close` | 완료된 작업을 spec에 흡수 |
129
+
130
+ 스킬 없이 자연어로 같은 작업을 요청해도 된다. `AGENTS.md`가 AI에게 워크플로우를 알려주기 때문이다. 스킬은 자주 쓰는 흐름의 단축키다.
131
+
132
+ ## 요구 사항
133
+
134
+ - Node.js >= 18.0.0
135
+ - 외부 의존성 없음 (zero-dependency)
136
+
137
+ ## 라이선스
138
+
139
+ MIT
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,67 @@
1
+ /**
2
+ * 문서 검사기 진입점. `pnpm docs:check`
3
+ *
4
+ * `pnpm test` 와 분리해 둔다 - 실 문서 재편이 끝나기 전에는 목차·참조 절 지적이
5
+ * 대량으로 남으므로, 4 smoke 에 넣으면 게이트가 상시 red 가 되어 신호 기능을 잃는다.
6
+ */
7
+ import { loadConfig } from '../config-loader.js';
8
+ import { buildIndex } from '../utils/scan.js';
9
+ import { checkLinks } from '../checks/links.js';
10
+ import { checkSectionRefs } from '../checks/sections.js';
11
+ import { checkChangeLog } from '../checks/changelog.js';
12
+ import { checkHeadings } from '../checks/headings.js';
13
+ import { checkToc } from '../checks/toc.js';
14
+ import { checkReferences } from '../checks/references.js';
15
+ import { checkTimestamps } from '../checks/timestamps.js';
16
+ import { checkPending } from '../checks/pending.js';
17
+ import { checkMarkers } from '../checks/markers.js';
18
+ import { checkRuleDeclared, checkStyle } from '../checks/style.js';
19
+ import { isIgnored } from '../utils/ignore.js';
20
+ import { report } from '../utils/report.js';
21
+ import { isWorkExempt } from '../utils/scope.js';
22
+ const config = loadConfig();
23
+ const index = buildIndex(config);
24
+ // 색인 규모를 먼저 찍는다. 지적 수만 보면 검사가 실제로 대상을 훑었는지 알 수 없다
25
+ const counts = { md: 0, code: 0, json: 0 };
26
+ let headings = 0;
27
+ let links = 0;
28
+ let sectionRefs = 0;
29
+ let markers = 0;
30
+ let legacyMarkers = 0;
31
+ let pendingItems = 0;
32
+ for (const f of index.files.values()) {
33
+ counts[f.kind]++;
34
+ headings += f.headings.length;
35
+ links += f.links.length;
36
+ sectionRefs += f.sectionRefs.length;
37
+ markers += f.markers.filter((m) => !m.legacy).length;
38
+ legacyMarkers += f.markers.filter((m) => m.legacy).length;
39
+ pendingItems += f.pendingItems.length;
40
+ }
41
+ let ignoredLines = 0;
42
+ for (const f of index.files.values())
43
+ ignoredLines += f.ignored.size;
44
+ const summary = {
45
+ title: '색인',
46
+ lines: [
47
+ `문서 ${counts.md} / 코드 ${counts.code} / 데이터 ${counts.json}`,
48
+ `헤딩 ${headings} / 링크 ${links} / 절 참조 ${sectionRefs}`,
49
+ `마커 새 형식 ${markers} / 구 형식 ${legacyMarkers} / 미확정 항목 ${pendingItems}`,
50
+ `인라인 억제 ${ignoredLines}`,
51
+ ],
52
+ };
53
+ const { features } = config;
54
+ const findings = [
55
+ ...checkHeadings(index),
56
+ ...checkToc(index),
57
+ ...(features.references ? checkReferences(index) : []),
58
+ ...checkLinks(index),
59
+ ...checkSectionRefs(index),
60
+ ...checkChangeLog(index),
61
+ ...checkTimestamps(index),
62
+ ...(features.markers ? checkPending(index) : []),
63
+ ...(features.markers ? checkMarkers(index) : []),
64
+ ...(features.emDash ? checkStyle(index) : []),
65
+ ...checkRuleDeclared(index),
66
+ ].filter((f) => !isWorkExempt(f, index.config) && !isIgnored(index, f));
67
+ process.exit(report(findings, summary));
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ const [command, ...rest] = process.argv.slice(2);
3
+ const usage = `specthread <command>
4
+
5
+ commands:
6
+ init [--tools claude,cursor] 프로젝트 초기화
7
+ check 문서 검사
8
+ gen [--write] 참조/목차 생성`;
9
+ const run = async () => {
10
+ switch (command) {
11
+ case "check":
12
+ await import("./check.js");
13
+ break;
14
+ case "gen":
15
+ await import("./generate.js");
16
+ break;
17
+ case "init":
18
+ await (await import("../commands/init.js")).init(rest);
19
+ break;
20
+ default:
21
+ console.log(usage);
22
+ process.exit(command === undefined || command === "--help" ? 0 : 1);
23
+ }
24
+ };
25
+ run();
26
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,55 @@
1
+ /**
2
+ * 생성기 진입점. `pnpm docs:generate` (미리보기) / `--write` (적용)
3
+ *
4
+ * 기본이 미리보기다. 문서를 고치는 도구가 확인 없이 쓰면 되돌리기가 어렵다.
5
+ */
6
+ import { writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { loadConfig } from "../config-loader.js";
9
+ import { buildIndex, REPO_ROOT } from "../utils/scan.js";
10
+ import { isTargetDoc } from "../utils/scope.js";
11
+ import { applyToc } from "../gen/toc.js";
12
+ import { applyReferences } from "../gen/references.js";
13
+ import { applySummary } from "../gen/summary.js";
14
+ import { applyPendingSection } from "../gen/pending-section.js";
15
+ /**
16
+ * 한 문서에 걸 생성기 목록. **문서 아래쪽을 고치는 것부터** 둔다.
17
+ *
18
+ * 색인의 줄 번호는 원본 기준이라, 위쪽을 먼저 고치면 아래쪽 생성기가 밀린 자리를
19
+ * 가리킨다. 반대 순서면 앞 생성기가 건드린 범위가 뒤 생성기의 범위 밖이라 안전하다.
20
+ */
21
+ const write = process.argv.includes("--write");
22
+ const config = loadConfig();
23
+ const { features } = config;
24
+ const GENERATORS = [
25
+ ...(features.markers ? [applyPendingSection] : []),
26
+ ...(features.references ? [applyReferences] : []),
27
+ ...(features.markers ? [applySummary] : []),
28
+ applyToc,
29
+ ];
30
+ const index = buildIndex(config);
31
+ const files = index.files.values();
32
+ const changed = [];
33
+ for (const file of files) {
34
+ if (!isTargetDoc(file, index.config))
35
+ continue;
36
+ let next = file.lines;
37
+ for (const apply of GENERATORS) {
38
+ next = apply(file, next, index) ?? next;
39
+ }
40
+ // 바꿀 것이 없는 문서는 목록에 올리지 않는다
41
+ if (next === file.lines)
42
+ continue;
43
+ changed.push(file.path);
44
+ if (write) {
45
+ writeFileSync(join(REPO_ROOT, file.path), next.join("\n"), "utf8");
46
+ }
47
+ }
48
+ const mode = write ? "적용" : "미리보기";
49
+ console.log(`문서 생성 ${mode} - ${changed.length} 건`);
50
+ for (const path of changed) {
51
+ console.log(` ${path}`);
52
+ }
53
+ if (!write && changed.length > 0) {
54
+ console.log("\n실제로 쓰려면 --write");
55
+ }
@@ -0,0 +1,8 @@
1
+ import type { DocIndex, Finding } from '../types.ts';
2
+ /**
3
+ * 날짜가 거꾸로 놓인 첫 자리를 찾아 한 건만 지적한다.
4
+ *
5
+ * 줄마다 지적하면 한 문서에서 여러 건이 쏟아지는데 고치는 일은 표 하나를 다시
6
+ * 정렬하는 한 번의 작업이다.
7
+ */
8
+ export declare const checkChangeLog: (index: DocIndex) => Finding[];
@@ -0,0 +1,30 @@
1
+ import { RULE } from '../constants/rules.js';
2
+ /** 변경 이력 순서 - 오래된 순이어야 한다 (`docs/system/rules.md` §2-4). */
3
+ import { isCheckTarget } from '../utils/scope.js';
4
+ /**
5
+ * 날짜가 거꾸로 놓인 첫 자리를 찾아 한 건만 지적한다.
6
+ *
7
+ * 줄마다 지적하면 한 문서에서 여러 건이 쏟아지는데 고치는 일은 표 하나를 다시
8
+ * 정렬하는 한 번의 작업이다.
9
+ */
10
+ export const checkChangeLog = (index) => {
11
+ const findings = [];
12
+ for (const file of index.files.values()) {
13
+ if (file.kind !== 'md' || !isCheckTarget(file.path, index.config))
14
+ continue;
15
+ if (file.changeLogDates.length < 2)
16
+ continue;
17
+ const dates = file.changeLogDates;
18
+ const bad = dates.findIndex((d, i) => i > 0 && d < dates[i - 1]);
19
+ if (bad < 0)
20
+ continue;
21
+ const heading = file.headings.find((h) => h.title === '변경 이력');
22
+ findings.push({
23
+ file: file.path,
24
+ line: heading?.line ?? 1,
25
+ rule: RULE.CHANGELOG.ORDER,
26
+ message: `오래된 순이 아니다 - ${dates[bad - 1]} 다음에 ${dates[bad]}`,
27
+ });
28
+ }
29
+ return findings;
30
+ };
@@ -0,0 +1,3 @@
1
+ import type { DocIndex, Finding } from "../types.ts";
2
+ /** 꼬리 절 이름. `parse.ts` 의 판정과 같은 목록이어야 한다 */
3
+ export declare const checkHeadings: (index: DocIndex) => Finding[];
@@ -0,0 +1,54 @@
1
+ import { TAIL_NAMES } from '../constants/docs.js';
2
+ import { RULE } from '../constants/rules.js';
3
+ /**
4
+ * 헤딩 구조 - 제목이 하나인가, 꼬리 절 이름을 본문에서 재사용하지 않는가,
5
+ * 꼬리 절에 번호가 붙지 않았는가.
6
+ *
7
+ * 둘 다 생성기가 자리를 잘못 짚게 만드는 원인이다. 꼬리 절은 이름으로 찾으므로
8
+ * 이름이 겹치면 어느 쪽이 꼬리인지 가릴 수 없고, 번호가 붙으면 규칙 8 과 어긋난다.
9
+ */
10
+ import { isTargetDoc, titleHeadings } from "../utils/scope.js";
11
+ /** 꼬리 절 이름. `parse.ts` 의 판정과 같은 목록이어야 한다 */
12
+ export const checkHeadings = (index) => {
13
+ const findings = [];
14
+ for (const file of index.files.values()) {
15
+ if (!isTargetDoc(file, index.config))
16
+ continue;
17
+ // 제목이 둘이면 목차를 어디에 둘지 정할 근거가 없다. 생성기도 이 문서를 건너뛴다
18
+ const titles = titleHeadings(file);
19
+ if (titles.length > 1) {
20
+ findings.push({
21
+ file: file.path,
22
+ line: titles[1].line,
23
+ rule: RULE.HEADING.MULTIPLE_TITLE,
24
+ message: `문서 제목이 ${titles.length} 개다 - 하나여야 한다`,
25
+ });
26
+ }
27
+ for (const heading of file.headings) {
28
+ // 꼬리 이름과 겹치는 제목만 본다. 나머지는 이 검사의 관심 밖이다
29
+ if (!TAIL_NAMES.includes(heading.title))
30
+ continue;
31
+ // 번호가 붙었으면 본문 절로 쓰려 한 것이거나 꼬리 절에 번호를 남긴 것이다.
32
+ // 둘을 가릴 수 없으므로 위치로 판단한다 - 뒤에 번호 있는 `##` 이 더 오면 본문이다
33
+ const laterNumbered = file.headings.some((h) => h.level === 2 && h.line > heading.line && h.num !== null);
34
+ if (heading.num !== null && laterNumbered) {
35
+ findings.push({
36
+ file: file.path,
37
+ line: heading.line,
38
+ rule: RULE.HEADING.TAIL_NAME_REUSED,
39
+ message: `본문 절 제목이 꼬리 절 이름과 같다 - \`${heading.raw}\``,
40
+ });
41
+ continue;
42
+ }
43
+ if (heading.num !== null) {
44
+ findings.push({
45
+ file: file.path,
46
+ line: heading.line,
47
+ rule: RULE.HEADING.NUMBERED_TAIL,
48
+ message: `꼬리 절에 번호가 붙었다 - \`${heading.raw}\``,
49
+ });
50
+ }
51
+ }
52
+ }
53
+ return findings;
54
+ };
@@ -0,0 +1,8 @@
1
+ import type { DocIndex, Finding } from '../types.ts';
2
+ /**
3
+ * 링크를 두 단계로 본다 - 대상 파일이 있는가, 그 문서에 앵커가 있는가.
4
+ *
5
+ * 앵커 대조는 색인 안에 있는 문서만 한다. 색인 밖 (`archive/` 등) 은 헤딩을 모르므로
6
+ * 존재 확인까지만 하고 넘어간다.
7
+ */
8
+ export declare const checkLinks: (index: DocIndex) => Finding[];
@@ -0,0 +1,66 @@
1
+ import { RULE } from '../constants/rules.js';
2
+ /** 링크 유효성 - 대상 파일이 있는가, 앵커가 실제 헤딩을 가리키는가. */
3
+ import { existsSync } from 'node:fs';
4
+ import { join, dirname, normalize } from 'node:path';
5
+ import { REPO_ROOT } from '../utils/scan.js';
6
+ import { inChangeLog, inRefSection, isCheckTarget } from '../utils/scope.js';
7
+ /** 외부 링크는 파일 시스템에 없으니 확인하지 않는다 */
8
+ const isExternal = (target) => /^(https?:|mailto:)/.test(target);
9
+ /**
10
+ * 링크를 두 단계로 본다 - 대상 파일이 있는가, 그 문서에 앵커가 있는가.
11
+ *
12
+ * 앵커 대조는 색인 안에 있는 문서만 한다. 색인 밖 (`archive/` 등) 은 헤딩을 모르므로
13
+ * 존재 확인까지만 하고 넘어간다.
14
+ */
15
+ export const checkLinks = (index) => {
16
+ const findings = [];
17
+ for (const file of index.files.values()) {
18
+ if (file.kind !== 'md' || !isCheckTarget(file.path, index.config))
19
+ continue;
20
+ const anchors = new Set(file.headings.map((h) => h.anchor));
21
+ for (const link of file.links) {
22
+ if (inChangeLog(file, link.line))
23
+ continue;
24
+ // 참조 절의 대상은 본문 링크를 그대로 옮긴 것이라 여기서 깨졌으면 본문에서도
25
+ // 깨져 있다. 고칠 자리는 본문이고, 참조 절은 다시 생성하면 따라온다
26
+ if (inRefSection(file, link.line))
27
+ continue;
28
+ if (link.target === null) {
29
+ if (link.anchor && !anchors.has(link.anchor))
30
+ findings.push({
31
+ file: file.path,
32
+ line: link.line,
33
+ rule: RULE.LINK.ANCHOR,
34
+ message: `자기 문서에 앵커 #${link.anchor} 가 없다`,
35
+ });
36
+ continue;
37
+ }
38
+ if (isExternal(link.target))
39
+ continue;
40
+ const rel = normalize(join(dirname(file.path), link.target));
41
+ if (!existsSync(join(REPO_ROOT, rel))) {
42
+ findings.push({
43
+ file: file.path,
44
+ line: link.line,
45
+ rule: RULE.LINK.TARGET,
46
+ message: `대상이 없다 - ${link.target}`,
47
+ });
48
+ continue;
49
+ }
50
+ if (!link.anchor || !rel.endsWith('.md'))
51
+ continue;
52
+ const target = index.files.get(rel);
53
+ // 색인 범위 밖 문서 (archive 등) 는 앵커를 확인하지 않는다
54
+ if (!target)
55
+ continue;
56
+ if (!target.headings.some((h) => h.anchor === link.anchor))
57
+ findings.push({
58
+ file: file.path,
59
+ line: link.line,
60
+ rule: RULE.LINK.ANCHOR,
61
+ message: `${link.target} 에 앵커 #${link.anchor} 가 없다`,
62
+ });
63
+ }
64
+ }
65
+ return findings;
66
+ };
@@ -0,0 +1,2 @@
1
+ import type { DocIndex, Finding } from "../types.ts";
2
+ export declare const checkMarkers: (index: DocIndex) => Finding[];
@@ -0,0 +1,60 @@
1
+ /**
2
+ * 마커 ↔ 관리 문서 대조 (`docs/system/rules.md` §4-1).
3
+ *
4
+ * 양방향으로 본다 - 코드·문서에 박힌 새 형식 마커가 관리 문서 항목을 실제로
5
+ * 가리키는가, 그리고 관리 문서 항목이 최소 하나의 마커에서라도 걸리는가.
6
+ */
7
+ import { RULE } from "../constants/rules.js";
8
+ const ITEM = /^###\s+`\[([a-z]+::[a-z0-9][a-z0-9-]*)\]`/;
9
+ /** 관리 문서 항목 slug → 그 헤딩 줄 번호 */
10
+ const pendingItemLines = (pending) => {
11
+ const out = new Map();
12
+ let inChangeLog = false;
13
+ pending.lines.forEach((raw, i) => {
14
+ if (/^## 변경 이력/.test(raw))
15
+ inChangeLog = true;
16
+ if (inChangeLog)
17
+ return;
18
+ const m = ITEM.exec(raw);
19
+ if (m)
20
+ out.set(m[1], i + 1);
21
+ });
22
+ return out;
23
+ };
24
+ export const checkMarkers = (index) => {
25
+ const pending = index.files.get(index.config.pending);
26
+ if (pending === undefined)
27
+ return [];
28
+ const items = pendingItemLines(pending);
29
+ const findings = [];
30
+ const seen = new Set();
31
+ for (const file of index.files.values()) {
32
+ if (file.path === index.config.pending)
33
+ continue;
34
+ for (const marker of file.markers) {
35
+ if (marker.legacy || marker.slug === "")
36
+ continue;
37
+ const id = `${marker.kind}::${marker.slug}`;
38
+ seen.add(id);
39
+ if (items.has(id) || file.ignored.has(marker.line))
40
+ continue;
41
+ findings.push({
42
+ file: file.path,
43
+ line: marker.line,
44
+ rule: RULE.MARKER.ORPHAN,
45
+ message: `PENDING::${id} 를 가리키는 관리 문서 항목이 없다`,
46
+ });
47
+ }
48
+ }
49
+ for (const [slug, line] of items) {
50
+ if (seen.has(slug) || pending.ignored.has(line))
51
+ continue;
52
+ findings.push({
53
+ file: pending.path,
54
+ line,
55
+ rule: RULE.MARKER.UNMARKED,
56
+ message: `[${slug}] 를 가리키는 마커가 없다 - 억제하려면 @specthread-ignore`,
57
+ });
58
+ }
59
+ return findings;
60
+ };
@@ -0,0 +1,2 @@
1
+ import type { DocIndex, Finding } from '../types.ts';
2
+ export declare const checkPending: (index: DocIndex) => Finding[];