@wwkit/harness 1.0.40 → 1.0.41

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 (119) hide show
  1. package/package.json +2 -2
  2. package/skills/better-agent/SKILL.md +5 -5
  3. package/skills/better-agent/references/new-mode.md +9 -9
  4. package/skills/better-class/SKILL.md +122 -171
  5. package/skills/better-class/references/report-template.md +65 -0
  6. package/skills/better-class/references/workflow.md +32 -0
  7. package/skills/better-class/scripts/check-syntax.js +112 -0
  8. package/skills/better-class/scripts/run-tests.js +108 -0
  9. package/skills/better-skill/SKILL.md +41 -348
  10. package/skills/better-skill/references/planning_resources.md +87 -0
  11. package/skills/better-skill/references/subagent_prompts.md +24 -43
  12. package/skills/better-skill/scripts/check_input_vars.js +68 -0
  13. package/skills/better-skill/scripts/init.js +112 -0
  14. package/skills/better-skill/scripts/resolve_run_vars.js +104 -0
  15. package/skills/better-skill-test/SKILL.md +1 -1
  16. package/skills/blame-skill/SKILL.md +34 -141
  17. package/skills/blame-skill/references/planning_resources.md +79 -0
  18. package/skills/blame-skill/scripts/check_input_vars.js +62 -0
  19. package/skills/blame-skill/scripts/init.js +86 -0
  20. package/skills/blame-skill/scripts/resolve_run_vars.js +95 -0
  21. package/skills/blame-sprint-agent/SKILL.md +8 -8
  22. package/skills/blame-sprint-agent/references/demos/demo.md +1 -1
  23. package/skills/blame-sprint-agent/references/demos/fixed-traversal/references/prepare-prompt.md +1 -1
  24. package/skills/blame-sprint-agent/references/scoring-rules.md +10 -10
  25. package/skills/convert-files/SKILL.md +38 -0
  26. package/skills/convert-files/package.json +11 -0
  27. package/skills/convert-files/references/sprint_for_conversion.md +17 -0
  28. package/skills/convert-files/scripts/check_input_vars.js +54 -0
  29. package/skills/convert-files/scripts/convert.js +331 -0
  30. package/skills/convert-files/scripts/init.js +75 -0
  31. package/skills/convert-files/scripts/resolve_run_vars.js +125 -0
  32. package/skills/extract/SKILL.md +56 -110
  33. package/skills/extract/references/planning_template.md +23 -43
  34. package/skills/shared/references/common-references.md +76 -0
  35. package/skills/shared/references/failure_diagnosis.md +43 -0
  36. package/skills/shared/references/rules/blame-skill-rules.md +234 -0
  37. package/skills/shared/references/rules/blame-sprint-skill-rules.md +110 -0
  38. package/skills/shared/references/sprint-refinement.md +40 -0
  39. package/skills/shared/references/sprint_for_progress.md +24 -0
  40. package/skills/shared/references/template/planning-resources.md +58 -0
  41. package/skills/shared/references/template/skill-with-planning.md +78 -0
  42. package/skills/shared/references/template/skill-with-progress.md +68 -0
  43. package/skills/shared/references/template/skill.md +66 -0
  44. package/skills/shared/references/template/sprint-with-batch-subagent.md +94 -0
  45. package/skills/shared/references/template/sprint-with-planning.md +82 -0
  46. package/skills/shared/references/template/sprint-with-progress.md +48 -0
  47. package/skills/shared/references/template/sprint-with-subagent.md +52 -0
  48. package/skills/shared/references/template/sprint.md +43 -0
  49. package/skills/shared/references/template/subagent-prompt.md +63 -0
  50. package/skills/shared/scripts/format.md +83 -0
  51. package/skills/shared/scripts/resolve_dependencies.js +151 -0
  52. package/skills/shared/scripts/resolve_system_vars.js +80 -0
  53. package/skills/shared/scripts/template/check_input_vars.js +57 -0
  54. package/skills/shared/scripts/template/init.js +96 -0
  55. package/skills/shared/scripts/template/resolve_run_vars.js +122 -0
  56. package/skills/shared/scripts/utils.js +72 -0
  57. package/skills/translate/SKILL.md +19 -12
  58. package/skills/translate-file/SKILL.md +47 -0
  59. package/skills/translate-file/package.json +10 -0
  60. package/skills/translate-file/references/sprint_for_preprocess.md +22 -0
  61. package/skills/translate-file/references/sprint_for_teardown.md +23 -0
  62. package/skills/translate-file/references/sprint_for_translate.md +69 -0
  63. package/skills/translate-file/references/translation_prompt.md +43 -0
  64. package/skills/translate-file/scripts/check_input_vars.js +53 -0
  65. package/skills/translate-file/scripts/chunk_text.js +167 -0
  66. package/skills/translate-file/scripts/clean_text.js +121 -0
  67. package/skills/translate-file/scripts/extract.js +98 -0
  68. package/skills/translate-file/scripts/generate_review.js +155 -0
  69. package/skills/translate-file/scripts/init.js +86 -0
  70. package/skills/translate-file/scripts/merge_results.js +119 -0
  71. package/skills/translate-file/scripts/resolve_run_vars.js +120 -0
  72. package/skills/translate-file/scripts/verify_chunk.js +144 -0
  73. package/skills/better-skill/references/new_mode.md +0 -109
  74. package/skills/better-skill/references/progress_template.md +0 -58
  75. package/skills/blame-feedback-skill/SKILL.md +0 -309
  76. package/skills/blame-feedback-skill/demo.md +0 -23
  77. package/skills/blame-feedback-skill/references/progress_template.md +0 -36
  78. package/skills/blame-feedback-skill/references/scoring_rules.md +0 -76
  79. package/skills/blame-release-skill/SKILL.md +0 -293
  80. package/skills/blame-release-skill/demo.md +0 -45
  81. package/skills/blame-release-skill/references/demos/fixed-traversal/SKILL.md +0 -355
  82. package/skills/blame-release-skill/references/demos/fixed-traversal/references/failure_diagnosis.md +0 -19
  83. package/skills/blame-release-skill/references/demos/fixed-traversal/references/global_review_rules.md +0 -23
  84. package/skills/blame-release-skill/references/demos/fixed-traversal/references/planning_template.md +0 -198
  85. package/skills/blame-release-skill/references/demos/fixed-traversal/references/prepare_prompt.md +0 -28
  86. package/skills/blame-release-skill/references/demos/fixed-traversal/references/progress_template.md +0 -32
  87. package/skills/blame-release-skill/references/demos/fixed-traversal/references/resume_detection.md +0 -19
  88. package/skills/blame-release-skill/references/demos/fixed-traversal/references/translation_prompt.md +0 -32
  89. package/skills/blame-release-skill/references/demos/fixed-traversal/scripts/chunk_bilingual.js +0 -86
  90. package/skills/blame-release-skill/references/demos/fixed-traversal/scripts/init_progress.js +0 -63
  91. package/skills/blame-release-skill/references/demos/multi-override/SKILL.md +0 -393
  92. package/skills/blame-release-skill/references/demos/multi-override/references/planning_template.md +0 -233
  93. package/skills/blame-release-skill/references/demos/multi-override/references/progress_template.md +0 -31
  94. package/skills/blame-release-skill/references/demos/multi-override/references/review_rules.md +0 -38
  95. package/skills/blame-release-skill/references/demos/multi-override/scripts/analyze_file.js +0 -68
  96. package/skills/blame-release-skill/references/demos/multi-override/scripts/calc_score.js +0 -55
  97. package/skills/blame-release-skill/references/demos/routing/SKILL.md +0 -327
  98. package/skills/blame-release-skill/references/demos/routing/references/html_rules.md +0 -34
  99. package/skills/blame-release-skill/references/demos/routing/references/markdown_rules.md +0 -33
  100. package/skills/blame-release-skill/references/demos/routing/references/plain_rules.md +0 -28
  101. package/skills/blame-release-skill/references/demos/routing/references/planning_template.md +0 -204
  102. package/skills/blame-release-skill/references/demos/routing/references/progress_template.md +0 -29
  103. package/skills/blame-release-skill/references/demos/routing/scripts/validate_output.js +0 -38
  104. package/skills/blame-release-skill/references/planning_template.md +0 -114
  105. package/skills/blame-release-skill/references/progress_template.md +0 -31
  106. package/skills/blame-release-skill/references/scoring_rules.md +0 -72
  107. package/skills/blame-skill/references/scoring-rules.md +0 -231
  108. package/skills/blame-sprint-skill/SKILL.md +0 -259
  109. package/skills/blame-sprint-skill/references/demos/demo.md +0 -46
  110. package/skills/blame-sprint-skill/references/demos/single-list/SKILL.md +0 -181
  111. package/skills/blame-sprint-skill/references/demos/single-list/references/translation_rules.md +0 -35
  112. package/skills/blame-sprint-skill/references/demos/single-list/scripts/verify_chunk.js +0 -56
  113. package/skills/blame-sprint-skill/references/demos/single-list-internal-loop/SKILL.md +0 -208
  114. package/skills/blame-sprint-skill/references/demos/single-list-internal-loop/references/glossary_rules.md +0 -31
  115. package/skills/blame-sprint-skill/references/demos/single-list-internal-loop/scripts/count_terms.js +0 -59
  116. package/skills/blame-sprint-skill/references/scoring_rules.md +0 -104
  117. package/skills/blame-sprint-skill/references/state_management_rules.md +0 -194
  118. package/skills/extract/README.md +0 -86
  119. package/skills/extract/references/progress_template.md +0 -30
