@hamzaahmadaslam/chunk-standalone 0.0.0-stage → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hamza Ahmad Aslam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,199 @@
1
- # Temporary Holding Version
1
+ # chunk-standalone
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Finds the chunks in a RAG knowledge base that a reader could not understand on their own, and suggests keep, merge
4
+ or split for each; for anyone who chunks Markdown or text documents for retrieval.
5
+
6
+ A retriever returns chunks one at a time. A chunk that opens with "As shown above", promises "the following
7
+ settings" that sit in the next chunk, or calls the product "it" reaches the answering model without the text it
8
+ depends on, and the answer built on it comes out vague or wrong. A regular expression can find "above" and "this", but it cannot
9
+ tell whether the chunk explains them itself. A text-generating model can judge that, but it returns prose to parse
10
+ and no measure of how sure it is. chunk-standalone asks narrow yes/no and multiple-choice questions and gets
11
+ probabilities back, so code makes the decision and unclear cases go to a review list.
12
+
13
+ ## How it uses Jev
14
+
15
+ Jev is TypeSafe AI's System One model: it answers typed questions with probabilities and writes no text.
16
+
17
+ chunk-standalone sends each file's chunks in reading order. One request holds up to 8 consecutive chunks
18
+ (`--batch`) as the state, plus the last 1,500 characters of the chunk before them and the first 1,500 characters of
19
+ the chunk after them, so every chunk is judged next to both neighbours:
20
+
21
+ ```json
22
+ { "chunks": ["[...] end of the chunk before", "chunk 1", "chunk 2", "chunk 3", "start of the chunk after [...]"] }
23
+ ```
24
+
25
+ For every chunk in the request it asks three questions, which point at the chunk by its position:
26
+
27
+ | Question | Type | What it decides |
28
+ | --------------------------------------------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------- |
29
+ | Can a reader understand `chunks[2]` without the pieces before it? | noul | whether the chunk needs earlier text |
30
+ | Does `chunks[2]` refer to something that is not inside it, such as "this", "above", "the following", "as mentioned"? | noul | whether it points outside itself |
31
+ | What should be done with `chunks[2]` so that it reads well on its own? | choice | keep, merge with previous, merge with next, or split (a merge only when that neighbour exists) |
32
+
33
+ All three are asked for every chunk, 24 questions per request at the default batch size, and the code decides which
34
+ answers matter. The full wording is in `src/check.mjs`, and `--dry-run --json` prints every request body.
35
+
36
+ The verdict is made in code with one threshold, `--threshold` (default 0.8):
37
+
38
+ | Verdict | When |
39
+ | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
40
+ | ok | the first answer is at least the threshold, the second at most 1 minus the threshold, and the fix is keep with a confidence of at least the threshold |
41
+ | fix | the fix is a merge or a split with a confidence of at least the threshold, and a problem is confirmed (first answer at most 1 minus the threshold, or second at least the threshold) or the fix is split |
42
+ | review | everything else: an answer between the two limits, a fix Jev is unsure of, or answers that disagree |
43
+
44
+ A split stands on its own because a chunk can make sense alone and still mix two topics. The report prints the
45
+ probabilities next to every verdict. Every word in it comes from your files or from fixed text in the code.
46
+
47
+ ## Install
48
+
49
+ Needs Node.js 20 or later.
50
+
51
+ ```sh
52
+ npm install -g @hamzaahmadaslam/chunk-standalone
53
+ ```
54
+
55
+ ## Usage
56
+
57
+ ```sh
58
+ export TYPESAFE_API_KEY=<your-key>
59
+ chunk-standalone docs/
60
+ ```
61
+
62
+ In PowerShell, set the key with `$env:TYPESAFE_API_KEY = "<your-key>"`.
63
+
64
+ ```sh
65
+ chunk-standalone docs/ --dry-run # the chunks, the questions and a token estimate; sends nothing
66
+ chunk-standalone docs/ --by paragraph # split at blank lines instead of headings
67
+ chunk-standalone docs/guide.md --by tokens=300 # pieces of about 300 tokens
68
+ chunk-standalone chunks.jsonl --json > report.json
69
+ chunk-standalone docs/ --threshold 0.9 # stricter: more chunks go to review
70
+ ```
71
+
72
+ | Option | Default | What it does |
73
+ | ---------------------------------- | --------- | ------------------------------------------------------------------------------------------------ |
74
+ | `--by heading\|paragraph\|tokens=N` | `heading` | How to split Markdown and text files. Ignored for JSONL input. |
75
+ | `--threshold <p>` | `0.8` | Confidence needed to mark a chunk ok or fix. Above 0.5, at most 1. |
76
+ | `--batch <n>` | `8` | Chunks per request, 1 to 50. `--batch 1` sends each chunk with only its own neighbours. |
77
+ | `--timeout <seconds>` | `10` | Time limit for each request. Rate limits (429) and overload (529) are retried three times. |
78
+ | `--json` | off | Print JSON: every chunk, its verdict and the raw probabilities. |
79
+ | `--dry-run` | off | Print how the files were chunked, one chunk's questions and the token estimate. Needs no key. |
80
+
81
+ Environment: `TYPESAFE_API_KEY` (needed unless `--dry-run`) and `TYPESAFE_MODEL` (default `jev-latest`).
82
+
83
+ Exit codes: `0` when no chunk needs a fix, `1` when at least one does, so it can fail a CI job, and `2` on an error.
84
+ Chunks in review do not change the exit code.
85
+
86
+ ### Input
87
+
88
+ - A folder: every `.md`, `.markdown`, `.mdx` and `.txt` file below it, except inside `node_modules` and folders
89
+ whose names start with a dot. YAML front matter at the top of a Markdown file is skipped.
90
+ - One file with one of those extensions.
91
+ - A `.jsonl` file of chunks you already made, one per line:
92
+
93
+ ```json
94
+ {"id": "install-2", "text": "As shown above, run the installer.", "source": "install.md"}
95
+ ```
96
+
97
+ The text may also be in `page_content` or `content`, and the source in `metadata.source` or
98
+ `metadata.file_name`, which covers LangChain-style exports. Chunks are checked in line order within their
99
+ source. Without a source, the whole file counts as one document.
100
+
101
+ Files are split the three common ways, so the report shows the problems your own chunker is likely to make:
102
+
103
+ | `--by` | Splits |
104
+ | ----------- | -------------------------------------------------------------------------------------------------------- |
105
+ | `heading` | at every heading (`#` to `######`) outside code blocks; text before the first heading is its own chunk |
106
+ | `paragraph` | at every blank line outside code blocks |
107
+ | `tokens=N` | into pieces of about N tokens (four characters per token), cut between words, with no overlap |
108
+
109
+ If your pipeline adds overlap, titles or heading paths to its chunks, export the chunks to JSONL and check those.
110
+
111
+ ## Example
112
+
113
+ `examples/docs` holds two short Markdown pages about a made-up backup feature, written for this example. The
114
+ probabilities below come from `examples/fixture-answers.json`: they were written by hand for the tests, not
115
+ recorded from TypeSafe, and show the report format. Your numbers will differ. `node examples/run.mjs` prints this
116
+ report without a key or a network call.
117
+
118
+ ```text
119
+ chunk-standalone: 9 chunks in 2 files, split by heading
120
+ Model jev-1.13.0, 2 requests, 3,695 input tokens, threshold 0.8
121
+
122
+ ok 4 fix 4 review 1
123
+
124
+ backups.md (5 chunks: fix 3, review 1)
125
+ #2 line 10 review (unclear if it stands alone, unclear if it points outside itself, unclear which fix)
126
+ standalone 0.46 | outside reference 0.38 | fix answer: merge with previous 0.55, keep 0.41 (confidence 0.40)
127
+ "## Schedule It starts at 02:00 server time and usually takes a few..."
128
+ #3 line 14 fix: merge with previous (needs earlier text, points outside itself)
129
+ standalone 0.14 | outside reference 0.93 | fix answer: merge with previous 0.91, keep 0.05 (confidence 0.88)
130
+ "## Keeping copies As shown above, a copy is made every night. Copies..."
131
+ #4 line 19 fix: merge with next (points outside itself)
132
+ standalone 0.35 | outside reference 0.95 | fix answer: merge with next 0.92 (confidence 0.89)
133
+ "## Settings The following settings control the job."
134
+ #5 line 23 fix: split (covers more than one topic)
135
+ standalone 0.84 | outside reference 0.12 | fix answer: split 0.90, keep 0.08 (confidence 0.85)
136
+ "## Settings reference `backup.bucket` is the storage bucket that..."
137
+
138
+ restore.md (4 chunks: fix 1)
139
+ #3 line 16 fix: merge with previous (needs earlier text, points outside itself)
140
+ standalone 0.11 | outside reference 0.94 | fix answer: merge with previous 0.93 (confidence 0.91)
141
+ "## If it fails Repeat step 2 with maintenance mode switched on. If the..."
142
+
143
+ fix: confident answers (threshold 0.8) found a problem and agree on the fix.
144
+ review: the answers were not confident enough or disagreed. Read these chunks yourself.
145
+ ```
146
+
147
+ "As shown above" and "Repeat step 2" point back to earlier chunks, "The following settings" points forward, and
148
+ the settings reference mixes backup settings with account emails and invoices. "It starts at 02:00" sits near the
149
+ middle on every question, so it goes to review. The same run with `--json` is in `examples/report.json`, and the
150
+ dry run in `examples/dry-run.txt`.
151
+
152
+ ## What leaves your machine
153
+
154
+ Only when you run it with a key and without `--dry-run`, and only to `https://api.typesafe.ai/v1/systemone`:
155
+
156
+ - the text of your chunks, up to 8 consecutive chunks of one file per request (`--batch`);
157
+ - the last 1,500 characters of the chunk before them and the first 1,500 characters of the chunk after them;
158
+ - the fixed question text, which names chunks only by position (`chunks[2]`), question ids such as `c12_fix`, and
159
+ the model name;
160
+ - your API key, in the `Authorization` header.
161
+
162
+ File names, folder names, chunk ids, line numbers and other JSONL fields are not sent. The tool writes nothing to
163
+ disk and makes no other network requests, for telemetry, updates or anything else.
164
+
165
+ ## Limits
166
+
167
+ - Jev sees the chunk text and its neighbours, not what your pipeline adds at query time. If you prepend titles or
168
+ heading paths to chunks before embedding, put them in the chunk text (JSONL input) so the check sees what your
169
+ retriever sees.
170
+ - The fix is one of four answers. For a chunk that only lacks its section name, adding the heading is often the
171
+ better fix; the report does not suggest it.
172
+ - A merge suggestion names one neighbour. A chunk that needs text on both sides gets one of them.
173
+ - The splitting modes approximate common chunkers: no overlap, only `#` headings (underlined headings are not
174
+ recognised), and token counts estimated at four characters per token. For your exact chunks, use JSONL.
175
+ - English is where Jev is most accurate. The token estimate also assumes English; other scripts use more tokens per
176
+ character, so lower `--batch` if TypeSafe rejects a request as too large.
177
+ - Chunks estimated above 14,000 tokens are listed as skipped, not checked.
178
+ - Text written to steer a model, such as an instruction hidden in a document, can move Jev's answers.
179
+ - The tool reports and never edits files. Treat fix verdicts as suggestions, read the review list yourself, and
180
+ check a sample of verdicts on your own documents before you rely on a threshold.
181
+
182
+ ## Token use
183
+
184
+ The input tokens of a request are its state (the chunks and the text on either side of them) and its questions. The
185
+ questions add about 375 tokens per chunk, so for short chunks most of the input is the questions. By the tool's own
186
+ estimate (four characters per token):
187
+
188
+ | Run | Requests | Input tokens |
189
+ | ----------------------------------------------------------- | -------- | -------------- |
190
+ | The example: 9 chunks in 2 files | 2 | about 3,700 |
191
+ | 1,000 chunks of about 200 tokens (100 files of 10 sections) | 200 | about 630,000 |
192
+ | The same files with `--batch 1` | 1,000 | about 980,000 |
193
+
194
+ `--dry-run` prints the estimate for your own files before anything is sent. After a run, the report prints the input
195
+ tokens TypeSafe counted.
196
+
197
+ ## License
198
+
199
+ MIT. Made by [Hamza Ahmad Aslam](https://hamzaahmadaslam.com), WordPress and web performance engineer.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "../src/cli.mjs";
3
+
4
+ process.exitCode = await main(process.argv.slice(2));
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@hamzaahmadaslam/chunk-standalone",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Finds RAG chunks that cannot be understood on their own and suggests keep, merge or split, using TypeSafe's Jev model.",
5
+ "type": "module",
6
+ "bin": {
7
+ "chunk-standalone": "bin/chunk-standalone.mjs"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src"
12
+ ],
13
+ "engines": {
14
+ "node": ">=20"
15
+ },
16
+ "scripts": {
17
+ "test": "node --test"
18
+ },
19
+ "keywords": [
20
+ "rag",
21
+ "chunking",
22
+ "retrieval",
23
+ "markdown",
24
+ "lint",
25
+ "typesafe",
26
+ "jev"
27
+ ],
28
+ "author": "Hamza Ahmad Aslam (https://hamzaahmadaslam.com)",
29
+ "license": "MIT",
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/hamzaahmadaslam/chunk-standalone.git"
33
+ },
34
+ "homepage": "https://hamzaahmadaslam.com/open-source/chunk-standalone",
35
+ "bugs": {
36
+ "url": "https://github.com/hamzaahmadaslam/chunk-standalone/issues"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ }
41
+ }
package/src/check.mjs ADDED
@@ -0,0 +1,270 @@
1
+ // Builds the requests (consecutive chunks of one document as the state, three questions per chunk), sends them to
2
+ // Jev, and turns the answers into a verdict for each chunk: ok, fix or review. The thresholds live here, in code.
3
+ import { estimateTokens } from "./chunk.mjs";
4
+ import { askJev, choice, DEFAULT_MODEL, noul } from "./jev.mjs";
5
+
6
+ export const DEFAULT_THRESHOLD = 0.8;
7
+ export const DEFAULT_BATCH = 8;
8
+ export const MAX_BATCH = 50;
9
+ export const DEFAULT_TIMEOUT_SECONDS = 10;
10
+ /** Estimated tokens of state per request. TypeSafe allows 32k for the state plus the longest question. */
11
+ export const STATE_BUDGET = 16_000;
12
+ /** How much of a neighbour outside the batch goes into the state: the end of the one before, the start of the one after. */
13
+ export const CONTEXT_CHARS = 1_500;
14
+ /** Chunks estimated above this many tokens are reported as too large and not sent. */
15
+ export const MAX_CHUNK_TOKENS = 14_000;
16
+ const CONCURRENCY = 4;
17
+
18
+ const ORDER = "`chunks` lists consecutive pieces of one document, in reading order.";
19
+
20
+ /**
21
+ * The three questions asked about the chunk at `chunks[at]` in the state. `key` prefixes the question ids; the ids
22
+ * are for this code only. The merge options are offered only when that neighbour is in the state.
23
+ */
24
+ export function questionsFor(key, at, { hasPrevious, hasNext }) {
25
+ const self = `\`chunks[${at}]\``;
26
+ const previous = `\`chunks[${at - 1}]\``;
27
+ const next = `\`chunks[${at + 1}]\``;
28
+ const fixes = { keep: "Keep it as it is: it makes sense on its own and covers one topic." };
29
+ if (hasPrevious) fixes.merge_with_previous = `Join it to ${previous}: it continues ${previous} or needs it to make sense.`;
30
+ if (hasNext) {
31
+ fixes.merge_with_next = `Join it to ${next}: it is only a heading or an introduction for ${next}, or it leads into a list or example in ${next}.`;
32
+ }
33
+ fixes.split = "Split it: it covers two or more separate topics.";
34
+ return {
35
+ [`${key}_standalone`]: noul(
36
+ `${ORDER} A search system will return ${self} alone. Can a reader understand ${self} without the pieces before it?`,
37
+ {
38
+ true: "It says what it is about, and every sentence in it makes sense without earlier text.",
39
+ false:
40
+ "It continues a sentence, list, table, code block or explanation from earlier text, or what it is about is only named in earlier text.",
41
+ },
42
+ ),
43
+ [`${key}_outside`]: noul(
44
+ `Does ${self} refer to something that is not inside ${self}, with words such as "this", "above", "below", "the following", "as mentioned" or "the previous step"?`,
45
+ {
46
+ true: "It points to a passage, list, table, figure, step or section that is outside it.",
47
+ false: "It points to nothing outside itself, or what it points to is inside it.",
48
+ },
49
+ ),
50
+ [`${key}_fix`]: choice(
51
+ `${ORDER} A search system will return ${self} alone. What should be done with ${self} so that it reads well on its own?`,
52
+ fixes,
53
+ ),
54
+ };
55
+ }
56
+
57
+ /** Why a chunk cannot be sent, or null when it can. */
58
+ function skipReason(chunk) {
59
+ if (!chunk.text.trim()) return "empty";
60
+ if (estimateTokens(chunk.text) > MAX_CHUNK_TOKENS) return "too_large";
61
+ return null;
62
+ }
63
+
64
+ /** Tokens a text takes up inside the JSON state, quotes and escapes included. */
65
+ const stateTokens = (text) => estimateTokens(JSON.stringify(text));
66
+ const CONTEXT_TOKENS = 2 * stateTokens(`[...] ${"x".repeat(CONTEXT_CHARS)}`);
67
+
68
+ /** The end of a neighbour chunk, cut at a word boundary and marked with [...]. */
69
+ function tail(text) {
70
+ if (text.length <= CONTEXT_CHARS) return text;
71
+ const cut = text.slice(-CONTEXT_CHARS);
72
+ const space = cut.search(/\s/);
73
+ return `[...] ${(space >= 0 ? cut.slice(space) : cut).trim()}`;
74
+ }
75
+
76
+ /** The start of a neighbour chunk, cut at a word boundary and marked with [...]. */
77
+ function head(text) {
78
+ if (text.length <= CONTEXT_CHARS) return text;
79
+ const cut = text.slice(0, CONTEXT_CHARS);
80
+ const space = cut.search(/\s\S*$/);
81
+ return `${(space > 0 ? cut.slice(0, space) : cut).trim()} [...]`;
82
+ }
83
+
84
+ /**
85
+ * Groups the chunks of each document into requests. A request holds up to `batch` consecutive chunks, plus the end
86
+ * of the chunk before them and the start of the chunk after them, so every checked chunk has both neighbours in the
87
+ * state. Empty chunks and chunks over MAX_CHUNK_TOKENS are listed in `skipped` instead.
88
+ */
89
+ export function planRequests(documents, { batch = DEFAULT_BATCH, model = DEFAULT_MODEL } = {}) {
90
+ const requests = [];
91
+ const skipped = [];
92
+ let counter = 0;
93
+ for (const doc of documents) {
94
+ const { chunks } = doc;
95
+ const numbers = chunks.map(() => counter++);
96
+ let i = 0;
97
+ while (i < chunks.length) {
98
+ const reason = skipReason(chunks[i]);
99
+ if (reason) {
100
+ skipped.push({ source: doc.source, chunk: chunks[i], reason });
101
+ i++;
102
+ continue;
103
+ }
104
+ const asked = [i];
105
+ let tokens = CONTEXT_TOKENS + stateTokens(chunks[i].text);
106
+ let j = i + 1;
107
+ while (j < chunks.length && asked.length < batch && !skipReason(chunks[j])) {
108
+ const more = stateTokens(chunks[j].text);
109
+ if (tokens + more > STATE_BUDGET) break;
110
+ tokens += more;
111
+ asked.push(j++);
112
+ }
113
+ requests.push(buildRequest(doc, asked, numbers, model));
114
+ i = j;
115
+ }
116
+ }
117
+ return { documents, requests, skipped, chunkCount: counter };
118
+ }
119
+
120
+ function buildRequest(doc, asked, numbers, model) {
121
+ const { chunks } = doc;
122
+ const items = [];
123
+ const before = chunks[asked[0] - 1];
124
+ if (before?.text.trim()) items.push(tail(before.text));
125
+ const offset = items.length;
126
+ for (const k of asked) items.push(chunks[k].text);
127
+ const after = chunks[asked[asked.length - 1] + 1];
128
+ if (after?.text.trim()) items.push(head(after.text));
129
+ const questions = {};
130
+ const targets = asked.map((k, index) => {
131
+ const at = offset + index;
132
+ const key = `c${numbers[k]}`;
133
+ Object.assign(questions, questionsFor(key, at, { hasPrevious: at > 0, hasNext: at < items.length - 1 }));
134
+ return { key, at, chunk: chunks[k] };
135
+ });
136
+ return { source: doc.source, targets, body: { model, state: { chunks: items }, questions } };
137
+ }
138
+
139
+ /** Estimated input tokens of a plan, per request and in total, for --dry-run. */
140
+ export function estimatePlan(plan) {
141
+ const perRequest = plan.requests.map((request) => estimateTokens(JSON.stringify(request.body)));
142
+ const tokens = perRequest.reduce((sum, n) => sum + n, 0);
143
+ return { perRequest, tokens };
144
+ }
145
+
146
+ const isProbability = (value) => typeof value === "number" && value >= 0 && value <= 1;
147
+
148
+ /** The three answers for one chunk from a response, or null when any is missing or malformed. */
149
+ export function readAnswer(answers, key) {
150
+ const standalone = answers?.[`${key}_standalone`]?.noul;
151
+ const outside = answers?.[`${key}_outside`]?.noul;
152
+ const fix = answers?.[`${key}_fix`];
153
+ if (!isProbability(standalone) || !isProbability(outside)) return null;
154
+ if (typeof fix?.choice !== "string" || !isProbability(fix.confidence)) return null;
155
+ if (!fix.probabilities || typeof fix.probabilities !== "object") return null;
156
+ return { standalone, outside, fix: { choice: fix.choice, confidence: fix.confidence, probabilities: fix.probabilities } };
157
+ }
158
+
159
+ // Rounding keeps float noise (1 - 0.8 is 0.19999999999999996) from moving an answer that sits on the threshold.
160
+ const round = (value) => Math.round(value * 1e6) / 1e6;
161
+
162
+ /**
163
+ * Turns one chunk's answers into a verdict. A yes/no answer counts only at or above `threshold` (yes) or at or
164
+ * below 1 - `threshold` (no), and the fix answer only when its confidence is at or above `threshold`.
165
+ * ok: it stands alone, points to nothing outside itself, and the fix is keep.
166
+ * fix: the fix is merge or split, and either a problem is confirmed or the fix is split (a chunk can make
167
+ * sense alone and still cover two topics).
168
+ * review: anything else, with the reasons.
169
+ */
170
+ export function decide(answer, threshold = DEFAULT_THRESHOLD) {
171
+ const { standalone, outside, fix } = answer;
172
+ const standsAlone = round(standalone) >= threshold;
173
+ const needsEarlier = round(1 - standalone) >= threshold;
174
+ const pointsOut = round(outside) >= threshold;
175
+ const selfContained = round(1 - outside) >= threshold;
176
+ const fixSure = round(fix.confidence) >= threshold;
177
+ const clean = standsAlone && selfContained;
178
+ const problem = needsEarlier || pointsOut;
179
+
180
+ if (clean && fixSure && fix.choice === "keep") return { verdict: "ok", fix: "keep", reasons: [] };
181
+ if (fixSure && fix.choice !== "keep" && (problem || fix.choice === "split")) {
182
+ const reasons = [];
183
+ if (needsEarlier) reasons.push("needs_earlier_text");
184
+ if (pointsOut) reasons.push("points_outside");
185
+ if (fix.choice === "split") reasons.push("mixes_topics");
186
+ return { verdict: "fix", fix: fix.choice, reasons };
187
+ }
188
+ const reasons = [];
189
+ if (!standsAlone && !needsEarlier) reasons.push("unsure_standalone");
190
+ if (!pointsOut && !selfContained) reasons.push("unsure_outside");
191
+ if (!fixSure) reasons.push("unsure_fix");
192
+ else if ((fix.choice === "keep" && problem) || (fix.choice !== "keep" && clean)) reasons.push("answers_disagree");
193
+ return { verdict: "review", fix: fix.choice, reasons: reasons.length ? reasons : ["answers_disagree"] };
194
+ }
195
+
196
+ /** Runs `worker` over `items` with at most `limit` at a time; stops starting new work after the first failure. */
197
+ async function mapLimit(items, limit, worker) {
198
+ const results = new Array(items.length);
199
+ let next = 0;
200
+ let failed = false;
201
+ const lanes = Array.from({ length: Math.min(limit, items.length) }, async () => {
202
+ while (!failed && next < items.length) {
203
+ const index = next++;
204
+ try {
205
+ results[index] = await worker(items[index]);
206
+ } catch (error) {
207
+ failed = true;
208
+ throw error;
209
+ }
210
+ }
211
+ });
212
+ await Promise.all(lanes);
213
+ return results;
214
+ }
215
+
216
+ /**
217
+ * Sends every request in the plan (four at a time) and returns the verdicts grouped by document:
218
+ * { model, threshold, files: [{ source, chunks: [{ chunk, verdict, fix, reasons, answer }] }], summary, usage }.
219
+ * Any TypeSafe error (missing key, 401, 422, 429 or 529 after retries, timeout) stops the run with a JevError.
220
+ */
221
+ export async function runPlan(plan, options = {}) {
222
+ const {
223
+ threshold = DEFAULT_THRESHOLD,
224
+ apiKey,
225
+ model = DEFAULT_MODEL,
226
+ timeoutSeconds = DEFAULT_TIMEOUT_SECONDS,
227
+ retries = 3,
228
+ fetchImpl,
229
+ onProgress,
230
+ } = options;
231
+ let done = 0;
232
+ const responses = await mapLimit(plan.requests, CONCURRENCY, async (request) => {
233
+ const response = await askJev(request.body.state, request.body.questions, {
234
+ apiKey,
235
+ model,
236
+ timeoutMs: timeoutSeconds * 1000,
237
+ retries,
238
+ fetchImpl,
239
+ });
240
+ onProgress?.(++done, plan.requests.length);
241
+ return response;
242
+ });
243
+
244
+ const outcomes = new Map();
245
+ plan.requests.forEach((request, i) => {
246
+ for (const { key, chunk } of request.targets) {
247
+ const answer = readAnswer(responses[i].answers, key);
248
+ outcomes.set(
249
+ chunk,
250
+ answer ? { answer, ...decide(answer, threshold) } : { answer: null, verdict: "review", fix: null, reasons: ["no_answer"] },
251
+ );
252
+ }
253
+ });
254
+ for (const { chunk, reason } of plan.skipped) {
255
+ outcomes.set(chunk, { answer: null, verdict: "skipped", fix: null, reasons: [reason] });
256
+ }
257
+
258
+ const files = plan.documents.map((doc) => ({
259
+ source: doc.source,
260
+ chunks: doc.chunks.map((chunk) => ({ chunk, ...outcomes.get(chunk) })),
261
+ }));
262
+ const summary = { files: files.length, chunks: plan.chunkCount, ok: 0, fix: 0, review: 0, skipped: 0 };
263
+ for (const file of files) for (const entry of file.chunks) summary[entry.verdict]++;
264
+ const usage = {
265
+ requests: responses.length,
266
+ input_tokens: responses.reduce((sum, r) => sum + (Number(r.usage?.input_tokens) || 0), 0),
267
+ output_tokens: responses.reduce((sum, r) => sum + (Number(r.usage?.output_tokens) || 0), 0),
268
+ };
269
+ return { model: responses[0]?.model ?? model, threshold, files, summary, usage };
270
+ }
package/src/chunk.mjs ADDED
@@ -0,0 +1,128 @@
1
+ // Splits Markdown and plain text into chunks the way common RAG chunkers do, so the check runs on chunks shaped
2
+ // like the ones your own pipeline makes: at headings, at blank lines, or every N tokens.
3
+ import { UserError } from "./errors.mjs";
4
+
5
+ export const MIN_TOKENS = 20;
6
+ export const MAX_TOKENS = 14_000;
7
+
8
+ /** A rough token count: about four characters per token, which fits English prose. Used for sizes and estimates. */
9
+ export function estimateTokens(text) {
10
+ return Math.ceil(text.length / 4);
11
+ }
12
+
13
+ /** Parses the --by value into { mode } or { mode: "tokens", size }. */
14
+ export function parseBy(value) {
15
+ const text = String(value ?? "").trim().toLowerCase();
16
+ if (text === "heading" || text === "paragraph") return { mode: text };
17
+ const match = /^tokens=(\d+)$/.exec(text);
18
+ if (match && Number(match[1]) >= MIN_TOKENS && Number(match[1]) <= MAX_TOKENS) {
19
+ return { mode: "tokens", size: Number(match[1]) };
20
+ }
21
+ throw new UserError(
22
+ `--by must be heading, paragraph or tokens=N with N from ${MIN_TOKENS} to ${MAX_TOKENS}, not "${value}".`,
23
+ );
24
+ }
25
+
26
+ /** The --by value as the user would write it, for reports. */
27
+ export function describeBy(by) {
28
+ return by.mode === "tokens" ? `tokens=${by.size}` : by.mode;
29
+ }
30
+
31
+ /** Removes a byte order mark and turns Windows and old Mac line endings into \n. */
32
+ export function normalize(text) {
33
+ return text.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
34
+ }
35
+
36
+ /** Blanks out YAML front matter at the top of a Markdown file. The lines stay, so line numbers still match the file. */
37
+ export function blankFrontMatter(text) {
38
+ const lines = text.split("\n");
39
+ if (!/^---\s*$/.test(lines[0])) return text;
40
+ for (let i = 1; i < lines.length; i++) {
41
+ if (/^(---|\.\.\.)\s*$/.test(lines[i])) {
42
+ for (let j = 0; j <= i; j++) lines[j] = "";
43
+ return lines.join("\n");
44
+ }
45
+ }
46
+ return text;
47
+ }
48
+
49
+ const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})/;
50
+ const FENCE_CLOSE = /^ {0,3}(`{3,}|~{3,})\s*$/;
51
+ const HEADING = /^ {0,3}#{1,6}(?:[ \t]|$)/;
52
+
53
+ /** Tracks fenced code blocks: returns the open fence after `line`, or null when outside a code block. */
54
+ function nextFence(line, open) {
55
+ if (!open) {
56
+ const match = FENCE_OPEN.exec(line);
57
+ return match ? match[1] : null;
58
+ }
59
+ const match = FENCE_CLOSE.exec(line);
60
+ return match && match[1][0] === open[0] && match[1].length >= open.length ? null : open;
61
+ }
62
+
63
+ /** Lines start..end (end excluded) as a chunk, without blank lines at either end; null when there is no text. */
64
+ function toChunk(lines, start, end) {
65
+ while (start < end && !lines[start].trim()) start++;
66
+ while (end > start && !lines[end - 1].trim()) end--;
67
+ if (start === end) return null;
68
+ return { line: start + 1, text: lines.slice(start, end).join("\n").trimEnd() };
69
+ }
70
+
71
+ /** Splits wherever `isBoundary(line)` says a new chunk starts (or, for blank lines, where one ends). */
72
+ function splitLines(lines, isBoundary, boundaryStartsChunk) {
73
+ const chunks = [];
74
+ let start = 0;
75
+ let fence = null;
76
+ lines.forEach((line, i) => {
77
+ if (!fence && isBoundary(line)) {
78
+ chunks.push(toChunk(lines, start, i));
79
+ start = boundaryStartsChunk ? i : i + 1;
80
+ }
81
+ fence = nextFence(line, fence);
82
+ });
83
+ chunks.push(toChunk(lines, start, lines.length));
84
+ return chunks.filter(Boolean);
85
+ }
86
+
87
+ /** A new chunk at every ATX heading (# to ######) outside code blocks. Text before the first heading is a chunk too. */
88
+ export function chunkByHeading(text) {
89
+ return splitLines(normalize(text).split("\n"), (line) => HEADING.test(line), true);
90
+ }
91
+
92
+ /** A new chunk after every blank line outside code blocks. */
93
+ export function chunkByParagraph(text) {
94
+ return splitLines(normalize(text).split("\n"), (line) => !line.trim(), false);
95
+ }
96
+
97
+ /** Chunks of at most about `size` tokens, cut between words, with no overlap. */
98
+ export function chunkByTokens(text, size) {
99
+ const source = normalize(text);
100
+ const maxChars = size * 4;
101
+ const chunks = [];
102
+ let current = "";
103
+ let startLine = 1;
104
+ let line = 1;
105
+ let scanned = 0;
106
+ const lineAt = (offset) => {
107
+ for (; scanned < offset; scanned++) if (source.charCodeAt(scanned) === 10) line++;
108
+ return line;
109
+ };
110
+ for (const match of source.matchAll(/\S+\s*/g)) {
111
+ const word = match[0];
112
+ if (current && current.length + word.trimEnd().length > maxChars) {
113
+ chunks.push({ line: startLine, text: current.trimEnd() });
114
+ current = "";
115
+ }
116
+ if (!current) startLine = lineAt(match.index);
117
+ current += word;
118
+ }
119
+ if (current.trim()) chunks.push({ line: startLine, text: current.trimEnd() });
120
+ return chunks;
121
+ }
122
+
123
+ /** Splits `text` with the parsed --by value. Returns [{ line, text }] with 1-based line numbers. */
124
+ export function chunkText(text, by) {
125
+ if (by.mode === "heading") return chunkByHeading(text);
126
+ if (by.mode === "paragraph") return chunkByParagraph(text);
127
+ return chunkByTokens(text, by.size);
128
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,147 @@
1
+ // The command line: parses options, loads the input, and prints the report, the JSON or the dry run.
2
+ // main() takes its environment, output streams and fetch as arguments, so tests run it without a network.
3
+ import { readFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { parseArgs } from "node:util";
6
+ import { parseBy } from "./chunk.mjs";
7
+ import {
8
+ DEFAULT_BATCH,
9
+ DEFAULT_THRESHOLD,
10
+ DEFAULT_TIMEOUT_SECONDS,
11
+ MAX_BATCH,
12
+ planRequests,
13
+ runPlan,
14
+ } from "./check.mjs";
15
+ import { UserError } from "./errors.mjs";
16
+ import { DEFAULT_MODEL, JevError } from "./jev.mjs";
17
+ import { isJsonlPath, loadInput } from "./load.mjs";
18
+ import { dryRunJson, formatDryRun, formatReport, toJson } from "./report.mjs";
19
+
20
+ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
21
+
22
+ export const USAGE = `Usage: chunk-standalone <folder | file.md | chunks.jsonl> [options]
23
+
24
+ Checks whether each RAG chunk can be understood on its own, and suggests keep, merge or split.
25
+
26
+ Options:
27
+ --by <mode> how to split .md and .txt files: heading, paragraph or tokens=N (default heading)
28
+ --threshold <p> confidence needed to mark a chunk ok or fix, above 0.5 and up to 1 (default ${DEFAULT_THRESHOLD})
29
+ --batch <n> chunks per request, 1 to ${MAX_BATCH} (default ${DEFAULT_BATCH})
30
+ --timeout <seconds> time limit for each request (default ${DEFAULT_TIMEOUT_SECONDS})
31
+ --json print JSON instead of the report
32
+ --dry-run print the questions and a token estimate; send nothing
33
+ -h, --help show this help
34
+ -v, --version show the version
35
+
36
+ Environment:
37
+ TYPESAFE_API_KEY your TypeSafe API key (not needed for --dry-run)
38
+ TYPESAFE_MODEL the model to use (default ${DEFAULT_MODEL})
39
+
40
+ Exit codes: 0 no chunk to fix, 1 at least one chunk to fix, 2 error.
41
+ `;
42
+
43
+ function parseOptions(argv) {
44
+ let parsed;
45
+ try {
46
+ parsed = parseArgs({
47
+ args: argv,
48
+ allowPositionals: true,
49
+ options: {
50
+ by: { type: "string" },
51
+ threshold: { type: "string" },
52
+ batch: { type: "string" },
53
+ timeout: { type: "string" },
54
+ json: { type: "boolean", default: false },
55
+ "dry-run": { type: "boolean", default: false },
56
+ help: { type: "boolean", short: "h", default: false },
57
+ version: { type: "boolean", short: "v", default: false },
58
+ },
59
+ });
60
+ } catch (error) {
61
+ throw new UserError(`${error.message} Run chunk-standalone --help for the options.`);
62
+ }
63
+ const { values, positionals } = parsed;
64
+ if (values.help || values.version) return { help: values.help, version: values.version };
65
+ if (positionals.length !== 1) {
66
+ throw new UserError("Give one folder, Markdown or text file, or .jsonl file to check. Run chunk-standalone --help for usage.");
67
+ }
68
+
69
+ const threshold = values.threshold === undefined ? DEFAULT_THRESHOLD : Number(values.threshold);
70
+ if (!(threshold > 0.5 && threshold <= 1)) {
71
+ throw new UserError(`--threshold must be a number above 0.5 and at most 1, not "${values.threshold}".`);
72
+ }
73
+ const batch = values.batch === undefined ? DEFAULT_BATCH : Number(values.batch);
74
+ if (!Number.isInteger(batch) || batch < 1 || batch > MAX_BATCH) {
75
+ throw new UserError(`--batch must be a whole number from 1 to ${MAX_BATCH}, not "${values.batch}".`);
76
+ }
77
+ const timeoutSeconds = values.timeout === undefined ? DEFAULT_TIMEOUT_SECONDS : Number(values.timeout);
78
+ if (!(timeoutSeconds > 0 && timeoutSeconds <= 600)) {
79
+ throw new UserError(`--timeout must be a number of seconds above 0 and at most 600, not "${values.timeout}".`);
80
+ }
81
+ return {
82
+ input: positionals[0],
83
+ by: parseBy(values.by ?? "heading"),
84
+ byGiven: values.by !== undefined,
85
+ threshold,
86
+ batch,
87
+ timeoutSeconds,
88
+ json: values.json,
89
+ dryRun: values["dry-run"],
90
+ };
91
+ }
92
+
93
+ /** Runs the tool. Returns the exit code: 0 nothing to fix, 1 at least one chunk to fix, 2 an error. */
94
+ export async function main(argv, io = {}) {
95
+ const { env = process.env, stdout = process.stdout, stderr = process.stderr, fetchImpl = globalThis.fetch } = io;
96
+ const write = (stream, text) => stream.write(text.endsWith("\n") ? text : `${text}\n`);
97
+ try {
98
+ const options = parseOptions(argv);
99
+ if (options.help || options.version) {
100
+ write(stdout, options.help ? USAGE : VERSION);
101
+ return 0;
102
+ }
103
+
104
+ const jsonl = isJsonlPath(options.input);
105
+ const documents = loadInput(options.input, options.by);
106
+ if (jsonl && options.byGiven) write(stderr, "chunk-standalone: --by is ignored for JSONL input; its chunks are checked as they are.");
107
+ const model = env.TYPESAFE_MODEL?.trim() || DEFAULT_MODEL;
108
+ const meta = {
109
+ version: VERSION,
110
+ inputKind: jsonl ? "jsonl" : "files",
111
+ jsonlName: path.basename(options.input),
112
+ by: options.by,
113
+ batch: options.batch,
114
+ model,
115
+ };
116
+ const plan = planRequests(documents, { batch: options.batch, model });
117
+
118
+ if (options.dryRun) {
119
+ write(stdout, options.json ? JSON.stringify(dryRunJson(plan, meta), null, 2) : formatDryRun(plan, meta));
120
+ return 0;
121
+ }
122
+
123
+ const apiKey = env.TYPESAFE_API_KEY?.trim();
124
+ if (!apiKey) {
125
+ throw new UserError(
126
+ "TYPESAFE_API_KEY is not set. Get a key at https://typesafe.ai and export it first, or use --dry-run to see what would be sent.",
127
+ );
128
+ }
129
+ const progress = stderr.isTTY
130
+ ? (done, total) => stderr.write(`\rchecked ${done} of ${total} requests${done === total ? "\n" : ""}`)
131
+ : undefined;
132
+ const result = await runPlan(plan, {
133
+ threshold: options.threshold,
134
+ apiKey,
135
+ model,
136
+ timeoutSeconds: options.timeoutSeconds,
137
+ fetchImpl,
138
+ onProgress: progress,
139
+ });
140
+ write(stdout, options.json ? JSON.stringify(toJson(result, meta), null, 2) : formatReport(result, meta));
141
+ return result.summary.fix > 0 ? 1 : 0;
142
+ } catch (error) {
143
+ const known = error instanceof UserError || error instanceof JevError;
144
+ write(stderr, `chunk-standalone: ${known ? error.message : `unexpected error: ${error?.message ?? error}`}`);
145
+ return 2;
146
+ }
147
+ }
package/src/errors.mjs ADDED
@@ -0,0 +1,7 @@
1
+ /** An error whose message is written for the person running the tool. The CLI prints it without a stack trace. */
2
+ export class UserError extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "UserError";
6
+ }
7
+ }
package/src/jev.mjs ADDED
@@ -0,0 +1,92 @@
1
+ // A small client for TypeSafe's System One API (Jev). Copy this file into a tool as src/jev.mjs.
2
+ // API: POST https://api.typesafe.ai/v1/systemone { model, state, questions } -> { model, answers, usage }
3
+ // The key comes from TYPESAFE_API_KEY and is only ever sent in the Authorization header.
4
+
5
+ export const JEV_ENDPOINT = "https://api.typesafe.ai/v1/systemone";
6
+ export const DEFAULT_MODEL = "jev-latest";
7
+
8
+ export class JevError extends Error {
9
+ constructor(message, status) {
10
+ super(message);
11
+ this.name = "JevError";
12
+ this.status = status;
13
+ }
14
+ }
15
+
16
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
17
+
18
+ /**
19
+ * Asks Jev the `questions` about `state`. Retries 429 and 529 up to `retries` times with exponential backoff
20
+ * (honouring retry-after), times out each attempt after `timeoutMs`, and throws a JevError with a plain message
21
+ * otherwise. `fetchImpl` is injectable so tests never touch the network.
22
+ */
23
+ export async function askJev(state, questions, options = {}) {
24
+ const {
25
+ apiKey = process.env.TYPESAFE_API_KEY,
26
+ model = process.env.TYPESAFE_MODEL || DEFAULT_MODEL,
27
+ timeoutMs = 10_000,
28
+ retries = 3,
29
+ fetchImpl = globalThis.fetch,
30
+ } = options;
31
+ if (!apiKey || !apiKey.trim()) {
32
+ throw new JevError("TYPESAFE_API_KEY is not set. Get a key at https://typesafe.ai and export it first.", 0);
33
+ }
34
+ const body = JSON.stringify({ model, state, questions });
35
+ for (let attempt = 0; ; attempt++) {
36
+ let res;
37
+ try {
38
+ res = await fetchImpl(JEV_ENDPOINT, {
39
+ method: "POST",
40
+ headers: { authorization: `Bearer ${apiKey.trim()}`, "content-type": "application/json" },
41
+ body,
42
+ signal: AbortSignal.timeout(timeoutMs),
43
+ });
44
+ } catch (error) {
45
+ if (attempt < retries) {
46
+ await sleep(500 * 2 ** attempt);
47
+ continue;
48
+ }
49
+ throw new JevError(`Could not reach TypeSafe: ${error?.name === "TimeoutError" ? "timed out" : error?.message}`, 0);
50
+ }
51
+ if (res.ok) {
52
+ const data = await res.json();
53
+ if (!data || typeof data.answers !== "object") throw new JevError("TypeSafe answered without answers.", res.status);
54
+ return data;
55
+ }
56
+ if ((res.status === 429 || res.status === 529) && attempt < retries) {
57
+ const after = Number(res.headers.get("retry-after"));
58
+ await sleep(Number.isFinite(after) && after > 0 ? after * 1000 : 500 * 2 ** attempt);
59
+ continue;
60
+ }
61
+ const detail = await res.text().catch(() => "");
62
+ const reason =
63
+ res.status === 401
64
+ ? "the API key was refused"
65
+ : res.status === 422
66
+ ? `the request was invalid: ${detail.slice(0, 300)}`
67
+ : res.status === 429
68
+ ? "rate limited; try again later"
69
+ : res.status === 529
70
+ ? "TypeSafe is overloaded; try again later"
71
+ : `HTTP ${res.status}`;
72
+ throw new JevError(`TypeSafe error: ${reason}`, res.status);
73
+ }
74
+ }
75
+
76
+ /** Question helpers (the shapes in reference/typesafe/api.md). */
77
+ export const noul = (instructions, criteria) => ({ type: "noul", instructions, ...(criteria ? { criteria } : {}) });
78
+ export const choice = (instructions, options) => ({ type: "choice", instructions, criteria: options });
79
+ export const score = (instructions, levels) => ({ type: "score", instructions, criteria: levels });
80
+
81
+ /** A fetch stand-in for tests: answers each request with `respond(body)` (a plain object) or an error status. */
82
+ export function fixtureFetch(respond) {
83
+ const calls = [];
84
+ const fetchImpl = async (url, init) => {
85
+ const body = JSON.parse(init.body);
86
+ calls.push({ url, body, headers: init.headers });
87
+ const out = await respond(body, calls.length);
88
+ if (typeof out === "number") return new Response(JSON.stringify({ error: "fixture" }), { status: out });
89
+ return new Response(JSON.stringify(out), { status: 200, headers: { "content-type": "application/json" } });
90
+ };
91
+ return { fetchImpl, calls };
92
+ }
package/src/load.mjs ADDED
@@ -0,0 +1,108 @@
1
+ // Reads the input: a folder of Markdown and text files, one such file, or a JSONL file of ready-made chunks.
2
+ import { readdirSync, readFileSync, statSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { blankFrontMatter, chunkText, normalize } from "./chunk.mjs";
5
+ import { UserError } from "./errors.mjs";
6
+
7
+ export const TEXT_EXTENSIONS = [".md", ".markdown", ".mdx", ".txt"];
8
+ const MARKDOWN_EXTENSIONS = [".md", ".markdown", ".mdx"];
9
+ const JSONL_EXTENSIONS = [".jsonl", ".ndjson"];
10
+
11
+ export function isJsonlPath(inputPath) {
12
+ return JSONL_EXTENSIONS.includes(path.extname(inputPath).toLowerCase());
13
+ }
14
+
15
+ /**
16
+ * Loads the input and returns documents in a stable order:
17
+ * [{ source, chunks: [{ id, label, number, line, text }] }], where `number` is the chunk's position in its document
18
+ * (from 1) and `line` is the line of the file (or of the JSONL file) where the chunk starts.
19
+ */
20
+ export function loadInput(inputPath, by) {
21
+ let stat;
22
+ try {
23
+ stat = statSync(inputPath);
24
+ } catch {
25
+ throw new UserError(`Cannot read ${inputPath}: there is no such file or folder.`);
26
+ }
27
+ if (stat.isDirectory()) return loadFolder(inputPath, by);
28
+ if (isJsonlPath(inputPath)) return loadJsonl(inputPath);
29
+ if (TEXT_EXTENSIONS.includes(path.extname(inputPath).toLowerCase())) {
30
+ return [loadFile(inputPath, path.basename(inputPath), by)];
31
+ }
32
+ throw new UserError(`${inputPath} is not a folder, a Markdown or text file (${TEXT_EXTENSIONS.join(", ")}) or a .jsonl file.`);
33
+ }
34
+
35
+ /** Every Markdown and text file below `root`, skipping node_modules and folders whose names start with a dot. */
36
+ export function listTextFiles(root) {
37
+ const found = [];
38
+ const walk = (dir) => {
39
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
40
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
41
+ const full = path.join(dir, entry.name);
42
+ if (entry.isDirectory()) walk(full);
43
+ else if (entry.isFile() && TEXT_EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) found.push(full);
44
+ }
45
+ };
46
+ walk(root);
47
+ return found
48
+ .map((full) => ({ full, source: path.relative(root, full).split(path.sep).join("/") }))
49
+ .sort((a, b) => (a.source < b.source ? -1 : a.source > b.source ? 1 : 0));
50
+ }
51
+
52
+ function loadFolder(root, by) {
53
+ const files = listTextFiles(root);
54
+ if (!files.length) throw new UserError(`${root} has no ${TEXT_EXTENSIONS.join(", ")} files.`);
55
+ return files.map(({ full, source }) => loadFile(full, source, by));
56
+ }
57
+
58
+ function loadFile(full, source, by) {
59
+ let text = normalize(readFileSync(full, "utf8"));
60
+ if (MARKDOWN_EXTENSIONS.includes(path.extname(full).toLowerCase())) text = blankFrontMatter(text);
61
+ const chunks = chunkText(text, by).map((chunk, i) => ({
62
+ id: `${source}#${i + 1}`,
63
+ label: `#${i + 1}`,
64
+ number: i + 1,
65
+ line: chunk.line,
66
+ text: chunk.text,
67
+ }));
68
+ return { source, chunks };
69
+ }
70
+
71
+ const firstString = (...values) => values.find((value) => typeof value === "string");
72
+ const firstName = (...values) => {
73
+ const value = values.find((v) => typeof v === "string" || typeof v === "number");
74
+ return value === undefined ? undefined : String(value);
75
+ };
76
+
77
+ /**
78
+ * One chunk per line: {"id": "...", "text": "...", "source": "..."}. The text may also be in "page_content" or
79
+ * "content", and the source in "metadata.source" or "metadata.file_name". Chunks are grouped by source and kept in
80
+ * line order, so a chunk's neighbours are the lines before and after it with the same source.
81
+ */
82
+ function loadJsonl(file) {
83
+ const name = path.basename(file);
84
+ const groups = new Map();
85
+ const lines = normalize(readFileSync(file, "utf8")).split("\n");
86
+ lines.forEach((raw, i) => {
87
+ if (!raw.trim()) return;
88
+ const where = `${name} line ${i + 1}`;
89
+ let row;
90
+ try {
91
+ row = JSON.parse(raw);
92
+ } catch {
93
+ throw new UserError(`${where} is not valid JSON.`);
94
+ }
95
+ if (!row || typeof row !== "object" || Array.isArray(row)) throw new UserError(`${where} is not a JSON object.`);
96
+ const text = firstString(row.text, row.page_content, row.content);
97
+ if (text === undefined) {
98
+ throw new UserError(`${where} has no "text" string (also accepted: "page_content" or "content").`);
99
+ }
100
+ const source = firstName(row.source, row.metadata?.source, row.metadata?.file_name) ?? name;
101
+ const id = firstName(row.id, row.chunk_id) ?? `line ${i + 1}`;
102
+ if (!groups.has(source)) groups.set(source, []);
103
+ const chunks = groups.get(source);
104
+ chunks.push({ id, label: id, number: chunks.length + 1, line: i + 1, text: normalize(text) });
105
+ });
106
+ if (!groups.size) throw new UserError(`${name} has no chunks.`);
107
+ return [...groups].map(([source, chunks]) => ({ source, chunks }));
108
+ }
package/src/report.mjs ADDED
@@ -0,0 +1,223 @@
1
+ // Formats results for people (the report, the dry run) and for programs (JSON). Every word printed comes from the
2
+ // input files or from the fixed text in this file; Jev returns only probabilities.
3
+ import { describeBy, estimateTokens } from "./chunk.mjs";
4
+ import { estimatePlan } from "./check.mjs";
5
+
6
+ const FIX_NAMES = {
7
+ keep: "keep",
8
+ merge_with_previous: "merge with previous",
9
+ merge_with_next: "merge with next",
10
+ split: "split",
11
+ };
12
+ const FIX_ORDER = Object.keys(FIX_NAMES);
13
+
14
+ const REASONS = {
15
+ needs_earlier_text: "needs earlier text",
16
+ points_outside: "points outside itself",
17
+ mixes_topics: "covers more than one topic",
18
+ unsure_standalone: "unclear if it stands alone",
19
+ unsure_outside: "unclear if it points outside itself",
20
+ unsure_fix: "unclear which fix",
21
+ answers_disagree: "answers disagree",
22
+ no_answer: "no answer from TypeSafe",
23
+ empty: "empty chunk",
24
+ too_large: "too large to check",
25
+ };
26
+
27
+ const LIST_LIMIT = 20;
28
+
29
+ const count = (n) => n.toLocaleString("en-US");
30
+ const plural = (n, word) => `${count(n)} ${word}${n === 1 ? "" : "s"}`;
31
+ const p2 = (value) => value.toFixed(2);
32
+
33
+ /** The start of a chunk on one line, for finding it in the file. */
34
+ export function preview(text, max = 76) {
35
+ const flat = text.replace(/\s+/g, " ").trim();
36
+ if (flat.length <= max) return flat;
37
+ const cut = flat.slice(0, max - 3);
38
+ const space = cut.lastIndexOf(" ");
39
+ return `${space > max / 2 ? cut.slice(0, space) : cut}...`;
40
+ }
41
+
42
+ function scope(meta, files) {
43
+ return meta.inputKind === "jsonl"
44
+ ? `${plural(files, "source")}, read from ${meta.jsonlName}`
45
+ : `${plural(files, "file")}, split by ${describeBy(meta.by)}`;
46
+ }
47
+
48
+ function reasonText(entry) {
49
+ return entry.reasons
50
+ .map((reason) =>
51
+ reason === "too_large" ? `${REASONS[reason]}, about ${count(estimateTokens(entry.chunk.text))} tokens` : REASONS[reason] ?? reason,
52
+ )
53
+ .join(", ");
54
+ }
55
+
56
+ function fixAnswer(fix) {
57
+ const ranked = Object.entries(fix.probabilities)
58
+ .filter(([, value]) => typeof value === "number")
59
+ .sort((a, b) => b[1] - a[1] || FIX_ORDER.indexOf(a[0]) - FIX_ORDER.indexOf(b[0]));
60
+ const shown = ranked.filter(([, value], i) => i === 0 || value >= 0.05).slice(0, 3);
61
+ const options = shown.map(([name, value]) => `${FIX_NAMES[name] ?? name} ${p2(value)}`).join(", ");
62
+ return `${options} (confidence ${p2(fix.confidence)})`;
63
+ }
64
+
65
+ function formatEntry(entry) {
66
+ const { chunk, verdict, answer } = entry;
67
+ const where = ` ${chunk.label} line ${chunk.line}`;
68
+ const lines = [
69
+ verdict === "fix" ? `${where} fix: ${FIX_NAMES[entry.fix]} (${reasonText(entry)})` : `${where} ${verdict} (${reasonText(entry)})`,
70
+ ];
71
+ if (answer) {
72
+ lines.push(
73
+ ` standalone ${p2(answer.standalone)} | outside reference ${p2(answer.outside)} | fix answer: ${fixAnswer(answer.fix)}`,
74
+ );
75
+ }
76
+ if (chunk.text.trim()) lines.push(` "${preview(chunk.text)}"`);
77
+ return lines;
78
+ }
79
+
80
+ /** The human-readable report: counts, then the chunks to fix or review, grouped by file, with probabilities. */
81
+ export function formatReport(result, meta) {
82
+ const { summary, usage, threshold } = result;
83
+ const lines = [
84
+ `chunk-standalone: ${plural(summary.chunks, "chunk")} in ${scope(meta, summary.files)}`,
85
+ `Model ${result.model}, ${plural(usage.requests, "request")}, ${count(usage.input_tokens)} input tokens, threshold ${threshold}`,
86
+ "",
87
+ `ok ${summary.ok} fix ${summary.fix} review ${summary.review}${summary.skipped ? ` skipped ${summary.skipped}` : ""}`,
88
+ ];
89
+ const listed = result.files
90
+ .map((file) => ({ file, entries: file.chunks.filter((entry) => entry.verdict !== "ok") }))
91
+ .filter(({ entries }) => entries.length);
92
+ for (const { file, entries } of listed) {
93
+ const tally = ["fix", "review", "skipped"]
94
+ .map((verdict) => [verdict, entries.filter((entry) => entry.verdict === verdict).length])
95
+ .filter(([, n]) => n)
96
+ .map(([verdict, n]) => `${verdict} ${n}`)
97
+ .join(", ");
98
+ lines.push("", `${file.source} (${plural(file.chunks.length, "chunk")}: ${tally})`);
99
+ for (const entry of entries) lines.push(...formatEntry(entry));
100
+ }
101
+ const quiet = result.files.length - listed.length;
102
+ if (!listed.length) lines.push("", "No chunks to fix or review.");
103
+ else if (quiet) lines.push("", `${plural(quiet, "other file")} had nothing to fix or review.`);
104
+ if (summary.fix || summary.review) {
105
+ lines.push(
106
+ "",
107
+ `fix: confident answers (threshold ${threshold}) found a problem and agree on the fix.`,
108
+ "review: the answers were not confident enough or disagreed. Read these chunks yourself.",
109
+ );
110
+ }
111
+ return `${lines.join("\n")}\n`;
112
+ }
113
+
114
+ /** The report as JSON: every chunk, its verdict, and the raw probabilities. */
115
+ export function toJson(result, meta) {
116
+ return {
117
+ tool: "chunk-standalone",
118
+ version: meta.version,
119
+ input: meta.inputKind,
120
+ by: meta.inputKind === "jsonl" ? null : describeBy(meta.by),
121
+ threshold: result.threshold,
122
+ batch: meta.batch,
123
+ model: result.model,
124
+ summary: result.summary,
125
+ usage: result.usage,
126
+ files: result.files.map((file) => ({
127
+ source: file.source,
128
+ chunks: file.chunks.map(({ chunk, verdict, fix, reasons, answer }) => ({
129
+ id: chunk.id,
130
+ number: chunk.number,
131
+ line: chunk.line,
132
+ estimated_tokens: estimateTokens(chunk.text),
133
+ verdict,
134
+ fix,
135
+ reasons,
136
+ standalone: answer?.standalone ?? null,
137
+ outside_reference: answer?.outside ?? null,
138
+ fix_probabilities: answer?.fix.probabilities ?? null,
139
+ fix_confidence: answer?.fix.confidence ?? null,
140
+ preview: preview(chunk.text),
141
+ })),
142
+ })),
143
+ };
144
+ }
145
+
146
+ /** The first chunk that has both neighbours in its request, to show its questions; else the first chunk. */
147
+ function exampleTarget(plan) {
148
+ for (const request of plan.requests) {
149
+ const target = request.targets.find((t) => t.at > 0 && t.at < request.body.state.chunks.length - 1);
150
+ if (target) return { request, target };
151
+ }
152
+ const request = plan.requests[0];
153
+ return request ? { request, target: request.targets[0] } : null;
154
+ }
155
+
156
+ /** What --dry-run prints: how the files were chunked, the requests, the token estimate and one chunk's questions. */
157
+ export function formatDryRun(plan, meta) {
158
+ const estimate = estimatePlan(plan);
159
+ const lines = [
160
+ "Dry run: nothing was sent to TypeSafe.",
161
+ "",
162
+ `${plural(plan.chunkCount, "chunk")} in ${scope(meta, plan.documents.length)}`,
163
+ ];
164
+ const shown = plan.documents.slice(0, LIST_LIMIT);
165
+ const width = Math.max(...shown.map((doc) => doc.source.length));
166
+ for (const doc of shown) {
167
+ const sizes = doc.chunks.map((chunk) => estimateTokens(chunk.text));
168
+ const range = sizes.length ? `, ${count(Math.min(...sizes))} to ${count(Math.max(...sizes))} tokens each` : "";
169
+ lines.push(` ${doc.source.padEnd(width)} ${plural(doc.chunks.length, "chunk")}${range}`);
170
+ }
171
+ if (plan.documents.length > shown.length) lines.push(` and ${plural(plan.documents.length - shown.length, "more file")}`);
172
+ for (const { source, chunk, reason } of plan.skipped) {
173
+ lines.push(`Skipped ${source} ${chunk.label} line ${chunk.line}: ${reasonText({ chunk, reasons: [reason] })}`);
174
+ }
175
+ lines.push("", `${plural(plan.requests.length, "request")} to ${meta.model}, about ${count(estimate.tokens)} input tokens`);
176
+ const example = exampleTarget(plan);
177
+ if (example) {
178
+ const { request, target } = example;
179
+ lines.push("", `Each chunk gets three questions. For ${request.source} ${target.chunk.label}, which is \`chunks[${target.at}]\` in its request:`);
180
+ for (const suffix of ["standalone", "outside", "fix"]) {
181
+ const id = `${target.key}_${suffix}`;
182
+ const question = request.body.questions[id];
183
+ const options = question.type === "choice" ? `: ${Object.keys(question.criteria).join(", ")}` : "";
184
+ lines.push(` ${id} (${question.type}${options})`, ` ${question.instructions}`);
185
+ }
186
+ }
187
+ lines.push("", "Run with --dry-run --json to see every request body.");
188
+ return `${lines.join("\n")}\n`;
189
+ }
190
+
191
+ /** What --dry-run --json prints: the estimate and every request body exactly as it would be sent. */
192
+ export function dryRunJson(plan, meta) {
193
+ const estimate = estimatePlan(plan);
194
+ return {
195
+ tool: "chunk-standalone",
196
+ version: meta.version,
197
+ dry_run: true,
198
+ input: meta.inputKind,
199
+ by: meta.inputKind === "jsonl" ? null : describeBy(meta.by),
200
+ batch: meta.batch,
201
+ model: meta.model,
202
+ summary: {
203
+ files: plan.documents.length,
204
+ chunks: plan.chunkCount,
205
+ requests: plan.requests.length,
206
+ skipped: plan.skipped.length,
207
+ },
208
+ estimated_input_tokens: estimate.tokens,
209
+ skipped: plan.skipped.map(({ source, chunk, reason }) => ({
210
+ source,
211
+ id: chunk.id,
212
+ line: chunk.line,
213
+ reason,
214
+ estimated_tokens: estimateTokens(chunk.text),
215
+ })),
216
+ requests: plan.requests.map((request, i) => ({
217
+ source: request.source,
218
+ chunks: request.targets.map((target) => target.chunk.id),
219
+ estimated_tokens: estimate.perRequest[i],
220
+ body: request.body,
221
+ })),
222
+ };
223
+ }