specthread 0.1.5 → 0.2.1

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 (75) hide show
  1. package/README.md +171 -66
  2. package/dist/bin/check.js +9 -34
  3. package/dist/bin/cli.js +5 -4
  4. package/dist/bin/generate.js +32 -19
  5. package/dist/bin/open-project.d.ts +5 -0
  6. package/dist/bin/open-project.js +26 -0
  7. package/dist/checks/changelog.js +5 -4
  8. package/dist/checks/headings.d.ts +0 -1
  9. package/dist/checks/headings.js +15 -6
  10. package/dist/checks/links.js +7 -4
  11. package/dist/checks/markers.d.ts +3 -1
  12. package/dist/checks/markers.js +33 -18
  13. package/dist/checks/pending.js +57 -23
  14. package/dist/checks/references.js +2 -2
  15. package/dist/checks/sections.js +3 -6
  16. package/dist/checks/style.d.ts +0 -8
  17. package/dist/checks/style.js +23 -43
  18. package/dist/checks/timestamps.js +5 -5
  19. package/dist/checks/toc.js +4 -6
  20. package/dist/commands/config-template.d.ts +8 -0
  21. package/{scaffold/config.jsonc → dist/commands/config-template.js} +48 -40
  22. package/dist/commands/init.js +121 -47
  23. package/dist/commands/upgrade-prompt.d.ts +12 -0
  24. package/dist/commands/upgrade-prompt.js +147 -0
  25. package/dist/config-loader.d.ts +44 -1
  26. package/dist/config-loader.js +219 -36
  27. package/dist/config.schema.d.ts +16 -35
  28. package/dist/config.schema.js +1 -7
  29. package/dist/constants/docs.d.ts +8 -4
  30. package/dist/constants/docs.js +8 -5
  31. package/dist/constants/exit.d.ts +12 -0
  32. package/dist/constants/exit.js +12 -0
  33. package/dist/constants/paths.d.ts +25 -0
  34. package/dist/constants/paths.js +25 -0
  35. package/dist/constants/patterns.d.ts +13 -6
  36. package/dist/constants/patterns.js +16 -6
  37. package/dist/constants/rules.d.ts +7 -3
  38. package/dist/constants/rules.js +7 -3
  39. package/dist/gen/pending-section.js +20 -16
  40. package/dist/gen/references.js +13 -9
  41. package/dist/gen/summary.d.ts +1 -1
  42. package/dist/gen/summary.js +11 -7
  43. package/dist/gen/toc.js +5 -2
  44. package/dist/run-check.d.ts +5 -0
  45. package/dist/run-check.js +35 -0
  46. package/dist/types.d.ts +6 -4
  47. package/dist/utils/anchor.d.ts +1 -1
  48. package/dist/utils/anchor.js +1 -1
  49. package/dist/utils/ignore.d.ts +2 -8
  50. package/dist/utils/ignore.js +23 -6
  51. package/dist/utils/parse.d.ts +6 -6
  52. package/dist/utils/parse.js +18 -27
  53. package/dist/utils/path-match.d.ts +19 -0
  54. package/dist/utils/path-match.js +27 -0
  55. package/dist/utils/report.d.ts +1 -7
  56. package/dist/utils/report.js +10 -3
  57. package/dist/utils/resolve.d.ts +15 -5
  58. package/dist/utils/resolve.js +63 -25
  59. package/dist/utils/root.d.ts +2 -0
  60. package/dist/utils/root.js +19 -0
  61. package/dist/utils/scan.d.ts +1 -3
  62. package/dist/utils/scan.js +28 -26
  63. package/dist/utils/scope.d.ts +37 -11
  64. package/dist/utils/scope.js +60 -24
  65. package/package.json +3 -3
  66. package/scaffold/AGENTS.md +4 -6
  67. package/scaffold/claude/skills/{check.md → check/SKILL.md} +6 -3
  68. package/scaffold/claude/skills/{gen.md → gen/SKILL.md} +5 -3
  69. package/scaffold/claude/skills/{plan-close.md → plan-close/SKILL.md} +1 -0
  70. package/scaffold/claude/skills/{plan-open.md → plan-open/SKILL.md} +1 -0
  71. package/scaffold/claude/skills/{plan-run.md → plan-run/SKILL.md} +1 -0
  72. package/scaffold/pending.md +1 -1
  73. package/scaffold/project.md +1 -1
  74. package/scaffold/rules.md +28 -27
  75. package/scaffold/templates/plan.md +3 -7