@@ -0,0 +1,69 @@
1
+ # Sprint Backlog for translate
2
+
3
+ ## Sprint Goal
4
+ Chunk the clean text, then translate a batch of chunks in parallel.
5
+
6
+ ## Sprint Backlog Items
7
+
8
+ ### Item1: Append self to progress
9
+ - Implement: Append `Sprint for translate,pending` to `{{run_dir}}/progress.csv`
10
+ - DoD check: The progress file contains the current sprint status
11
+
12
+ ### Item2: Create chunks
13
+ - Implement: run `node '{{skill_dir}}/scripts/chunk_text.js' '{{run_dir}}/source.txt' '{{run_dir}}/chunks' {{chunk_words}}`
14
+ - DoD check: Chunk files are saved to `{{run_dir}}/chunks`
15
+
16
+ ### Item3: Create chunk progress file
17
+ - Implement: Create `{{run_dir}}/chunk_progress.csv` and write:
18
+
19
+ ```
20
+ chunk_id,status,retry
21
+ p001,pending,0
22
+ p002,pending,0
23
+ ...
24
+ ```
25
+
26
+ - DoD check: `chunk_progress.csv` is created and contains chunk statuses
27
+
28
+ ### Item4: Determine chunk batch [Loop body start]
29
+ - Implement: Read up to `{{max_parallel}}` chunks from `{{run_dir}}/chunk_progress.csv` that are not `translated` or have `failed` status with `retry` < 3, in order
30
+ - Short-circuit: skip the loop body, proceed directly to **Merge output** when no chunks are pending translation
31
+ - DoD check: The chunk batch list is determined
32
+
33
+ ### Item5: Prepare subagent prompt
34
+ - Implement: Read the subagent prompt from `{{skill_dir}}/references/translation_prompt.md`. If any chunk has `failed` status, read `{{shared_dir}}/references/failure_diagnosis.md` to locate the issue and adjust the prompt accordingly
35
+ - DoD check: The subagent prompt is determined
36
+
37
+ ### Item6: Prepare variable table
38
+ - Implement: Create the subagent variable table:
39
+
40
+ | Variable | Value | Description |
41
+ |---|---|---|
42
+ | `chunk_id` | chunk ID (per chunk) | from the chunk batch list |
43
+ | `run_dir` | `{{run_dir}}` | run data directory |
44
+ | `language` | `{{language}}` | target language |
45
+ | `skill_dir` | `{{skill_dir}}` | skill directory |
46
+
47
+ - DoD check: All variable values or resolution rules are determined
48
+
49
+ ### Item7: Parallel translation
50
+ - Implement: Dispatch one subagent per chunk, all in a single message. Parameters: `subagent_type: "general"`, `description: "Translate chunk {{chunk_id}}"`, `prompt: <subagent prompt> \n Variable table: <subagent variable table>`
51
+ - DoD check: All chunk translation results have been received
52
+
53
+ ### Item8: Update chunk status [Loop body end]
54
+ - Implement: For each chunk in the batch, check `{{run_dir}}/results/{{chunk_id}}.md` and update `{{run_dir}}/chunk_progress.csv`:
55
+ - Exists and not empty: update to `{{chunk_id}},translated,<retry>`
56
+ - Missing or empty: update to `{{chunk_id}},failed,<retry+1>`; do not retry failed chunks
57
+ - DoD check: All chunk statuses in the batch have been updated
58
+
59
+ ### Item9: Loop back [Loop back]
60
+ - Implement: Jump back to [Loop body start] for the next batch
61
+ - DoD check: Control has returned to the loop body start
62
+
63
+ ### Item10: Merge output
64
+ - Implement: run `node '{{skill_dir}}/scripts/merge_results.js' '{{run_dir}}/chunks' '{{run_dir}}/results' '{{output_dir}}' '{{run_name}}'`
65
+ - DoD check: `{{output_dir}}/{{run_name}}.txt` is generated
66
+
67
+ ### Item11: Update self status
68
+ - Implement: Update the current sprint status to `completed` in `{{run_dir}}/progress.csv`
69
+ - DoD check: The current sprint status has been updated to `completed`
@@ -0,0 +1,43 @@
1
+ You are a translator named Paul in the Scrum Team. Please achieve the Sprint Goal within one Sprint.
2
+
3
+ ## Translation Rules
4
+
5
+ | ID | Category | Rule |
6
+ |---|---|---|
7
+ | R1 | Style | **Literal translation**: do not add, remove, or alter words and content; do not change sentence order; translate sentence by sentence; do not add explanations not present in the source |
8
+ | R2 | Output contract | **Bilingual layout**: source paragraph first, translation paragraph second, separated by a blank line; headings are laid out the same as paragraphs; no formatting preserved |
9
+ | R3 | Output contract | **Output form**: output bilingual text only, no explanations, no thought process |
10
+ | R4 | Detail | **Footnote translation**: preserve the marker `[^N]`, content format `source \| translation` |
11
+ | R5 | Detail | **Source file error correction**: proactively identify OCR and other source file errors, fix during translation, use the corrected text in the source paragraph |
12
+ | R6 | Detail | **[CONT] marker**: a marker that may appear at the end of a chunk indicating an incomplete sentence. Preserve it in both languages |
13
+
14
+ ## Sprint Goal
15
+ Translate 1 chunk into `{{language}}` and write to the result file.
16
+
17
+ ## Sprint Increment
18
+
19
+ | Product | Type | Description | DoD |
20
+ |---|---|---|---|
21
+ | `{{run_dir}}/results/{{chunk_id}}.md` | file | Translation result (bilingual) | file exists and is not empty |
22
+
23
+ ## Sprint Backlog Items
24
+
25
+ ### Item1: Translate
26
+ - Implement: Translate `{{run_dir}}/chunks/{{chunk_id}}.txt` following the **Translation Rules** above and write directly to `{{run_dir}}/results/{{chunk_id}}.md`
27
+ - DoD check: `{{run_dir}}/results/{{chunk_id}}.md` exists and is not empty
28
+
29
+ ### Item2: Self-check
30
+ - Implement: run `node '{{skill_dir}}/scripts/verify_chunk.js' '{{run_dir}}/chunks/{{chunk_id}}.txt' '{{run_dir}}/results/{{chunk_id}}.md'`
31
+ - DoD check: Self-check result is obtained (VALID or INVALID with reasons)
32
+
33
+ ### Item3: Fix and update
34
+ - Short-circuit: skip when self-check result is VALID
35
+ - Implement: Investigate errors, fix and update `{{run_dir}}/results/{{chunk_id}}.md`. After ≤2 fix attempts, if still INVALID, stop fixing (keep the content)
36
+ - DoD check: Self-check update is complete
37
+
38
+ # Sprint Now!
39
+
40
+ Follow the Sequential workflow to implement:
41
+ 1. Sprint: Execute the **Sprint Backlog Items** one by one.
42
+ 2. Increment Check: Check that the **Sprint Increment** meets the DoD.
43
+ 3. Sprint Review: Present the **Sprint Goal** completion or non-completion process to the team in minimal steps.
@@ -0,0 +1,53 @@
1
+ /**
2
+ * check_input_vars.js — Validate the input variable (input_path) extracted from context
3
+ *
4
+ * Input: input_path (source file or directory path)
5
+ * Validation: input_path not provided / does not exist / is neither file nor directory
6
+ * Invalid: print specific error + ERR_INPUT_INVALID
7
+ * Valid: print OK_INPUT_VALID
8
+ *
9
+ * Boundary: this script only validates context-extracted input variables;
10
+ * runtime variable validation (skill_data_dir, extension, no supported files in dir, etc.)
11
+ * is handled by resolve_run_vars.js.
12
+ */
13
+
14
+ import { existsSync, statSync } from 'fs'
15
+ import { render } from '../../shared/scripts/utils.js'
16
+
17
+ const OK_OUTPUT_TEMPLATE = 'OK: 输入校验通过'
18
+ const INVALID_OUTPUT_TEMPLATE = 'INVALID: ${error}'
19
+ const ERR_INPUT_INVALID = '请提示用户输入不合法,任务结束'
20
+
21
+ export const OK_INPUT_VALID = OK_OUTPUT_TEMPLATE
22
+
23
+ /**
24
+ * Validate the context-extracted input variable input_path (pure function, testable).
25
+ * @param {string} inputPath — source file or directory path
26
+ * @returns {{ok: true} | {error: string}}
27
+ */
28
+ export function checkInputVars(inputPath) {
29
+ if (!inputPath) {
30
+ return { error: `input_path 未提供,${ERR_INPUT_INVALID}` }
31
+ }
32
+ if (!existsSync(inputPath)) {
33
+ return { error: `input_path 不存在:${inputPath},${ERR_INPUT_INVALID}` }
34
+ }
35
+ if (!statSync(inputPath).isFile() && !statSync(inputPath).isDirectory()) {
36
+ return { error: `input_path 不是文件也不是目录:${inputPath},${ERR_INPUT_INVALID}` }
37
+ }
38
+ return { ok: true }
39
+ }
40
+
41
+ const isMain = import.meta.url === `file://${process.argv[1]}`
42
+ if (isMain) {
43
+ const inputPath = process.argv[2]
44
+
45
+ const result = checkInputVars(inputPath)
46
+
47
+ if (result.error) {
48
+ console.log(render(INVALID_OUTPUT_TEMPLATE, { error: result.error }))
49
+ process.exit(0)
50
+ }
51
+
52
+ console.log(OK_OUTPUT_TEMPLATE)
53
+ }
@@ -0,0 +1,167 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * chunk_text.js — 文本分块脚本(ESM,段落感知),适配自 translate/chunk-text.js
4
+ *
5
+ * 输入:argv[2] = 源文本文件路径(source_txt_file),argv[3] = 输出目录(chunks_dir),argv[4] = 每块最大词数(默认 3000)
6
+ * 输出:p001.txt, p002.txt, ... 写入输出目录,stdout 打印总块数
7
+ *
8
+ * 分块策略:
9
+ * - PDF 文本(含 \f):按 \f 切分页面,按 chunk_words 分组
10
+ * - 纯文本(无 \f):按段落边界切分,尽量不切断段落;单段落超长时按词数硬切
11
+ * - 每块末尾检测段落是否完整(以句末标点结尾),不完整时追加 [CONT] 标记(末块不追加)
12
+ */
13
+
14
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs'
15
+ import { join } from 'path'
16
+ import { render } from '../../shared/scripts/utils.js'
17
+
18
+ // ── 输出模板(CLI stdout:status 行 + data)──
19
+ const CHUNKED_OUTPUT_TEMPLATE = 'chunked: ${count} chunks -> ${dir}'
20
+
21
+ // Count words (rough: split by whitespace)
22
+ function countWords(text) {
23
+ return text.trim().split(/\s+/).filter(w => w.length > 0).length
24
+ }
25
+
26
+ // Check if text ends with a complete sentence (sentence-ending punctuation)
27
+ function isParagraphComplete(text) {
28
+ const trimmed = text.trimEnd()
29
+ if (trimmed.length === 0) return true
30
+ // Common sentence-ending punctuation in multiple languages
31
+ return /[.!?。!?:;;]\s*$/.test(trimmed) ||
32
+ /["'」』))\]]\s*$/.test(trimmed) ||
33
+ trimmed.endsWith('[CONT]') // already marked
34
+ }
35
+
36
+ // Append [CONT] marker if last paragraph is incomplete
37
+ function markIncomplete(chunk) {
38
+ const trimmed = chunk.trimEnd()
39
+ if (trimmed.length === 0) return chunk
40
+ if (isParagraphComplete(trimmed)) return chunk
41
+ // Find last non-empty line
42
+ return chunk.replace(/\s*$/, '\n[CONT]\n')
43
+ }
44
+
45
+ // Hard-split within maxWords: prefer nearest sentence boundary (sentence-ending
46
+ // punctuation) to avoid cutting mid-sentence; fall back to word-count cut.
47
+ function splitAtBoundary(text, maxWords) {
48
+ const words = text.trim().split(/\s+/)
49
+ if (words.length <= maxWords) return { first: text.trim(), rest: '' }
50
+ let boundary = maxWords
51
+ for (let i = maxWords; i > 0; i--) {
52
+ if (/[.!?。!?:;;]["'」』))\]]?$/.test(words[i - 1])) {
53
+ boundary = i
54
+ break
55
+ }
56
+ }
57
+ return {
58
+ first: words.slice(0, boundary).join(' '),
59
+ rest: words.slice(boundary).join(' '),
60
+ }
61
+ }
62
+
63
+ /**
64
+ * 将文本分块(纯函数,无 IO)。
65
+ * @param {string} content — 源文本(含 \f 视为 PDF 分页)
66
+ * @param {number} chunkWords — 每块最大词数(默认 3000)
67
+ * @returns {string[]} chunk 文本数组(顺序即 p001..pNNN)
68
+ */
69
+ export function chunkText(content, chunkWords = 3000) {
70
+ const maxWords = chunkWords
71
+ let chunks = []
72
+
73
+ if (content.includes('\f')) {
74
+ // PDF text with form feed page breaks
75
+ const pages = content.split('\f')
76
+ let currentChunk = ''
77
+
78
+ for (let i = 0; i < pages.length; i++) {
79
+ const page = pages[i]
80
+ if (page.trim().length === 0) continue
81
+
82
+ const pageWords = countWords(page)
83
+ const wouldExceedWords = countWords(currentChunk) + pageWords > maxWords
84
+
85
+ if (wouldExceedWords && currentChunk.length > 0) {
86
+ // Mark incomplete before flushing
87
+ chunks.push(markIncomplete(currentChunk))
88
+ currentChunk = page
89
+ } else {
90
+ currentChunk += (currentChunk ? '\n' : '') + page
91
+ }
92
+ }
93
+
94
+ // Flush remaining (last chunk — don't mark [CONT], it's the end of document)
95
+ if (currentChunk.trim().length > 0) {
96
+ chunks.push(currentChunk)
97
+ }
98
+ } else {
99
+ // Plain text without page breaks — split by paragraph boundaries
100
+ const paragraphs = content.split(/\n\s*\n/) // Split on double newline (paragraph boundary)
101
+
102
+ let currentChunk = ''
103
+
104
+ for (const para of paragraphs) {
105
+ if (para.trim().length === 0) continue
106
+
107
+ const paraWords = countWords(para)
108
+ const chunkWordsNow = countWords(currentChunk)
109
+
110
+ // If adding this paragraph exceeds limit and we have content, flush
111
+ if (chunkWordsNow + paraWords > maxWords && currentChunk.length > 0) {
112
+ chunks.push(markIncomplete(currentChunk))
113
+ currentChunk = para
114
+ } else {
115
+ currentChunk += (currentChunk ? '\n\n' : '') + para
116
+ }
117
+
118
+ // If single paragraph exceeds chunk_words, hard-split it by words
119
+ while (countWords(currentChunk) > maxWords) {
120
+ const { first, rest } = splitAtBoundary(currentChunk, maxWords)
121
+ chunks.push(markIncomplete(first))
122
+ currentChunk = rest
123
+ }
124
+ }
125
+
126
+ // Flush remaining (last chunk — no [CONT])
127
+ if (currentChunk.trim().length > 0) {
128
+ chunks.push(currentChunk)
129
+ }
130
+ }
131
+
132
+ return chunks
133
+ }
134
+
135
+ // --- CLI ---
136
+
137
+ const isMain = import.meta.url === `file://${process.argv[1]}`
138
+ if (isMain) {
139
+ const args = process.argv.slice(2)
140
+
141
+ if (args.length < 2) {
142
+ console.error('usage: chunk_text.js <source_file> <output_dir> [chunk_words=3000]')
143
+ process.exit(2)
144
+ }
145
+
146
+ const sourcePath = args[0]
147
+ const outputDir = args[1]
148
+ const chunkWords = Math.max(100, parseInt(args[2] || '3000', 10)) // CLI 最小 100 词保护
149
+
150
+ if (!existsSync(sourcePath)) {
151
+ console.error(`ERROR: source file not found: ${sourcePath}`)
152
+ process.exit(2)
153
+ }
154
+
155
+ mkdirSync(outputDir, { recursive: true })
156
+
157
+ const content = readFileSync(sourcePath, 'utf-8')
158
+ const chunks = chunkText(content, chunkWords)
159
+
160
+ // Write chunk files
161
+ chunks.forEach((chunk, i) => {
162
+ const id = `p${String(i + 1).padStart(3, '0')}`
163
+ writeFileSync(join(outputDir, `${id}.txt`), chunk, 'utf-8')
164
+ })
165
+
166
+ console.log(render(CHUNKED_OUTPUT_TEMPLATE, { count: chunks.length, dir: outputDir }))
167
+ }
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * clean_text.js — PDF 提取文本清洗脚本(ESM,纯 JS,无系统依赖)
4
+ *
5
+ * 清洗 pdf-parse 提取的 source.txt 中的确定性噪声:
6
+ * 1. Tab 字符 → 空格
7
+ * 2. 独立 ^ 字符(OCR 噪声)→ 删除(保留 \f 页标记)
8
+ * 3. 行中 \f(页中断合并文本)→ 拆分为独立行
9
+ * 4. 连续空格 → 单空格
10
+ * 5. 行尾空格 → 删除
11
+ *
12
+ * 输入:argv[2] = source.txt 路径
13
+ * 输出:原地清洗,stdout 打印统计
14
+ *
15
+ * 用法:
16
+ * node clean_text.js "<source.txt>"
17
+ */
18
+
19
+ import { readFileSync, writeFileSync, existsSync } from 'fs'
20
+
21
+ // ── 输出模板(CLI stdout:status 行)──
22
+ const CLEAN_TEXT_OK = 'OK: clean-text'
23
+
24
+ /**
25
+ * 清洗文本内容,返回清洗后的内容和统计信息。
26
+ * @param {string} content — 原始文本
27
+ * @returns {{ content: string, stats: { tabs: number, carets: number, formFeeds: number } }}
28
+ */
29
+ export function cleanText(content) {
30
+ let tabCount = 0
31
+ let caretCount = 0
32
+ let formFeedSplitCount = 0
33
+
34
+ // 1. 行中 \f 拆分:将 "text\fmore" 拆为 "text\n\f\nmore"
35
+ // \f 独占一行,保留为页标记(chunk_text.js 依赖 \f 分页)
36
+ const lines = content.split('\n')
37
+ const processedLines = []
38
+
39
+ for (const line of lines) {
40
+ // 独占行的 \f 是页标记,不拆分
41
+ if (line === '\f') {
42
+ processedLines.push(line)
43
+ continue
44
+ }
45
+ if (line.includes('\f')) {
46
+ const parts = line.split('\f')
47
+ for (let i = 0; i < parts.length; i++) {
48
+ if (i > 0) {
49
+ processedLines.push('\f')
50
+ formFeedSplitCount++
51
+ }
52
+ if (parts[i].length > 0) {
53
+ processedLines.push(parts[i])
54
+ }
55
+ }
56
+ } else {
57
+ processedLines.push(line)
58
+ }
59
+ }
60
+
61
+ // 2. 逐行清洗:tab→空格、删除^、折叠空格、去行尾空格
62
+ const cleanedLines = processedLines.map(line => {
63
+ // 跳过 \f 独占行,不清洗
64
+ if (line === '\f') return line
65
+
66
+ let cleaned = line
67
+
68
+ // Tab → 空格
69
+ const tabs = (cleaned.match(/\t/g) || []).length
70
+ if (tabs > 0) {
71
+ cleaned = cleaned.replace(/\t/g, ' ')
72
+ tabCount += tabs
73
+ }
74
+
75
+ // 删除 ^ 字符(OCR 噪声,不删除 \f)
76
+ const carets = (cleaned.match(/\^/g) || []).length
77
+ if (carets > 0) {
78
+ cleaned = cleaned.replace(/\^/g, '')
79
+ caretCount += carets
80
+ }
81
+
82
+ // 折叠连续空格 → 单空格
83
+ cleaned = cleaned.replace(/ {2,}/g, ' ')
84
+
85
+ // 去行尾空格
86
+ cleaned = cleaned.replace(/\s+$/, '')
87
+
88
+ return cleaned
89
+ })
90
+
91
+ return {
92
+ content: cleanedLines.join('\n'),
93
+ stats: { tabs: tabCount, carets: caretCount, formFeeds: formFeedSplitCount },
94
+ }
95
+ }
96
+
97
+ // --- CLI ---
98
+
99
+ const isMain = import.meta.url === `file://${process.argv[1]}`
100
+
101
+ if (isMain) {
102
+ const args = process.argv.slice(2)
103
+
104
+ if (args.length < 1) {
105
+ console.error('usage: clean_text.js <source.txt>')
106
+ process.exit(2)
107
+ }
108
+
109
+ const filePath = args[0]
110
+
111
+ if (!existsSync(filePath)) {
112
+ console.error(`ERROR: source file not found: ${filePath}`)
113
+ process.exit(2)
114
+ }
115
+
116
+ const raw = readFileSync(filePath, 'utf-8')
117
+ const { content } = cleanText(raw)
118
+ writeFileSync(filePath, content, 'utf-8')
119
+
120
+ console.log(CLEAN_TEXT_OK)
121
+ }
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * extract.js — 源文件文本提取脚本(ESM,纯 JS,无系统依赖)
4
+ *
5
+ * 自动区分源文件类型(由 shared utils.js 工具判断):
6
+ * - .pdf → pdf-parse 提取(\f 分页符分隔页面),依赖由 init.js resolve_dependencies 管理
7
+ * - .txt / .md → 直接复制到输出路径
8
+ *
9
+ * 输入:argv[2] = 源文件路径,argv[3] = 输出文本文件路径
10
+ * 输出:纯文本(.pdf 以 \f 分页符分隔页面),stdout 打印行数(和页数,.pdf 时)
11
+ *
12
+ * 用法:
13
+ * node extract.js "<源文件路径>" "<output.txt>"
14
+ */
15
+
16
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
17
+ import { dirname } from 'path'
18
+ import { createRequire } from 'module'
19
+ import { render, isPdf } from '../../shared/scripts/utils.js'
20
+
21
+ const require = createRequire(import.meta.url)
22
+
23
+ // ── 输出模板(CLI stdout:status 行 + data)──
24
+ const EXTRACTED_OUTPUT_TEMPLATE = 'extracted: ${lines} lines, ~${pages} pages -> ${path}'
25
+ const COPIED_OUTPUT_TEMPLATE = 'copied: ${lines} lines -> ${path}'
26
+
27
+ /**
28
+ * 将 pdf-parse 的页面文本数组连接为纯文本(纯函数,无 IO)。
29
+ * 每页文本用 \f 连接(与 pdftotext 输出格式一致,chunk_text.js 依赖此格式)。
30
+ * @param {Array<{text: string}>} pages — pdf-parse getText() 返回的 pages
31
+ * @returns {string} 以 \f 分页符分隔的全文
32
+ */
33
+ export function joinPages(pages) {
34
+ return pages.map(p => p.text || '').join('\f')
35
+ }
36
+
37
+ // --- CLI ---
38
+
39
+ const isMain = import.meta.url === `file://${process.argv[1]}`
40
+ if (isMain) {
41
+ const args = process.argv.slice(2)
42
+
43
+ if (args.length < 2) {
44
+ console.error('usage: extract.js <source-file> <output-txt>')
45
+ process.exit(2)
46
+ }
47
+
48
+ const sourcePath = args[0]
49
+ const outPath = args[1]
50
+
51
+ // 检查源文件存在
52
+ if (!existsSync(sourcePath)) {
53
+ console.error(`ERROR: source file not found: ${sourcePath}`)
54
+ process.exit(2)
55
+ }
56
+
57
+ // 检查输出目录
58
+ const outDir = dirname(outPath)
59
+ if (!existsSync(outDir)) {
60
+ mkdirSync(outDir, { recursive: true })
61
+ }
62
+
63
+ if (isPdf(sourcePath)) {
64
+ // ── .pdf:pdf-parse 提取(依赖由 init.js resolve_dependencies 管理)──
65
+ const { PDFParse } = require('pdf-parse')
66
+
67
+ try {
68
+ const buf = readFileSync(sourcePath)
69
+ const parser = new PDFParse({ data: buf })
70
+ const result = await parser.getText()
71
+
72
+ if (!result || !result.pages) {
73
+ console.error('ERROR: pdf-parse returned no pages')
74
+ process.exit(4)
75
+ }
76
+
77
+ // 将每页文本用 \f 连接(与 pdftotext 输出格式一致,chunk_text.js 依赖此格式)
78
+ const content = joinPages(result.pages)
79
+
80
+ writeFileSync(outPath, content, 'utf-8')
81
+
82
+ const lines = content.split('\n').length
83
+ const formFeeds = (content.match(/\f/g) || []).length
84
+ const pageCount = formFeeds + 1
85
+ console.log(render(EXTRACTED_OUTPUT_TEMPLATE, { lines, pages: pageCount, path: outPath }))
86
+ } catch (e) {
87
+ console.error(`ERROR: pdf-parse failed on: ${sourcePath}`)
88
+ console.error(e.message)
89
+ process.exit(4)
90
+ }
91
+ } else {
92
+ // ── .txt / .md:直接复制 ──
93
+ const content = readFileSync(sourcePath, 'utf-8')
94
+ writeFileSync(outPath, content, 'utf-8')
95
+ const lines = content.split('\n').length
96
+ console.log(render(COPIED_OUTPUT_TEMPLATE, { lines, path: outPath }))
97
+ }
98
+ }