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
@@ -0,0 +1,24 @@
1
+ /**
2
+ * 헤딩 텍스트 → GitHub 앵커 변환.
3
+ *
4
+ * 목차 생성기와 링크 검사가 같은 규칙을 써야 하므로 한 곳에 둔다.
5
+ * 규칙: 소문자화 → 영숫자·하이픈·밑줄·공백·CJK 외 제거 → 공백을 하이픈으로.
6
+ *
7
+ * **공백은 하나씩 바꾼다.** 여러 개를 하나로 합치지 않는다. `항목 · 형식` 처럼
8
+ * 지워지는 구두점 양옆에 공백이 있으면 그 자리에 공백 둘이 남아 하이픈 둘이 된다.
9
+ * 하이픈 자신은 허용 문자라 지워지지 않는다 - `항목 - 형식` 은 하이픈 셋이 된다.
10
+ */
11
+ export const slugify = (text) => text
12
+ .trim()
13
+ .toLowerCase()
14
+ .replace(/[^\p{L}\p{N}\s_-]/gu, '')
15
+ .replace(/\s/g, '-');
16
+ /**
17
+ * 헤딩 원문에서 앞머리 번호를 떼어낸다. `6-1. 기본 데미지` → `6-1` + `기본 데미지`
18
+ *
19
+ * 중간 자리에 문자가 오는 `1-B-1` 도 받는다 - `CLAUDE.md` §7 이 정한 형태다.
20
+ */
21
+ export const splitHeadingNum = (raw) => {
22
+ const m = /^(\d+(?:-[0-9A-Za-z]+)*)\.\s+(.*)$/.exec(raw);
23
+ return m ? { num: m[1], title: m[2] } : { num: null, title: raw };
24
+ };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * 인라인 억제 - `@specthread-ignore` 로 특정 줄의 지적을 막는다.
3
+ *
4
+ * 같은 줄이나 바로 윗줄에 `@specthread-ignore` 가 있으면 그 줄의 지적을 건너뛴다.
5
+ * eslint-disable-next-line 과 같은 모델이다.
6
+ */
7
+ import type { DocIndex, Finding } from "../types.ts";
8
+ /** 줄 배열에서 억제된 줄 번호(1-indexed)를 모은다 */
9
+ export declare const parseIgnoredLines: (lines: string[]) => Set<number>;
10
+ /** 인라인 억제에 해당하는 지적인지 */
11
+ export declare const isIgnored: (index: DocIndex, finding: Finding) => boolean;
@@ -0,0 +1,20 @@
1
+ const IGNORE = /@specthread-ignore/;
2
+ /** 줄 배열에서 억제된 줄 번호(1-indexed)를 모은다 */
3
+ export const parseIgnoredLines = (lines) => {
4
+ const ignored = new Set();
5
+ for (let i = 0; i < lines.length; i++) {
6
+ if (!IGNORE.test(lines[i]))
7
+ continue;
8
+ ignored.add(i + 1);
9
+ if (i + 1 < lines.length)
10
+ ignored.add(i + 2);
11
+ }
12
+ return ignored;
13
+ };
14
+ /** 인라인 억제에 해당하는 지적인지 */
15
+ export const isIgnored = (index, finding) => {
16
+ const file = index.files.get(finding.file);
17
+ if (file === undefined)
18
+ return false;
19
+ return file.ignored.has(finding.line);
20
+ };
@@ -0,0 +1,50 @@
1
+ import type { AnchorLabelSpan, FileKind, Heading, IndexedFile, Marker, Range } from '../types.ts';
2
+ /**
3
+ * 펜스 코드블록 바깥의 줄만 넘겨준다.
4
+ *
5
+ * 펜스 여는 줄과 닫는 줄 자체도 넘기지 않는다. 여닫이를 구분하지 않고 토글만
6
+ * 하므로 언어 표기가 붙은 ` ```markdown ` 도 그대로 잡힌다.
7
+ */
8
+ export declare const eachContentLine: (lines: string[], fn: (line: string, index: number) => void) => void;
9
+ /**
10
+ * 인라인 백틱 코드 스팬 위치. 각 문자가 코드 안인지 표시한다.
11
+ *
12
+ * 백틱 안 `§1-A-3` 은 표기법을 인용한 것이지 참조가 아니다. 반대로
13
+ * `` `skill-tree.md §4` `` 처럼 문서명을 함께 담은 것은 실 참조라서, 스팬 안에
14
+ * 문서명이 있는지로 갈라야 한다. 위치만 계산해 두고 판정은 참조 파서가 한다.
15
+ */
16
+ export declare const codeSpanMask: (line: string) => boolean[];
17
+ /**
18
+ * 앵커가 붙은 마크다운 링크의 라벨 구간.
19
+ *
20
+ * `[`battle.md` §7](./battle.md#7-승리---패배-조건)` 처럼 라벨 안에 놓인 `§` 는 이미
21
+ * 앵커로 걸린 참조라 정상이다. 반대로 라벨 밖 `§` 는 링크 없이 적은 것이다.
22
+ * 절 참조 파서가 이 구간으로 둘을 가른다.
23
+ */
24
+ export declare const anchorLinkLabelSpans: (line: string) => AnchorLabelSpan[];
25
+ /** 마크다운 링크의 대상 `(...)` 구간. URL 안 문자열을 본문과 가르는 데 쓴다 */
26
+ export declare const linkTargetSpans: (line: string) => Range[];
27
+ /**
28
+ * 마커를 모은다. 새 형식과 구 형식을 갈라 담으므로 재편 진척을 셀 수 있다.
29
+ *
30
+ * 마크다운은 펜스 안을 건너뛰고 (템플릿이 마커 예시를 코드블록에 담는다),
31
+ * 코드와 JSON 은 전부 훑는다.
32
+ */
33
+ export declare const parseMarkers: (lines: string[], kind: FileKind) => Marker[];
34
+ /**
35
+ * 헤딩만 뽑는다.
36
+ *
37
+ * 색인과 따로 부를 수 있어야 한다. 생성기가 절을 새로 끼워 넣으면 헤딩 목록이
38
+ * 바뀌므로, 뒤따르는 생성기는 색인이 아니라 **갱신된 줄** 에서 다시 읽어야 한다.
39
+ *
40
+ * 문서 제목 (`#`) 도 담는다. 절은 아니지만 제목이 둘인 문서를 가려내야 하고,
41
+ * 절 판정은 모두 `level === 2` 로 걸러 쓴다.
42
+ */
43
+ export declare const parseHeadings: (lines: string[]) => Heading[];
44
+ /**
45
+ * 문서 한 개를 훑어 색인 항목을 만든다. 절 참조는 별도로 해소하므로 빠져 있다.
46
+ *
47
+ * 훑으면서 들고 가는 상태는 두 개뿐이다 - 직전 헤딩 번호 (링크를 절에 귀속시킨다) 와
48
+ * 꼬리 절 진입 여부. 절 범위는 훑기가 끝난 뒤 헤딩 목록에서 뽑는다.
49
+ */
50
+ export declare const parseMarkdown: (path: string, lines: string[]) => Omit<IndexedFile, 'sectionRefs' | 'ignored'>;
@@ -0,0 +1,272 @@
1
+ /**
2
+ * 마크다운 한 파일에서 색인 재료를 뽑는다 - 헤딩·링크·마커·미확정 항목과
3
+ * 생성기가 덮어쓸 블록의 위치.
4
+ *
5
+ * 펜스 코드블록 안은 전부 무시한다. 템플릿이 골격을 코드블록으로 담고 있어서
6
+ * 추적하지 않으면 헤딩 88 개와 링크 90 개가 오탐으로 잡힌다.
7
+ */
8
+ import { TAIL_NAMES } from '../constants/docs.js';
9
+ import { slugify, splitHeadingNum } from './anchor.js';
10
+ /**
11
+ * 꼬리 절 이름. 하나가 나오면 그 뒤는 전부 꼬리다.
12
+ *
13
+ * 꼬리 절은 문서 맨 끝에 순서대로 오므로 (`docs/system/rules.md` 규칙 8) 첫 꼬리
14
+ * 헤딩부터 파일 끝까지를 꼬리로 보면 된다. 하위 절 (`### 문서` 등) 도 따라 잡힌다.
15
+ */
16
+ const TAIL_SET = new Set(TAIL_NAMES);
17
+ /**
18
+ * 펜스 코드블록 바깥의 줄만 넘겨준다.
19
+ *
20
+ * 펜스 여는 줄과 닫는 줄 자체도 넘기지 않는다. 여닫이를 구분하지 않고 토글만
21
+ * 하므로 언어 표기가 붙은 ` ```markdown ` 도 그대로 잡힌다.
22
+ */
23
+ export const eachContentLine = (lines, fn) => {
24
+ let fence = false;
25
+ lines.forEach((line, i) => {
26
+ if (/^\s*(```|~~~)/.test(line)) {
27
+ fence = !fence;
28
+ return;
29
+ }
30
+ if (!fence)
31
+ fn(line, i);
32
+ });
33
+ };
34
+ /**
35
+ * 인라인 백틱 코드 스팬 위치. 각 문자가 코드 안인지 표시한다.
36
+ *
37
+ * 백틱 안 `§1-A-3` 은 표기법을 인용한 것이지 참조가 아니다. 반대로
38
+ * `` `skill-tree.md §4` `` 처럼 문서명을 함께 담은 것은 실 참조라서, 스팬 안에
39
+ * 문서명이 있는지로 갈라야 한다. 위치만 계산해 두고 판정은 참조 파서가 한다.
40
+ */
41
+ export const codeSpanMask = (line) => {
42
+ const mask = new Array(line.length).fill(false);
43
+ let open = -1;
44
+ for (let i = 0; i < line.length; i++) {
45
+ if (line[i] !== '`')
46
+ continue;
47
+ if (open < 0)
48
+ open = i;
49
+ else {
50
+ for (let j = open; j <= i; j++)
51
+ mask[j] = true;
52
+ open = -1;
53
+ }
54
+ }
55
+ return mask;
56
+ };
57
+ /**
58
+ * 앵커가 붙은 마크다운 링크의 라벨 구간.
59
+ *
60
+ * `[`battle.md` §7](./battle.md#7-승리---패배-조건)` 처럼 라벨 안에 놓인 `§` 는 이미
61
+ * 앵커로 걸린 참조라 정상이다. 반대로 라벨 밖 `§` 는 링크 없이 적은 것이다.
62
+ * 절 참조 파서가 이 구간으로 둘을 가른다.
63
+ */
64
+ export const anchorLinkLabelSpans = (line) => {
65
+ const spans = [];
66
+ for (const m of line.matchAll(/\[([^\]]*)\]\(([^)\s]+)\)/g)) {
67
+ if (!m[2].includes('#'))
68
+ continue;
69
+ const labelStart = m.index + 1;
70
+ spans.push({
71
+ start: labelStart,
72
+ end: labelStart + m[1].length,
73
+ target: m[2].split('#')[0],
74
+ });
75
+ }
76
+ return spans;
77
+ };
78
+ /** 마크다운 링크의 대상 `(...)` 구간. URL 안 문자열을 본문과 가르는 데 쓴다 */
79
+ export const linkTargetSpans = (line) => {
80
+ const spans = [];
81
+ for (const m of line.matchAll(/\]\(([^)\s]+)\)/g)) {
82
+ const start = m.index + 2;
83
+ spans.push({ start, end: start + m[1].length });
84
+ }
85
+ return spans;
86
+ };
87
+ /** 새 형식 마커. 종류와 slug 를 함께 캡처한다 */
88
+ const MARKER_NEW = /PENDING::([a-z]+)::([a-z0-9][a-z0-9-]*)/g;
89
+ /** 구 `TEMP_*` 형식. slug 가 없어 큐와 묶이지 않으므로 재편에서 치환한다 */
90
+ const MARKER_LEGACY = /TEMP_(DESIGN|BALANCE|DEPS|STYLE)\b/g;
91
+ /** JSON 안 마커. 데이터에는 주석을 못 달아서 필드로 표기한다 */
92
+ const PENDING_JSON = /"_pending"\s*:\s*"([a-z]+)::([a-z0-9][a-z0-9-]*)"/g;
93
+ /** JSON 안 구 형식 마커 */
94
+ const TEMP_JSON = /"_temp"\s*:\s*"([a-z]+)"/g;
95
+ /**
96
+ * 미확정 항목. 마커와 달리 `PENDING` 접두가 없다.
97
+ *
98
+ * 세 모양을 받는다 - 관리 문서 항목은 `###` 헤딩 (`` `[slug]` ``), 문서 미확정 사항
99
+ * 절은 생성된 백링크 (`` [`slug`](...) ``), 둘 다 아닌 `li` (`` - `[slug]` ``) 는
100
+ * 낡은 형식이다. 형식 판정은 `checks/pending.ts` 가 하고 여기는 세는 일만 한다.
101
+ */
102
+ const PENDING_ITEM = /^(?:\s*-|###)\s+[`\[]+([a-z]+)::([a-z0-9][a-z0-9-]*)[`\]]+/;
103
+ /** 마크다운 링크. 대상에 공백이 없다고 보고 잡는다 */
104
+ const LINK = /\[([^\]]*)\]\(([^)\s]+)\)/g;
105
+ /** 변경 이력 표의 첫 칸 날짜 */
106
+ const CHANGELOG_DATE = /^\|\s*(\d{4}-\d{2}-\d{2})/;
107
+ /**
108
+ * 마커를 모은다. 새 형식과 구 형식을 갈라 담으므로 재편 진척을 셀 수 있다.
109
+ *
110
+ * 마크다운은 펜스 안을 건너뛰고 (템플릿이 마커 예시를 코드블록에 담는다),
111
+ * 코드와 JSON 은 전부 훑는다.
112
+ */
113
+ export const parseMarkers = (lines, kind) => {
114
+ const out = [];
115
+ const scan = (line, i) => {
116
+ for (const m of line.matchAll(MARKER_NEW))
117
+ out.push({ kind: m[1], slug: m[2], line: i + 1, legacy: false });
118
+ for (const m of line.matchAll(MARKER_LEGACY))
119
+ out.push({ kind: m[1].toLowerCase(), slug: '', line: i + 1, legacy: true });
120
+ if (kind === 'json') {
121
+ for (const m of line.matchAll(PENDING_JSON))
122
+ out.push({ kind: m[1], slug: m[2], line: i + 1, legacy: false });
123
+ for (const m of line.matchAll(TEMP_JSON))
124
+ out.push({ kind: m[1], slug: '', line: i + 1, legacy: true });
125
+ }
126
+ };
127
+ if (kind === 'md')
128
+ eachContentLine(lines, scan);
129
+ else
130
+ lines.forEach((l, i) => scan(l, i));
131
+ return out;
132
+ };
133
+ /**
134
+ * 제목 다음 `**목차**` 블록 범위. 생성기가 이 자리를 덮어쓴다.
135
+ *
136
+ * 제목 바로 아래 몇 줄만 본다 - 본문 중간의 목록을 목차로 오인하지 않기 위함이다.
137
+ * 첫 `##` 헤딩을 만나면 목차가 없는 문서로 판정한다.
138
+ */
139
+ const findTocBlock = (lines) => {
140
+ const head = lines.findIndex((l) => /^#\s+/.test(l));
141
+ if (head < 0)
142
+ return null;
143
+ for (let i = head + 1; i < Math.min(head + 6, lines.length); i++) {
144
+ if (/^#{2,}\s/.test(lines[i]))
145
+ return null;
146
+ if (!/^\*\*목차\*\*/.test(lines[i]))
147
+ continue;
148
+ // 한 줄에 몰아 쓴 인라인 나열은 그 줄이 블록 전체다. 규칙 12 위반이라
149
+ // 생성기가 목록 형태로 갈아끼운다
150
+ if (lines[i].trim() !== '**목차**')
151
+ return { start: i + 1, end: i + 1 };
152
+ let end = i;
153
+ for (let j = i + 1; j < lines.length; j++) {
154
+ if (/^\s*-\s+\[/.test(lines[j]))
155
+ end = j;
156
+ else if (lines[j].trim() === '')
157
+ continue;
158
+ else
159
+ break;
160
+ }
161
+ return { start: i + 1, end: end + 1 };
162
+ }
163
+ return null;
164
+ };
165
+ /**
166
+ * 꼬리 절 하나의 범위. 그 헤딩 다음 줄부터 다음 `##` 앞까지.
167
+ *
168
+ * 헤딩 목록에서 뽑기 때문에 시작이 끝보다 커지는 일이 구조적으로 없다. 훑으면서
169
+ * 상태로 들고 가면, 같은 이름의 절이 두 번 나올 때 시작만 덮어써져 범위가 뒤집힌다.
170
+ */
171
+ const tailRange = (headings, title, lineCount) => {
172
+ const at = headings.findIndex((h) => h.level === 2 && h.tail && h.title === title);
173
+ if (at < 0) {
174
+ return null;
175
+ }
176
+ const heading = headings[at];
177
+ const next = headings.slice(at + 1).find((h) => h.level === 2);
178
+ return { start: heading.line + 1, end: next === undefined ? lineCount : next.line - 1 };
179
+ };
180
+ /**
181
+ * 헤딩만 뽑는다.
182
+ *
183
+ * 색인과 따로 부를 수 있어야 한다. 생성기가 절을 새로 끼워 넣으면 헤딩 목록이
184
+ * 바뀌므로, 뒤따르는 생성기는 색인이 아니라 **갱신된 줄** 에서 다시 읽어야 한다.
185
+ *
186
+ * 문서 제목 (`#`) 도 담는다. 절은 아니지만 제목이 둘인 문서를 가려내야 하고,
187
+ * 절 판정은 모두 `level === 2` 로 걸러 쓴다.
188
+ */
189
+ export const parseHeadings = (lines) => {
190
+ const headings = [];
191
+ eachContentLine(lines, (line, i) => {
192
+ const h = /^(#{1,6})\s+(.*?)\s*$/.exec(line);
193
+ if (h === null)
194
+ return;
195
+ const { num, title } = splitHeadingNum(h[2]);
196
+ headings.push({
197
+ level: h[1].length,
198
+ num,
199
+ title,
200
+ raw: h[2],
201
+ anchor: slugify(h[2]),
202
+ line: i + 1,
203
+ // 꼬리 절은 최상위 절이다. 하위 절이 같은 이름을 쓰더라도 꼬리로 보지 않는다 -
204
+ // 그러면 문서 중간에서 inTail 이 켜져 뒤의 링크가 전부 꼬리로 잡힌다
205
+ tail: h[1].length === 2 && TAIL_SET.has(title),
206
+ });
207
+ });
208
+ return headings;
209
+ };
210
+ /**
211
+ * 문서 한 개를 훑어 색인 항목을 만든다. 절 참조는 별도로 해소하므로 빠져 있다.
212
+ *
213
+ * 훑으면서 들고 가는 상태는 두 개뿐이다 - 직전 헤딩 번호 (링크를 절에 귀속시킨다) 와
214
+ * 꼬리 절 진입 여부. 절 범위는 훑기가 끝난 뒤 헤딩 목록에서 뽑는다.
215
+ */
216
+ export const parseMarkdown = (path, lines) => {
217
+ const headings = parseHeadings(lines);
218
+ const headingAt = new Map(headings.map((h) => [h.line, h]));
219
+ const links = [];
220
+ const pendingItems = [];
221
+ const dated = [];
222
+ let currentSection = null;
223
+ let inTail = false;
224
+ eachContentLine(lines, (line, i) => {
225
+ // 항목은 헤딩 줄에도 올 수 있다 (관리 문서). 헤딩 분기보다 먼저 본다
226
+ const item = PENDING_ITEM.exec(line);
227
+ if (item) {
228
+ pendingItems.push({ kind: item[1], slug: item[2], line: i + 1 });
229
+ }
230
+ const h = headingAt.get(i + 1);
231
+ if (h !== undefined) {
232
+ if (h.tail)
233
+ inTail = true;
234
+ if (h.num !== null)
235
+ currentSection = h.num;
236
+ return;
237
+ }
238
+ for (const m of line.matchAll(LINK)) {
239
+ const [rawTarget, anchor] = m[2].split('#');
240
+ links.push({
241
+ label: m[1],
242
+ // `(#앵커)` 처럼 대상이 비면 자기 문서 안 링크다
243
+ target: rawTarget === '' ? null : rawTarget,
244
+ anchor: anchor ?? null,
245
+ line: i + 1,
246
+ section: currentSection,
247
+ inTail,
248
+ });
249
+ }
250
+ const date = CHANGELOG_DATE.exec(line);
251
+ if (date) {
252
+ dated.push({ line: i + 1, date: date[1] });
253
+ }
254
+ });
255
+ const changeLogRange = tailRange(headings, '변경 이력', lines.length);
256
+ // 본문에도 날짜 표가 있을 수 있어서 변경 이력 절 안의 것만 센다
257
+ const inLog = (line) => changeLogRange !== null && line >= changeLogRange.start && line <= changeLogRange.end;
258
+ return {
259
+ path,
260
+ kind: 'md',
261
+ lines,
262
+ headings,
263
+ links,
264
+ markers: parseMarkers(lines, 'md'),
265
+ pendingItems,
266
+ tocBlock: findTocBlock(lines),
267
+ refSection: tailRange(headings, '참조', lines.length),
268
+ pendingSection: tailRange(headings, '미확정 사항', lines.length),
269
+ changeLogRange,
270
+ changeLogDates: dated.filter((d) => inLog(d.line)).map((d) => d.date),
271
+ };
272
+ };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * 검사 결과 출력. 파일별로 묶고 규칙별 집계를 붙인다.
3
+ *
4
+ * **터미널 꾸미기는 이 파일에만 둔다.** 다른 곳에서 ANSI 문자열을 만들면 제어 문자가
5
+ * 소스 곳곳에 박혀 눈에 안 보이고, grep·sed 같은 도구가 그 파일을 못 다루게 된다.
6
+ */
7
+ import type { Finding } from "../types.ts";
8
+ /**
9
+ * 지적을 파일별로 묶어 출력하고 규칙별 집계를 붙인다.
10
+ *
11
+ * 종료 코드를 돌려준다 - 지적이 있으면 1. 재편이 끝나면 이 값으로 종료 게이트에 넣는다.
12
+ * 규칙별 집계가 있어야 어느 규칙이 소음을 내는지 보고 판단할 수 있다.
13
+ */
14
+ export declare const report: (findings: Finding[], summary: {
15
+ title: string;
16
+ lines: string[];
17
+ }) => number;
@@ -0,0 +1,38 @@
1
+ /** 터미널 강조. 규칙 이름을 흐리게 두어 메시지가 먼저 읽히게 한다 */
2
+ const BOLD = "\x1b[1m";
3
+ const DIM = "\x1b[2m";
4
+ const RESET = "\x1b[0m";
5
+ /**
6
+ * 지적을 파일별로 묶어 출력하고 규칙별 집계를 붙인다.
7
+ *
8
+ * 종료 코드를 돌려준다 - 지적이 있으면 1. 재편이 끝나면 이 값으로 종료 게이트에 넣는다.
9
+ * 규칙별 집계가 있어야 어느 규칙이 소음을 내는지 보고 판단할 수 있다.
10
+ */
11
+ export const report = (findings, summary) => {
12
+ console.log(`${BOLD}${summary.title}${RESET}`);
13
+ for (const line of summary.lines)
14
+ console.log(` ${line}`);
15
+ if (findings.length === 0) {
16
+ console.log(`\n${BOLD}지적 없음${RESET}`);
17
+ return 0;
18
+ }
19
+ const byFile = new Map();
20
+ for (const f of findings) {
21
+ const list = byFile.get(f.file) ?? [];
22
+ list.push(f);
23
+ byFile.set(f.file, list);
24
+ }
25
+ console.log(`\n${BOLD}지적 ${findings.length} 건${RESET}`);
26
+ for (const [file, list] of [...byFile.entries()].sort()) {
27
+ console.log(`\n ${file}`);
28
+ for (const f of list.sort((a, b) => a.line - b.line))
29
+ console.log(` ${String(f.line).padStart(5)} ${DIM}${f.rule}${RESET} ${f.message}`);
30
+ }
31
+ const byRule = new Map();
32
+ for (const f of findings)
33
+ byRule.set(f.rule, (byRule.get(f.rule) ?? 0) + 1);
34
+ console.log(`\n${BOLD}규칙별${RESET}`);
35
+ for (const [rule, n] of [...byRule.entries()].sort((a, b) => b[1] - a[1]))
36
+ console.log(` ${String(n).padStart(5)} ${rule}`);
37
+ return 1;
38
+ };
@@ -0,0 +1,21 @@
1
+ import type { FileKind, SectionRef } from "../types.ts";
2
+ /** 참조 해소에 필요한 문맥. 색인 대상 문서 목록에서 한 번 만들어 돌려 쓴다 */
3
+ export interface RefContext {
4
+ mdPaths: string[];
5
+ nameMap: Map<string, string[]>;
6
+ knownStems: Set<string>;
7
+ }
8
+ /**
9
+ * 색인 대상 문서 목록만으로 참조 해소 문맥을 만든다. 테스트에서도 이걸 쓴다.
10
+ *
11
+ * stem 은 두 글자 이하를 뺀다 - 짧은 낱말은 산문에서 우연히 겹칠 확률이 높다.
12
+ */
13
+ export declare const makeRefContext: (mdPaths: string[], ignoreDocNames?: string[]) => RefContext;
14
+ /**
15
+ * 한 파일의 절 참조를 모두 뽑아 해소한다.
16
+ *
17
+ * `battle.md §1·§4·§6` 같은 복수 절도 각 `§` 가 자기 왼쪽의 가까운 문서명에 붙으므로
18
+ * 따로 다룰 필요가 없다. 문서명을 못 찾으면 마크다운은 자기 문서 참조로 보고
19
+ * (표 안 `§4-1` 같은 것), 코드는 대상 불명으로 남긴다.
20
+ */
21
+ export declare const parseSectionRefs: (path: string, kind: FileKind, lines: string[], { mdPaths, nameMap, knownStems }: RefContext) => SectionRef[];
@@ -0,0 +1,157 @@
1
+ /**
2
+ * 절 참조 해소 - 문서에 적힌 이름을 리포 상대 경로로 푼다.
3
+ *
4
+ * 표기가 다섯 갈래로 갈려 있다. 경로 접두가 붙은 것, 파일명만 적은 것, 백틱에 감싼 것,
5
+ * 확장자를 뺀 것, 마크다운 링크를 동반한 것. 어느 쪽이든 같은 한 규칙으로 다룬다 -
6
+ * **같은 줄에서 왼쪽으로 가장 가까운 문서명** 을 대상으로 삼는다.
7
+ */
8
+ import { basename, dirname, join, normalize } from "node:path";
9
+ import { anchorLinkLabelSpans, codeSpanMask, eachContentLine, } from "./parse.js";
10
+ /** 절 참조. 중간 자리에 문자가 오는 `§1-B-1` 도 받는다 (`CLAUDE.md` §7 형태) */
11
+ const SECTION_REF = /§(\d+(?:-[0-9A-Za-z]+)*)/g;
12
+ /**
13
+ * 문서 이름 → 경로 색인. basename 과 확장자 없는 stem 양쪽으로 넣는다.
14
+ *
15
+ * 코드 주석이 `data-conventions §2` 처럼 확장자를 빼고 적는 경우가 있어서 stem 도
16
+ * 찾을 수 있어야 한다. 같은 이름의 문서가 여럿이면 (`CLAUDE.md` 가 루트와 client 에)
17
+ * 값이 여러 개 담기고, 그때는 경로가 붙어 있지 않으면 대상을 특정할 수 없다.
18
+ */
19
+ const buildNameMap = (paths) => {
20
+ const map = new Map();
21
+ const push = (key, path) => {
22
+ const list = map.get(key) ?? [];
23
+ list.push(path);
24
+ map.set(key, list);
25
+ };
26
+ for (const p of paths) {
27
+ const base = basename(p);
28
+ push(base, p);
29
+ push(base.replace(/\.md$/, ""), p);
30
+ }
31
+ return map;
32
+ };
33
+ /**
34
+ * 문서명 하나를 경로로 푼다. 적힌 형태에 따라 세 갈래로 나뉜다.
35
+ *
36
+ * 상대 경로면 참조한 문서 위치를 기준으로 풀고, 경로 조각이 있으면 접미 일치로 찾고,
37
+ * 이름만 있으면 색인에서 찾는다. 어느 쪽이든 후보가 둘 이상이면 특정하지 않는다 -
38
+ * 추측해서 붙이면 검사가 엉뚱한 문서를 대조하게 된다.
39
+ */
40
+ const resolveDocName = (raw, fromFile, mdPaths, nameMap) => {
41
+ // 상대 경로는 참조한 문서 위치를 기준으로 푼다. `../` 를 그냥 벗기면
42
+ // `../../CLAUDE.md` 가 `CLAUDE.md` 가 되어 루트와 client 중 어느 쪽인지 잃는다.
43
+ if (/^\.{1,2}\//.test(raw)) {
44
+ const resolved = normalize(join(dirname(fromFile), raw));
45
+ return mdPaths.includes(resolved)
46
+ ? { path: resolved, reason: "resolved" }
47
+ : { path: null, reason: "unknown-doc" };
48
+ }
49
+ // `spec/player.md` 처럼 경로 조각이 붙은 형태는 접미 일치로 찾는다
50
+ if (raw.includes("/")) {
51
+ const hits = mdPaths.filter((p) => p === raw || p.endsWith("/" + raw));
52
+ if (hits.length === 1)
53
+ return { path: hits[0], reason: "resolved" };
54
+ return {
55
+ path: null,
56
+ reason: hits.length > 1 ? "ambiguous-doc" : "unknown-doc",
57
+ };
58
+ }
59
+ const hits = nameMap.get(raw) ?? [];
60
+ if (hits.length === 1)
61
+ return { path: hits[0], reason: "resolved" };
62
+ return {
63
+ path: null,
64
+ reason: hits.length > 1 ? "ambiguous-doc" : "unknown-doc",
65
+ };
66
+ };
67
+ /**
68
+ * `§` 왼쪽에서 참조 대상으로 볼 문서명을 고른다. 없으면 null.
69
+ *
70
+ * **끝 위치가 가장 오른쪽인 후보를 고른다.** 시작 위치로 비교하면 `](../../CLAUDE.md)`
71
+ * 안의 stem `CLAUDE` 가 전체 경로보다 늦게 시작해 이겨버리고, 경로가 주는 판별력을 잃는다.
72
+ *
73
+ * 고른 문서명과 `§` 사이에 한글이 끼면 버린다. 그 문서명은 참조 대상이 아니라 화제다 -
74
+ * 실 참조는 사이에 공백·괄호·백틱·구분자만 온다.
75
+ */
76
+ const nearestDocName = (left, knownStems) => {
77
+ const candidates = [];
78
+ for (const named of left.matchAll(/([A-Za-z0-9_./-]+\.md)/g)) {
79
+ candidates.push({ text: named[1], end: named.index + named[1].length });
80
+ }
81
+ for (const word of left.matchAll(/([A-Za-z][A-Za-z0-9-]*)/g)) {
82
+ if (knownStems.has(word[1])) {
83
+ candidates.push({ text: word[1], end: word.index + word[1].length });
84
+ }
85
+ }
86
+ if (candidates.length === 0) {
87
+ return null;
88
+ }
89
+ const best = candidates.reduce((a, b) => (b.end > a.end ? b : a));
90
+ return /[가-힣]/.test(left.slice(best.end)) ? null : best.text;
91
+ };
92
+ /**
93
+ * 색인 대상 문서 목록만으로 참조 해소 문맥을 만든다. 테스트에서도 이걸 쓴다.
94
+ *
95
+ * stem 은 두 글자 이하를 뺀다 - 짧은 낱말은 산문에서 우연히 겹칠 확률이 높다.
96
+ */
97
+ export const makeRefContext = (mdPaths, ignoreDocNames = []) => {
98
+ const nameMap = buildNameMap(mdPaths);
99
+ const deny = new Set(ignoreDocNames);
100
+ return {
101
+ mdPaths,
102
+ nameMap,
103
+ knownStems: new Set([...nameMap.keys()].filter((k) => !k.endsWith(".md") && k.length > 2 && !deny.has(k))),
104
+ };
105
+ };
106
+ /**
107
+ * 한 파일의 절 참조를 모두 뽑아 해소한다.
108
+ *
109
+ * `battle.md §1·§4·§6` 같은 복수 절도 각 `§` 가 자기 왼쪽의 가까운 문서명에 붙으므로
110
+ * 따로 다룰 필요가 없다. 문서명을 못 찾으면 마크다운은 자기 문서 참조로 보고
111
+ * (표 안 `§4-1` 같은 것), 코드는 대상 불명으로 남긴다.
112
+ */
113
+ export const parseSectionRefs = (path, kind, lines, { mdPaths, nameMap, knownStems }) => {
114
+ const out = [];
115
+ const scan = (line, i) => {
116
+ const mask = kind === "md" ? codeSpanMask(line) : null;
117
+ const linkedSpans = kind === "md" ? anchorLinkLabelSpans(line) : [];
118
+ for (const m of line.matchAll(SECTION_REF)) {
119
+ // 라벨 안에 있으면 그 링크의 대상이 정답이다. 라벨 글자로 풀면 경로를 잃는다
120
+ const span = linkedSpans.find((s) => m.index >= s.start && m.index < s.end);
121
+ // 코드 span 안에는 마크다운 링크를 넣을 수 없다. 주석 예시를 보여주는 자리라
122
+ // 링크로 바꾸라고 요구하는 것 자체가 성립하지 않는다 (`rules.md` §3-5 가 코드
123
+ // 주석에 링크가 없다고 인정한 것과 같은 상황). 절 존재 검사는 그대로 받는다
124
+ const linked = span !== undefined || mask?.[m.index] === true;
125
+ const docName = span?.target ?? nearestDocName(line.slice(0, m.index), knownStems);
126
+ // 백틱 안에 문서명 없이 들어앉은 `§N` 은 표기법 인용이라 참조가 아니다
127
+ if (mask?.[m.index] && docName === null) {
128
+ continue;
129
+ }
130
+ if (docName === null) {
131
+ out.push({
132
+ num: m[1],
133
+ targetFile: kind === "md" ? path : null,
134
+ rawTarget: null,
135
+ reason: kind === "md" ? "resolved" : "no-doc-name",
136
+ linked,
137
+ line: i + 1,
138
+ });
139
+ continue;
140
+ }
141
+ const { path: target, reason } = resolveDocName(docName, path, mdPaths, nameMap);
142
+ out.push({
143
+ num: m[1],
144
+ targetFile: target,
145
+ rawTarget: docName,
146
+ reason,
147
+ linked,
148
+ line: i + 1,
149
+ });
150
+ }
151
+ };
152
+ if (kind === "md")
153
+ eachContentLine(lines, scan);
154
+ else
155
+ lines.forEach((l, i) => scan(l, i));
156
+ return out;
157
+ };
@@ -0,0 +1,11 @@
1
+ import type { DocIndex } from "../types.ts";
2
+ import type { SpecthreadConfig } from "../config.schema.ts";
3
+ /** 프로젝트 루트 절대 경로. 색인 경로를 여기 기준 상대 경로로 통일하는 데 쓴다 */
4
+ export declare const REPO_ROOT: string;
5
+ /**
6
+ * 색인을 만든다. 검사기와 생성기의 유일한 입력이다.
7
+ *
8
+ * 참조 해소 문맥을 먼저 만들어야 하므로 문서 목록을 두 번 본다 - 한 번은 이름 색인을
9
+ * 위해, 한 번은 실제 파싱을 위해. 코드와 JSON 은 헤딩이 없어서 빈 값으로 채운다.
10
+ */
11
+ export declare const buildIndex: (config: SpecthreadConfig) => DocIndex;