@@ -0,0 +1,19 @@
1
+ /**
2
+ * 설정에 적힌 경로와 색인 경로의 대조.
3
+ *
4
+ * skipCheck·skipRefs·work 는 모두 "이 경로 아래" 를 뜻하므로 같은 함수로 판정한다.
5
+ */
6
+ /**
7
+ * 설정에 적힌 경로를 색인 경로와 같은 형태로 만든다.
8
+ *
9
+ * 색인 경로는 루트 기준 상대 경로이고 `./` 도 끝 `/` 도 없다. 역슬래시는 `/` 로 바꾼다.
10
+ * 빈 문자열은 루트 전체다.
11
+ */
12
+ export declare const normalizeConfigPath: (raw: string) => string;
13
+ /**
14
+ * path 가 base 아래에 있는지. 디렉터리 경계로 판정한다.
15
+ *
16
+ * `docs` 는 `docs/a.md` 를 포함하고 `docs-old/a.md` 는 포함하지 않는다. 파일 경로를
17
+ * 정확히 적으면 그 파일 하나에 해당한다. base 는 정규화된 값이어야 한다.
18
+ */
19
+ export declare const underPath: (path: string, base: string) => boolean;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * 설정에 적힌 경로와 색인 경로의 대조.
3
+ *
4
+ * skipCheck·skipRefs·work 는 모두 "이 경로 아래" 를 뜻하므로 같은 함수로 판정한다.
5
+ */
6
+ /**
7
+ * 설정에 적힌 경로를 색인 경로와 같은 형태로 만든다.
8
+ *
9
+ * 색인 경로는 루트 기준 상대 경로이고 `./` 도 끝 `/` 도 없다. 역슬래시는 `/` 로 바꾼다.
10
+ * 빈 문자열은 루트 전체다.
11
+ */
12
+ export const normalizeConfigPath = (raw) => {
13
+ let p = raw.replace(/\\/g, "/").replace(/\/{2,}/g, "/");
14
+ while (p.startsWith("./"))
15
+ p = p.slice(2);
16
+ if (p === ".")
17
+ p = "";
18
+ p = p.replace(/^\/+/, "").replace(/\/+$/, "");
19
+ return p;
20
+ };
21
+ /**
22
+ * path 가 base 아래에 있는지. 디렉터리 경계로 판정한다.
23
+ *
24
+ * `docs` 는 `docs/a.md` 를 포함하고 `docs-old/a.md` 는 포함하지 않는다. 파일 경로를
25
+ * 정확히 적으면 그 파일 하나에 해당한다. base 는 정규화된 값이어야 한다.
26
+ */
27
+ export const underPath = (path, base) => base === "" || path === base || path.startsWith(`${base}/`);
@@ -1,14 +1,8 @@
1
- /**
2
- * 검사 결과 출력. 파일별로 묶고 규칙별 집계를 붙인다.
3
- *
4
- * **터미널 꾸미기는 이 파일에만 둔다.** 다른 곳에서 ANSI 문자열을 만들면 제어 문자가
5
- * 소스 곳곳에 박혀 눈에 안 보이고, grep·sed 같은 도구가 그 파일을 못 다루게 된다.
6
- */
7
1
  import type { Finding } from "../types.ts";
8
2
  /**
9
3
  * 지적을 파일별로 묶어 출력하고 규칙별 집계를 붙인다.
10
4
  *
11
- * 종료 코드를 돌려준다 - 지적이 있으면 1. 재편이 끝나면 이 값으로 종료 게이트에 넣는다.
5
+ * 종료 코드를 돌려준다 - 지적이 있으면 `EXIT.FINDINGS`.
12
6
  * 규칙별 집계가 있어야 어느 규칙이 소음을 내는지 보고 판단할 수 있다.
13
7
  */
14
8
  export declare const report: (findings: Finding[], summary: {
@@ -1,3 +1,10 @@
1
+ /**
2
+ * 검사 결과 출력. 파일별로 묶고 규칙별 집계를 붙인다.
3
+ *
4
+ * **터미널 꾸미기는 이 파일에만 둔다.** 다른 곳에서 ANSI 문자열을 만들면 제어 문자가
5
+ * 소스 곳곳에 박혀 눈에 안 보이고, grep·sed 같은 도구가 그 파일을 못 다루게 된다.
6
+ */
7
+ import { EXIT } from "../constants/exit.js";
1
8
  /** 터미널 강조. 규칙 이름을 흐리게 두어 메시지가 먼저 읽히게 한다 */
2
9
  const BOLD = "\x1b[1m";
3
10
  const DIM = "\x1b[2m";
@@ -5,7 +12,7 @@ const RESET = "\x1b[0m";
5
12
  /**
6
13
  * 지적을 파일별로 묶어 출력하고 규칙별 집계를 붙인다.
7
14
  *
8
- * 종료 코드를 돌려준다 - 지적이 있으면 1. 재편이 끝나면 이 값으로 종료 게이트에 넣는다.
15
+ * 종료 코드를 돌려준다 - 지적이 있으면 `EXIT.FINDINGS`.
9
16
  * 규칙별 집계가 있어야 어느 규칙이 소음을 내는지 보고 판단할 수 있다.
10
17
  */
11
18
  export const report = (findings, summary) => {
@@ -14,7 +21,7 @@ export const report = (findings, summary) => {
14
21
  console.log(` ${line}`);
15
22
  if (findings.length === 0) {
16
23
  console.log(`\n${BOLD}지적 없음${RESET}`);
17
- return 0;
24
+ return EXIT.OK;
18
25
  }
19
26
  const byFile = new Map();
20
27
  for (const f of findings) {
@@ -34,5 +41,5 @@ export const report = (findings, summary) => {
34
41
  console.log(`\n${BOLD}규칙별${RESET}`);
35
42
  for (const [rule, n] of [...byRule.entries()].sort((a, b) => b[1] - a[1]))
36
43
  console.log(` ${String(n).padStart(5)} ${rule}`);
37
- return 1;
44
+ return EXIT.FINDINGS;
38
45
  };
@@ -1,21 +1,31 @@
1
1
  import type { FileKind, SectionRef } from "../types.ts";
2
2
  /** 참조 해소에 필요한 문맥. 색인 대상 문서 목록에서 한 번 만들어 돌려 쓴다 */
3
3
  export interface RefContext {
4
- mdPaths: string[];
4
+ docPaths: string[];
5
5
  nameMap: Map<string, string[]>;
6
6
  knownStems: Set<string>;
7
+ /** 문서 확장자로 끝나는 파일 이름 패턴. 문서 확장자가 없으면 null */
8
+ docFile: RegExp | null;
9
+ }
10
+ export interface RefContextInput {
11
+ /** 색인 대상 문서의 리포 상대 경로 */
12
+ docPaths: string[];
13
+ /** 문서명 해소에서 제외할 이름. `config.ignoreDocNames` */
14
+ ignoreDocNames?: string[];
15
+ /** 문서 확장자. `config.fileKinds.doc` */
16
+ docExts?: string[];
7
17
  }
8
18
  /**
9
19
  * 색인 대상 문서 목록만으로 참조 해소 문맥을 만든다. 테스트에서도 이걸 쓴다.
10
20
  *
11
21
  * stem 은 두 글자 이하를 뺀다 - 짧은 낱말은 산문에서 우연히 겹칠 확률이 높다.
12
22
  */
13
- export declare const makeRefContext: (mdPaths: string[], ignoreDocNames?: string[]) => RefContext;
23
+ export declare const makeRefContext: ({ docPaths, ignoreDocNames, docExts, }: RefContextInput) => RefContext;
14
24
  /**
15
25
  * 한 파일의 절 참조를 모두 뽑아 해소한다.
16
26
  *
17
- * `battle.md §1·§4·§6` 같은 복수 절도 각 `§` 가 자기 왼쪽의 가까운 문서명에 붙으므로
18
- * 따로 다룰 필요가 없다. 문서명을 못 찾으면 마크다운은 자기 문서 참조로 보고
27
+ * `auth.md §1·§4·§6` 같은 복수 절도 각 `§` 가 자기 왼쪽에서 가장 가까운 문서명을 대상으로
28
+ * 하므로 따로 다룰 필요가 없다. 문서명을 못 찾으면 마크다운은 자기 문서 참조로 보고
19
29
  * (표 안 `§4-1` 같은 것), 코드는 대상 불명으로 남긴다.
20
30
  */
21
- export declare const parseSectionRefs: (path: string, kind: FileKind, lines: string[], { mdPaths, nameMap, knownStems }: RefContext) => SectionRef[];
31
+ export declare const parseSectionRefs: (path: string, kind: FileKind, lines: string[], { docPaths, nameMap, knownStems, docFile }: RefContext) => SectionRef[];
@@ -5,18 +5,38 @@
5
5
  * 확장자를 뺀 것, 마크다운 링크를 동반한 것. 어느 쪽이든 같은 한 규칙으로 다룬다 -
6
6
  * **같은 줄에서 왼쪽으로 가장 가까운 문서명** 을 대상으로 삼는다.
7
7
  */
8
- import { basename, dirname, join, normalize } from "node:path";
8
+ import { basename, dirname, extname, join, normalize } from "node:path";
9
+ import { DEFAULT_FILE_KINDS } from "../config.schema.js";
9
10
  import { anchorLinkLabelSpans, codeSpanMask, eachContentLine, } from "./parse.js";
10
- /** 절 참조. 중간 자리에 문자가 오는 `§1-B-1` 도 받는다 (`CLAUDE.md` §7 형태) */
11
+ /** 절 참조. 중간 자리에 문자가 오는 `§1-B-1` 도 받는다 */
11
12
  const SECTION_REF = /§(\d+(?:-[0-9A-Za-z]+)*)/g;
13
+ /** 문서 확장자를 뗀 이름. 문서 확장자가 아니면 그대로 둔다 */
14
+ const stemOf = (base, docExts) => {
15
+ const ext = extname(base).toLowerCase();
16
+ return docExts.includes(ext) ? base.slice(0, -ext.length) : base;
17
+ };
18
+ /**
19
+ * 문서 확장자로 끝나는 파일 이름 패턴. 문서 확장자가 없으면 null.
20
+ *
21
+ * 긴 확장자를 먼저 시도하고 뒤에 글자가 이어지지 않는지 본다. `.md` 만 문서일 때
22
+ * `guide.mdx` 의 앞부분을 `guide.md` 로 읽지 않기 위해서다.
23
+ */
24
+ const docFilePattern = (docExts) => {
25
+ if (docExts.length === 0)
26
+ return null;
27
+ const alts = [...docExts]
28
+ .sort((a, b) => b.length - a.length)
29
+ .map((e) => e.slice(1).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
30
+ return new RegExp(`([A-Za-z0-9_./-]+\\.(?:${alts.join("|")}))(?![A-Za-z0-9])`, "gi");
31
+ };
12
32
  /**
13
33
  * 문서 이름 → 경로 색인. basename 과 확장자 없는 stem 양쪽으로 넣는다.
14
34
  *
15
- * 코드 주석이 `data-conventions §2` 처럼 확장자를 빼고 적는 경우가 있어서 stem 도
16
- * 찾을 수 있어야 한다. 같은 이름의 문서가 여럿이면 (`CLAUDE.md` 가 루트와 client 에)
17
- * 값이 여러 개 담기고, 그때는 경로가 붙어 있지 않으면 대상을 특정할 수 없다.
35
+ * 코드 주석은 `conventions §2` 처럼 확장자를 빼고 적기도 하므로 stem 도 찾을 수 있어야
36
+ * 한다. 같은 이름의 문서가 여럿이면 (루트와 `docs/` 의 `README.md`) 값이 여러 개
37
+ * 담기고, 그때는 경로가 함께 적혀 있지 않으면 대상을 특정할 수 없다.
18
38
  */
19
- const buildNameMap = (paths) => {
39
+ const buildNameMap = (paths, docExts) => {
20
40
  const map = new Map();
21
41
  const push = (key, path) => {
22
42
  const list = map.get(key) ?? [];
@@ -26,7 +46,9 @@ const buildNameMap = (paths) => {
26
46
  for (const p of paths) {
27
47
  const base = basename(p);
28
48
  push(base, p);
29
- push(base.replace(/\.md$/, ""), p);
49
+ const stem = stemOf(base, docExts);
50
+ if (stem !== base)
51
+ push(stem, p);
30
52
  }
31
53
  return map;
32
54
  };
@@ -37,18 +59,18 @@ const buildNameMap = (paths) => {
37
59
  * 이름만 있으면 색인에서 찾는다. 어느 쪽이든 후보가 둘 이상이면 특정하지 않는다 -
38
60
  * 추측해서 붙이면 검사가 엉뚱한 문서를 대조하게 된다.
39
61
  */
40
- const resolveDocName = (raw, fromFile, mdPaths, nameMap) => {
62
+ const resolveDocName = (raw, fromFile, docPaths, nameMap) => {
41
63
  // 상대 경로는 참조한 문서 위치를 기준으로 푼다. `../` 를 그냥 벗기면
42
- // `../../CLAUDE.md` 가 `CLAUDE.md` 가 되어 루트와 client 중 어느 쪽인지 잃는다.
64
+ // `../../README.md` 가 `README.md` 가 되어 어느 디렉터리의 문서인지 알 수 없다.
43
65
  if (/^\.{1,2}\//.test(raw)) {
44
66
  const resolved = normalize(join(dirname(fromFile), raw));
45
- return mdPaths.includes(resolved)
67
+ return docPaths.includes(resolved)
46
68
  ? { path: resolved, reason: "resolved" }
47
69
  : { path: null, reason: "unknown-doc" };
48
70
  }
49
71
  // `spec/player.md` 처럼 경로 조각이 붙은 형태는 접미 일치로 찾는다
50
72
  if (raw.includes("/")) {
51
- const hits = mdPaths.filter((p) => p === raw || p.endsWith("/" + raw));
73
+ const hits = docPaths.filter((p) => p === raw || p.endsWith("/" + raw));
52
74
  if (hits.length === 1)
53
75
  return { path: hits[0], reason: "resolved" };
54
76
  return {
@@ -67,15 +89,15 @@ const resolveDocName = (raw, fromFile, mdPaths, nameMap) => {
67
89
  /**
68
90
  * `§` 왼쪽에서 참조 대상으로 볼 문서명을 고른다. 없으면 null.
69
91
  *
70
- * **끝 위치가 가장 오른쪽인 후보를 고른다.** 시작 위치로 비교하면 `](../../CLAUDE.md)`
71
- * 안의 stem `CLAUDE` 가 전체 경로보다 늦게 시작해 이겨버리고, 경로가 주는 판별력을 잃는다.
92
+ * **끝 위치가 가장 오른쪽인 후보를 고른다.** 시작 위치로 비교하면 `](../../README.md)`
93
+ * 안의 stem `README` 가 전체 경로보다 늦게 시작해서 선택되고, 경로로 구분할 수 없게 된다.
72
94
  *
73
95
  * 고른 문서명과 `§` 사이에 한글이 끼면 버린다. 그 문서명은 참조 대상이 아니라 화제다 -
74
96
  * 실 참조는 사이에 공백·괄호·백틱·구분자만 온다.
75
97
  */
76
- const nearestDocName = (left, knownStems) => {
98
+ const nearestDocName = (left, { docFile, knownStems }) => {
77
99
  const candidates = [];
78
- for (const named of left.matchAll(/([A-Za-z0-9_./-]+\.md)/g)) {
100
+ for (const named of docFile === null ? [] : left.matchAll(docFile)) {
79
101
  candidates.push({ text: named[1], end: named.index + named[1].length });
80
102
  }
81
103
  for (const word of left.matchAll(/([A-Za-z][A-Za-z0-9-]*)/g)) {
@@ -89,28 +111,37 @@ const nearestDocName = (left, knownStems) => {
89
111
  const best = candidates.reduce((a, b) => (b.end > a.end ? b : a));
90
112
  return /[가-힣]/.test(left.slice(best.end)) ? null : best.text;
91
113
  };
114
+ /**
115
+ * 링크 대상을 상대 경로 표기로 맞춘다.
116
+ *
117
+ * 링크 대상은 항상 그 문서 기준 상대 경로다. `./` 가 없는 `b.md` 를 그대로 넘기면
118
+ * 파일 이름 색인으로 찾게 되어, 같은 이름의 문서가 여럿이면 다른 문서로 풀린다.
119
+ */
120
+ const asRelativePath = (target) => /^\.{1,2}\//.test(target) ? target : `./${target}`;
92
121
  /**
93
122
  * 색인 대상 문서 목록만으로 참조 해소 문맥을 만든다. 테스트에서도 이걸 쓴다.
94
123
  *
95
124
  * stem 은 두 글자 이하를 뺀다 - 짧은 낱말은 산문에서 우연히 겹칠 확률이 높다.
96
125
  */
97
- export const makeRefContext = (mdPaths, ignoreDocNames = []) => {
98
- const nameMap = buildNameMap(mdPaths);
126
+ export const makeRefContext = ({ docPaths, ignoreDocNames = [], docExts = DEFAULT_FILE_KINDS.doc, }) => {
127
+ const exts = docExts.map((e) => e.toLowerCase());
99
128
  const deny = new Set(ignoreDocNames);
129
+ const stems = docPaths.map((p) => stemOf(basename(p), exts));
100
130
  return {
101
- mdPaths,
102
- nameMap,
103
- knownStems: new Set([...nameMap.keys()].filter((k) => !k.endsWith(".md") && k.length > 2 && !deny.has(k))),
131
+ docPaths,
132
+ nameMap: buildNameMap(docPaths, exts),
133
+ knownStems: new Set(stems.filter((k) => k.length > 2 && !deny.has(k))),
134
+ docFile: docFilePattern(exts),
104
135
  };
105
136
  };
106
137
  /**
107
138
  * 한 파일의 절 참조를 모두 뽑아 해소한다.
108
139
  *
109
- * `battle.md §1·§4·§6` 같은 복수 절도 각 `§` 가 자기 왼쪽의 가까운 문서명에 붙으므로
110
- * 따로 다룰 필요가 없다. 문서명을 못 찾으면 마크다운은 자기 문서 참조로 보고
140
+ * `auth.md §1·§4·§6` 같은 복수 절도 각 `§` 가 자기 왼쪽에서 가장 가까운 문서명을 대상으로
141
+ * 하므로 따로 다룰 필요가 없다. 문서명을 못 찾으면 마크다운은 자기 문서 참조로 보고
111
142
  * (표 안 `§4-1` 같은 것), 코드는 대상 불명으로 남긴다.
112
143
  */
113
- export const parseSectionRefs = (path, kind, lines, { mdPaths, nameMap, knownStems }) => {
144
+ export const parseSectionRefs = (path, kind, lines, { docPaths, nameMap, knownStems, docFile }) => {
114
145
  const out = [];
115
146
  const scan = (line, i) => {
116
147
  const mask = kind === "doc" ? codeSpanMask(line) : null;
@@ -122,7 +153,14 @@ export const parseSectionRefs = (path, kind, lines, { mdPaths, nameMap, knownSte
122
153
  // 링크로 바꾸라고 요구하는 것 자체가 성립하지 않는다 (`rules.md` §3-5 가 코드
123
154
  // 주석에 링크가 없다고 인정한 것과 같은 상황). 절 존재 검사는 그대로 받는다
124
155
  const linked = span !== undefined || mask?.[m.index] === true;
125
- const docName = span?.target ?? nearestDocName(line.slice(0, m.index), knownStems);
156
+ // 같은 문서 앵커 (`(#...)`) 는 대상 경로가 비어 있다. 자기 문서 참조다
157
+ if (span?.target === "") {
158
+ out.push({ num: m[1], targetFile: path, rawTarget: null, reason: "resolved", linked, line: i + 1 });
159
+ continue;
160
+ }
161
+ const docName = span === undefined
162
+ ? nearestDocName(line.slice(0, m.index), { docFile, knownStems })
163
+ : asRelativePath(span.target);
126
164
  // 백틱 안에 문서명 없이 들어앉은 `§N` 은 표기법 인용이라 참조가 아니다
127
165
  if (mask?.[m.index] && docName === null) {
128
166
  continue;
@@ -138,7 +176,7 @@ export const parseSectionRefs = (path, kind, lines, { mdPaths, nameMap, knownSte
138
176
  });
139
177
  continue;
140
178
  }
141
- const { path: target, reason } = resolveDocName(docName, path, mdPaths, nameMap);
179
+ const { path: target, reason } = resolveDocName(docName, path, docPaths, nameMap);
142
180
  out.push({
143
181
  num: m[1],
144
182
  targetFile: target,
@@ -0,0 +1,2 @@
1
+ /** start 에서 위로 올라가며 설정 파일이 있는 디렉터리를 찾는다. 없으면 null */
2
+ export declare const findRoot: (start?: string) => string | null;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * 프로젝트 루트 찾기.
3
+ *
4
+ * 설정 파일이 있는 디렉터리가 루트다. 하위 디렉터리에서 실행해도 같은 범위를 검사한다.
5
+ */
6
+ import { existsSync } from "node:fs";
7
+ import { dirname, join, resolve } from "node:path";
8
+ import { CONFIG_PATH } from "../constants/paths.js";
9
+ /** start 에서 위로 올라가며 설정 파일이 있는 디렉터리를 찾는다. 없으면 null */
10
+ export const findRoot = (start = process.cwd()) => {
11
+ let dir = resolve(start);
12
+ while (!existsSync(join(dir, CONFIG_PATH))) {
13
+ const parent = dirname(dir);
14
+ if (parent === dir)
15
+ return null;
16
+ dir = parent;
17
+ }
18
+ return dir;
19
+ };
@@ -1,7 +1,5 @@
1
1
  import type { DocIndex, FileKind } from "../types.ts";
2
2
  import type { FileKindsConfig, SpecthreadConfig } from "../config.schema.ts";
3
- /** 프로젝트 루트 절대 경로. 색인 경로를 여기 기준 상대 경로로 통일하는 데 쓴다 */
4
- export declare const REPO_ROOT: string;
5
3
  /** config.fileKinds 에서 확장자 → kind 역매핑을 만든다 */
6
4
  export declare const buildExtMap: (kinds: FileKindsConfig) => Map<string, FileKind>;
7
5
  /** doc 확장자 Set. 링크 대상이 문서인지 판정할 때 쓴다 */
@@ -12,4 +10,4 @@ export declare const docExtSet: (kinds: FileKindsConfig) => Set<string>;
12
10
  * 참조 해소 문맥을 먼저 만들어야 하므로 문서 목록을 두 번 본다 - 한 번은 이름 색인을
13
11
  * 위해, 한 번은 실제 파싱을 위해. 코드와 JSON 은 헤딩이 없어서 빈 값으로 채운다.
14
12
  */
15
- export declare const buildIndex: (config: SpecthreadConfig) => DocIndex;
13
+ export declare const buildIndex: (root: string, config: SpecthreadConfig) => DocIndex;
@@ -4,12 +4,11 @@
4
4
  * 검사기와 생성기가 모두 이 색인 하나를 쓴다.
5
5
  */
6
6
  import { readFileSync, readdirSync, statSync, existsSync } from "node:fs";
7
- import { join, relative, normalize } from "node:path";
7
+ import { join, relative, sep } from "node:path";
8
+ import { CONVENTION_FILES } from "../constants/paths.js";
8
9
  import { parseIgnoredLines } from "./ignore.js";
9
10
  import { parseMarkdown, parseMarkers } from "./parse.js";
10
11
  import { makeRefContext, parseSectionRefs } from "./resolve.js";
11
- /** 프로젝트 루트 절대 경로. 색인 경로를 여기 기준 상대 경로로 통일하는 데 쓴다 */
12
- export const REPO_ROOT = normalize(process.cwd());
13
12
  /** config.fileKinds 에서 확장자 → kind 역매핑을 만든다 */
14
13
  export const buildExtMap = (kinds) => {
15
14
  const map = new Map();
@@ -44,16 +43,16 @@ const walk = (dir, out = []) => {
44
43
  return out;
45
44
  };
46
45
  /**
47
- * config.path 에서 대상 파일을 모은다.
46
+ * config.path 에서 대상 파일을 모은다. 규약 파일은 `path` 에 없어도 더한다.
48
47
  *
49
48
  * 값이 디렉터리면 재귀 스캔, 파일이면 직접 로드. 파싱 전략은 확장자로 결정한다.
50
- * 인식하지 못하는 확장자는 건너뛴다.
49
+ * 인식하지 못하는 확장자는 건너뛴다. 색인 경로는 OS 와 관계없이 `/` 로 잇는다.
51
50
  */
52
- const collectTargets = (pathConfig, extMap) => {
51
+ const collectTargets = (root, pathConfig, extMap) => {
53
52
  const out = [];
54
53
  const seen = new Set();
55
54
  const add = (abs) => {
56
- const rel = relative(REPO_ROOT, abs);
55
+ const rel = relative(root, abs).split(sep).join("/");
57
56
  if (seen.has(rel))
58
57
  return;
59
58
  const kind = kindFromPath(rel, extMap);
@@ -62,18 +61,17 @@ const collectTargets = (pathConfig, extMap) => {
62
61
  seen.add(rel);
63
62
  out.push({ path: rel, kind });
64
63
  };
65
- for (const paths of Object.values(pathConfig)) {
66
- for (const entry of paths) {
67
- const abs = join(REPO_ROOT, entry);
68
- if (!existsSync(abs))
69
- continue;
70
- if (statSync(abs).isDirectory()) {
71
- for (const file of walk(abs))
72
- add(file);
73
- }
74
- else {
75
- add(abs);
76
- }
64
+ const entries = [...Object.values(pathConfig).flat(), ...CONVENTION_FILES];
65
+ for (const entry of entries) {
66
+ const abs = join(root, entry);
67
+ if (!existsSync(abs))
68
+ continue;
69
+ if (statSync(abs).isDirectory()) {
70
+ for (const file of walk(abs))
71
+ add(file);
72
+ }
73
+ else {
74
+ add(abs);
77
75
  }
78
76
  }
79
77
  return out;
@@ -84,16 +82,20 @@ const collectTargets = (pathConfig, extMap) => {
84
82
  * 참조 해소 문맥을 먼저 만들어야 하므로 문서 목록을 두 번 본다 - 한 번은 이름 색인을
85
83
  * 위해, 한 번은 실제 파싱을 위해. 코드와 JSON 은 헤딩이 없어서 빈 값으로 채운다.
86
84
  */
87
- export const buildIndex = (config) => {
85
+ export const buildIndex = (root, config) => {
88
86
  const extMap = buildExtMap(config.fileKinds);
89
- const targets = collectTargets(config.path, extMap);
90
- const mdPaths = targets.filter((t) => t.kind === "doc").map((t) => t.path);
91
- const ctx = makeRefContext(mdPaths, config.ignoreDocNames);
87
+ const targets = collectTargets(root, config.path, extMap);
88
+ const docPaths = targets.filter((t) => t.kind === "doc").map((t) => t.path);
89
+ const ctx = makeRefContext({
90
+ docPaths,
91
+ ignoreDocNames: config.ignoreDocNames,
92
+ docExts: config.fileKinds.doc,
93
+ });
92
94
  const files = new Map();
93
95
  for (const { path, kind } of targets) {
94
- const lines = readFileSync(join(REPO_ROOT, path), "utf8").split("\n");
96
+ const lines = readFileSync(join(root, path), "utf8").split("\n");
95
97
  const sectionRefs = parseSectionRefs(path, kind, lines, ctx);
96
- const ignored = parseIgnoredLines(lines);
98
+ const ignored = parseIgnoredLines(lines, kind);
97
99
  if (kind === "doc") {
98
100
  files.set(path, { ...parseMarkdown(path, lines), sectionRefs, ignored });
99
101
  }
@@ -116,5 +118,5 @@ export const buildIndex = (config) => {
116
118
  });
117
119
  }
118
120
  }
119
- return { files, docsByName: ctx.nameMap, config };
121
+ return { root, files, docsByName: ctx.nameMap, config };
120
122
  };
@@ -3,15 +3,14 @@
3
3
  *
4
4
  * 변경 이력 절은 과거 상태를 적은 곳이다. 지워진 문서를 가리키는 것이 정상이므로
5
5
  * 링크·절 참조 검사에서 뺀다. 지키게 하면 이력을 고쳐 써야 하는데, 그건
6
- * [`docs/system/rules.md`](../../docs/system/rules.md) §2-1 이 이력에 사건 기록을
7
- * 남기라고 한 것과 어긋난다. 참조 절과 미확정 사항 절은 현재 상태라 검사한다.
6
+ * `specthread/rules.md` §2-4 가 이력에 사건 기록을 남기라고 한 것과 어긋난다.
7
+ * 참조 절과 미확정 사항 절은 현재 상태라 검사한다.
8
8
  */
9
9
  import type { SpecthreadConfig } from "../config.schema.ts";
10
+ import type { RuleGroup, RuleId } from "../constants/rules.ts";
10
11
  import type { Finding, Heading, IndexedFile } from "../types.ts";
11
12
  /** 변경 이력 절 안의 줄인지 */
12
13
  export declare const inChangeLog: (file: IndexedFile, line: number) => boolean;
13
- /** 규칙을 적용할 파일인지. skipCheck 의 string 항목(경로 접두사)에 걸리면 제외 */
14
- export declare const isCheckTarget: (path: string, config: SpecthreadConfig) => boolean;
15
14
  /**
16
15
  * 목차 블록 안의 줄인지.
17
16
  *
@@ -27,6 +26,14 @@ export declare const inToc: (file: IndexedFile, line: number) => boolean;
27
26
  * 기계 생성물이 스스로 깨진 참조로 잡힌다.
28
27
  */
29
28
  export declare const inRefSection: (file: IndexedFile, line: number) => boolean;
29
+ /**
30
+ * 미확정 사항 절 안의 줄인지.
31
+ *
32
+ * 관리 문서 항목의 제목을 옮겨 온 생성 뷰다. 제목 안의 링크·절 참조·날짜는 관리 문서 기준으로
33
+ * 적힌 것이라, 이 문서 기준으로 검사하면 이 문서에서는 고칠 수 없는 지적이 된다. 원문은
34
+ * 관리 문서에서 검사한다.
35
+ */
36
+ export declare const inPendingSection: (file: IndexedFile, line: number) => boolean;
30
37
  /**
31
38
  * 헤딩 줄인지.
32
39
  *
@@ -34,18 +41,37 @@ export declare const inRefSection: (file: IndexedFile, line: number) => boolean;
34
41
  * 규칙 1 위반이라 그 규칙을 보는 검사가 따로 잡아야 한다.
35
42
  */
36
43
  export declare const isHeadingLine: (file: IndexedFile, line: number) => boolean;
37
- /** 규칙을 적용할 마크다운 문서인지. 검사기와 생성기가 같은 기준으로 걸러야 한다 */
38
- export declare const isTargetDoc: (file: IndexedFile, config: SpecthreadConfig) => boolean;
39
- /** 참조 절을 생성·검사할 문서인지. skipRefs 에 등록된 경로는 제외한다 */
44
+ /** 마크다운 문서인지. 헤딩·목차·꼬리 절을 갖는 것은 문서뿐이다 */
45
+ export declare const isDoc: (file: IndexedFile) => boolean;
46
+ /** 작업 문서인지. 흡수 후 사라지므로 미확정 사항 절을 만들지 않는다 */
47
+ export declare const isWorkDoc: (path: string, config: SpecthreadConfig) => boolean;
48
+ /** 참조 절을 생성·검사할 문서인지. skipRefs 경로 아래의 문서는 제외한다 */
40
49
  export declare const wantsRefSection: (file: IndexedFile, config: SpecthreadConfig) => boolean;
41
50
  /** 문서 제목 헤딩 목록. 하나여야 정상이다 */
42
51
  export declare const titleHeadings: (file: IndexedFile) => Heading[];
43
52
  /** 문서 제목의 헤딩. 하나가 아니면 null */
44
53
  export declare const singleTitle: (file: IndexedFile) => Heading | null;
45
54
  /**
46
- * skipCheck 의 객체 항목에 걸리는 지적인지.
55
+ * 꼬리 절이 참조 → 미확정 사항 → 변경 이력 순서인지. 없는 절은 건너뛴다.
56
+ *
57
+ * 생성기는 원본 줄 번호로 범위를 교체하며 이 순서를 전제한다.
58
+ */
59
+ export declare const tailOrderOk: (headings: Heading[]) => boolean;
60
+ /** 규칙 id 의 군 */
61
+ export declare const groupOf: (rule: RuleId) => RuleGroup;
62
+ /**
63
+ * 이 파일에서 유지할 규칙군. null 이면 전부, 빈 집합이면 하나도 없음.
64
+ *
65
+ * skipCheck 문자열 항목은 `{ path, only: [] }` 와 같다. 기본 제외가 앞에 붙는다.
66
+ * 여러 항목이 걸리면 모두 허용하는 군만 남는다.
67
+ */
68
+ export declare const allowedGroups: (path: string, config: SpecthreadConfig) => Set<RuleGroup> | null;
69
+ /** 이 파일에서 이 군을 검사·생성하는지 */
70
+ export declare const groupAllowed: (path: string, group: RuleGroup, config: SpecthreadConfig) => boolean;
71
+ /**
72
+ * skipCheck 에 걸려 버릴 지적인지.
47
73
  *
48
- * `{ path, only }` 는 해당 경로에서 `only` 에 나열된 규칙군만 유지한다는 뜻이다.
49
- * 그 밖의 규칙군에 속하는 지적은 여기서 걸러진다.
74
+ * 지적이 달린 파일 기준으로 판정한다. 색인 단계에서 파일을 빼면 그 파일을 가리키는 링크·절
75
+ * 참조와 마커 집계가 함께 사라진다.
50
76
  */
51
- export declare const isWorkExempt: (finding: Finding, config: SpecthreadConfig) => boolean;
77
+ export declare const isSkipped: (finding: Finding, config: SpecthreadConfig) => boolean;
@@ -1,16 +1,16 @@
1
+ import { TAIL_NAMES } from "../constants/docs.js";
2
+ import { DEFAULT_EXCLUDES } from "../constants/paths.js";
3
+ import { underPath } from "./path-match.js";
4
+ const inRange = (range, line) => range !== null && line >= range.start && line <= range.end;
1
5
  /** 변경 이력 절 안의 줄인지 */
2
- export const inChangeLog = (file, line) => file.changeLogRange !== null &&
3
- line >= file.changeLogRange.start &&
4
- line <= file.changeLogRange.end;
5
- /** 규칙을 적용할 파일인지. skipCheck 의 string 항목(경로 접두사)에 걸리면 제외 */
6
- export const isCheckTarget = (path, config) => !config.skipCheck.some((entry) => typeof entry === "string" && path.startsWith(entry));
6
+ export const inChangeLog = (file, line) => inRange(file.changeLogRange, line);
7
7
  /**
8
8
  * 목차 블록 안의 줄인지.
9
9
  *
10
10
  * 목차는 헤딩을 복사해 기계가 만든다. 제목에 `§` 가 들어 있으면 목차에도 실려
11
11
  * 같은 지적이 두 번 나온다. 생성물은 원본만 검사한다.
12
12
  */
13
- export const inToc = (file, line) => file.tocBlock !== null && line >= file.tocBlock.start && line <= file.tocBlock.end;
13
+ export const inToc = (file, line) => inRange(file.tocBlock, line);
14
14
  /**
15
15
  * 참조 절 안의 줄인지.
16
16
  *
@@ -18,9 +18,15 @@ export const inToc = (file, line) => file.tocBlock !== null && line >= file.tocB
18
18
  * 같은 줄 왼쪽 문서명을 대상으로 삼는 해소 규칙과 방향이 반대다. 그대로 두면
19
19
  * 기계 생성물이 스스로 깨진 참조로 잡힌다.
20
20
  */
21
- export const inRefSection = (file, line) => file.refSection !== null &&
22
- line >= file.refSection.start &&
23
- line <= file.refSection.end;
21
+ export const inRefSection = (file, line) => inRange(file.refSection, line);
22
+ /**
23
+ * 미확정 사항 절 안의 줄인지.
24
+ *
25
+ * 관리 문서 항목의 제목을 옮겨 온 생성 뷰다. 제목 안의 링크·절 참조·날짜는 관리 문서 기준으로
26
+ * 적힌 것이라, 이 문서 기준으로 검사하면 이 문서에서는 고칠 수 없는 지적이 된다. 원문은
27
+ * 관리 문서에서 검사한다.
28
+ */
29
+ export const inPendingSection = (file, line) => inRange(file.pendingSection, line);
24
30
  /**
25
31
  * 헤딩 줄인지.
26
32
  *
@@ -28,10 +34,12 @@ export const inRefSection = (file, line) => file.refSection !== null &&
28
34
  * 규칙 1 위반이라 그 규칙을 보는 검사가 따로 잡아야 한다.
29
35
  */
30
36
  export const isHeadingLine = (file, line) => file.headings.some((h) => h.line === line);
31
- /** 규칙을 적용할 마크다운 문서인지. 검사기와 생성기가 같은 기준으로 걸러야 한다 */
32
- export const isTargetDoc = (file, config) => file.kind === 'doc' && isCheckTarget(file.path, config);
33
- /** 참조 절을 생성·검사할 문서인지. skipRefs 에 등록된 경로는 제외한다 */
34
- export const wantsRefSection = (file, config) => isTargetDoc(file, config) && !config.skipRefs.includes(file.path);
37
+ /** 마크다운 문서인지. 헤딩·목차·꼬리 절을 갖는 것은 문서뿐이다 */
38
+ export const isDoc = (file) => file.kind === "doc";
39
+ /** 작업 문서인지. 흡수 후 사라지므로 미확정 사항 절을 만들지 않는다 */
40
+ export const isWorkDoc = (path, config) => underPath(path, config.work);
41
+ /** 참조 절을 생성·검사할 문서인지. skipRefs 경로 아래의 문서는 제외한다 */
42
+ export const wantsRefSection = (file, config) => isDoc(file) && !config.skipRefs.some((base) => underPath(file.path, base));
35
43
  /** 문서 제목 헤딩 목록. 하나여야 정상이다 */
36
44
  export const titleHeadings = (file) => file.headings.filter((h) => h.level === 1);
37
45
  /** 문서 제목의 헤딩. 하나가 아니면 null */
@@ -40,16 +48,44 @@ export const singleTitle = (file) => {
40
48
  return titles.length === 1 ? titles[0] : null;
41
49
  };
42
50
  /**
43
- * skipCheck 의 객체 항목에 걸리는 지적인지.
51
+ * 꼬리 절이 참조 → 미확정 사항 → 변경 이력 순서인지. 없는 절은 건너뛴다.
52
+ *
53
+ * 생성기는 원본 줄 번호로 범위를 교체하며 이 순서를 전제한다.
54
+ */
55
+ export const tailOrderOk = (headings) => {
56
+ const order = headings
57
+ .filter((h) => h.level === 2 && h.tail)
58
+ .map((h) => TAIL_NAMES.indexOf(h.title));
59
+ return order.every((n, i) => i === 0 || n > order[i - 1]);
60
+ };
61
+ /** 규칙 id 의 군 */
62
+ export const groupOf = (rule) => rule.split("/")[0];
63
+ /**
64
+ * 이 파일에서 유지할 규칙군. null 이면 전부, 빈 집합이면 하나도 없음.
65
+ *
66
+ * skipCheck 문자열 항목은 `{ path, only: [] }` 와 같다. 기본 제외가 앞에 붙는다.
67
+ * 여러 항목이 걸리면 모두 허용하는 군만 남는다.
68
+ */
69
+ export const allowedGroups = (path, config) => {
70
+ let allowed = null;
71
+ for (const entry of [...DEFAULT_EXCLUDES, ...config.skipCheck]) {
72
+ const base = typeof entry === "string" ? entry : entry.path;
73
+ if (!underPath(path, base))
74
+ continue;
75
+ const only = typeof entry === "string" ? [] : entry.only;
76
+ allowed = allowed === null ? new Set(only) : new Set(only.filter((g) => allowed?.has(g)));
77
+ }
78
+ return allowed;
79
+ };
80
+ /** 이 파일에서 이 군을 검사·생성하는지 */
81
+ export const groupAllowed = (path, group, config) => {
82
+ const allowed = allowedGroups(path, config);
83
+ return allowed === null || allowed.has(group);
84
+ };
85
+ /**
86
+ * skipCheck 에 걸려 버릴 지적인지.
44
87
  *
45
- * `{ path, only }` 는 해당 경로에서 `only` 에 나열된 규칙군만 유지한다는 뜻이다.
46
- * 그 밖의 규칙군에 속하는 지적은 여기서 걸러진다.
88
+ * 지적이 달린 파일 기준으로 판정한다. 색인 단계에서 파일을 빼면 그 파일을 가리키는 링크·절
89
+ * 참조와 마커 집계가 함께 사라진다.
47
90
  */
48
- export const isWorkExempt = (finding, config) => config.skipCheck.some((entry) => {
49
- if (typeof entry === "string")
50
- return false;
51
- if (!finding.file.startsWith(entry.path))
52
- return false;
53
- const group = finding.rule.split("/")[0];
54
- return !entry.only.some((g) => g === group);
55
- });
91
+ export const isSkipped = (finding, config) => !groupAllowed(finding.file, groupOf(finding.rule), config);