pi-dent-terms 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chris B
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,61 @@
1
- # Temporary Holding Version
1
+ # pi-dent-terms
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
+ A pi extension that manages a workspace's terms file — what each domain term means — and checks
4
+ the workspace's Markdown against it. pi-dent bundles it through its `pi.extensions`.
5
+
6
+ ## What a session gets
7
+
8
+ - **`Terms` tool.** `find` looks an entry up by id, label, form, reject phrase, or meaning, with
9
+ filters on status, key, group, and owner. `check` reports the workspace's findings. `add`,
10
+ `update`, `rename`, `merge`, `split`, `deprecate`, `reown`, and `import` change the terms file.
11
+ An operation writes the terms file and returns the document occurrences to edit; it never edits
12
+ a document itself.
13
+ - **After-edit check.** When the host's `edit` or `write` tool changes a Markdown document, the
14
+ extension appends that document's prose findings to the tool result, so a session sees its own
15
+ rejected wording at once.
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ pi install npm:pi-dent-terms # add it to pi's packages
21
+ pi -e npm:pi-dent-terms # or try it for one run
22
+ ```
23
+
24
+ Requires Node 26 or later, and a pi that provides the extension API
25
+ (`@earendil-works/pi-coding-agent`).
26
+
27
+ ## The terms file
28
+
29
+ `.pi/pi-dent/terms.yaml` under the workspace root, the top level of the Git working tree. It holds
30
+ one entry per concept: its `id`, `label`, `meaning`, the `owner` document that defines it, its
31
+ `group`, its `key`, its `status`, and its `history`. Change it through the `Terms` tool: an
32
+ operation records the history item and keeps ids and references consistent. A hand edit loses
33
+ both.
34
+
35
+ ## Findings
36
+
37
+ | Code | What it reports |
38
+ | --------- | ----------------------------------------------------------------------------------------------------------------------------------- |
39
+ | T001–T006 | Terms-file problems: syntax, duplicate labels, dangling ids, deprecation reasons, key use, and an owner that does not use its entry |
40
+ | P001–P002 | A rejected or deprecated phrase in prose |
41
+ | S001 | A `terms-ignore` comment that is not valid |
42
+
43
+ Silence one finding on one line with `<!-- terms-ignore P001: reason -->`.
44
+
45
+ ## Configuration
46
+
47
+ `terms.checkAfterEdit` in pi-dent's configuration file sets the after-edit check for the user; a
48
+ workspace's `settings.checkAfterEdit` in its terms file overrides it. Without a terms file the
49
+ check is off. A bad value or an unknown key is reported as a `pi-dent-terms: <message>` warning
50
+ when the session starts.
51
+
52
+ ## Documentation
53
+
54
+ - `specs/terms.md` — the terms file, matching, checks, and operations.
55
+ - `specs/terms-tool.md` — the `Terms` tool and the after-edit check.
56
+ - `docs/research/README.md` — the experiments behind the design.
57
+ - `AGENTS.md` — how to work on the repository.
58
+
59
+ ## License
60
+
61
+ MIT, see `LICENSE`.
package/index.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * pi-dent-terms - see specs/.
3
+ *
4
+ * Wiring only: every building block lives in lib/ (specs/terms-tool.md, Sections 1 and 4).
5
+ */
6
+
7
+ import { homedir } from "node:os";
8
+
9
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
10
+
11
+ import { createAfterEdit } from "./lib/after-edit.ts";
12
+ import { loadTermsConfig, type TermsConfig } from "./lib/config.ts";
13
+ import { createTermsTool } from "./lib/tool.ts";
14
+ import { realWorkspace } from "./lib/workspace.ts";
15
+
16
+ export default function piDentTerms(pi: ExtensionAPI): void {
17
+ // Read once per extension instance, at its first session_start (specs/terms-tool.md, 4.2).
18
+ // The project layer is `<cwd>` of the process (pi-dent's config-file.md, Section 1), not the session's.
19
+ let config: TermsConfig | undefined;
20
+
21
+ pi.registerTool(createTermsTool(realWorkspace));
22
+
23
+ const afterEdit = createAfterEdit({
24
+ io: realWorkspace,
25
+ homeDir: homedir(),
26
+ config: () => config,
27
+ });
28
+
29
+ pi.on("session_start", (_event, ctx) => {
30
+ if (config !== undefined) return;
31
+ config = loadTermsConfig({ cwd: process.cwd() });
32
+ if (!ctx.hasUI) return;
33
+ for (const message of config.diagnostics) {
34
+ ctx.ui.notify(`pi-dent-terms: ${message}`, "warning");
35
+ }
36
+ });
37
+
38
+ pi.on("tool_result", (event, ctx) => afterEdit(event, ctx.cwd));
39
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The after-edit check (specs/terms-tool.md, Section 4): the effective setting (4.1) and the
3
+ * handler that checks a document the host's `edit` or `write` tool changed (4.3).
4
+ */
5
+
6
+ import { basename, dirname, join, resolve } from "node:path";
7
+
8
+ import type { ToolResultEvent, ToolResultEventResult } from "@earendil-works/pi-coding-agent";
9
+
10
+ import { proseChecks, type ProseFinding } from "./checks.ts";
11
+ import type { TermsConfig } from "./config.ts";
12
+ import { parseTermsFile } from "./terms-file.ts";
13
+ import { findingText } from "./text.ts";
14
+ import { workspacePathOf, type WorkspaceAccess } from "./workspace.ts";
15
+
16
+ /** The content of a tool result (specs/terms-tool.md, Section 4.3). */
17
+ export type ResultContent = ToolResultEvent["content"];
18
+
19
+ /** The fields of a `tool_result` event the check reads. */
20
+ export interface ToolResultFields {
21
+ readonly toolName: string;
22
+ readonly input: Record<string, unknown>;
23
+ readonly content: ResultContent;
24
+ readonly isError: boolean;
25
+ }
26
+
27
+ /** The inputs of the handler (specs/terms-tool.md, Section 4.3). */
28
+ export interface AfterEditDependencies {
29
+ readonly io: WorkspaceAccess;
30
+ /** The user's home directory, for a leading `~`. */
31
+ readonly homeDir: string;
32
+ /** The configuration, once read at the first `session_start`; `undefined` before. */
33
+ readonly config: () => TermsConfig | undefined;
34
+ }
35
+
36
+ /**
37
+ * The effective after-edit setting of a workspace whose terms file exists (Section 4.1): the
38
+ * file's `settings.checkAfterEdit` when present, else the configuration's, else off.
39
+ */
40
+ export function effectiveCheckAfterEdit(
41
+ settings: boolean | undefined,
42
+ configured: boolean | undefined,
43
+ ): boolean {
44
+ return settings ?? configured ?? false;
45
+ }
46
+
47
+ /**
48
+ * The absolute target of an event's `path` (Section 4.3): one leading `@` removed, `~` or a
49
+ * leading `~/` read as `homeDir`, resolved against `cwd` when relative.
50
+ */
51
+ export function targetPath(raw: string, cwd: string, homeDir: string): string {
52
+ let path = raw.startsWith("@") ? raw.slice(1) : raw;
53
+ if (path === "~") {
54
+ path = homeDir;
55
+ } else if (path.startsWith("~/")) {
56
+ path = join(homeDir, path.slice(2));
57
+ }
58
+ return resolve(cwd, path);
59
+ }
60
+
61
+ /** The appended text of a check (Section 4.3): its header, then one line per finding. */
62
+ export function checkBlockText(path: string, findings: readonly ProseFinding[]): string {
63
+ return [
64
+ `Terms check of ${path}: ${findings.length} findings`,
65
+ ...findings.map((finding) => findingText(finding)),
66
+ ].join("\n");
67
+ }
68
+
69
+ /**
70
+ * The `tool_result` handler for `edit` and `write` (Section 4.3). It returns the event's content
71
+ * with the check block appended when findings remain, and `undefined` (the result unchanged) in
72
+ * every other case, a failure to run Git or read a file included.
73
+ */
74
+ export function createAfterEdit(
75
+ dependencies: AfterEditDependencies,
76
+ ): (event: ToolResultFields, cwd: string) => Promise<ToolResultEventResult | undefined> {
77
+ return async (event, cwd) => {
78
+ if (event.isError) return;
79
+ if (event.toolName !== "edit" && event.toolName !== "write") return;
80
+ const raw = event.input.path;
81
+ if (typeof raw !== "string") return;
82
+ // Only a `.md` target can be a document, so nothing else is looked at (terms.md, Section 1.2).
83
+ const target = targetPath(raw, cwd, dependencies.homeDir);
84
+ if (!basename(target).endsWith(".md")) return;
85
+ try {
86
+ return await checkWritten(dependencies, event.content, target, cwd);
87
+ } catch {
88
+ return;
89
+ }
90
+ };
91
+ }
92
+
93
+ async function checkWritten(
94
+ { io, config }: AfterEditDependencies,
95
+ content: ResultContent,
96
+ target: string,
97
+ cwd: string,
98
+ ): Promise<ToolResultEventResult | undefined> {
99
+ const root = await io.root(cwd);
100
+ const bytes = await io.readTerms(root);
101
+ if (bytes === undefined) return;
102
+ const terms = parseTermsFile(bytes);
103
+ if (!effectiveCheckAfterEdit(terms.settings.checkAfterEdit, config()?.checkAfterEdit)) {
104
+ return;
105
+ }
106
+
107
+ // The directory is resolved, so that a symbolic link in `cwd` does not hide the document.
108
+ const absolute = join(await io.realpath(dirname(target)), basename(target));
109
+ const path = workspacePathOf(root, absolute);
110
+ if (path === undefined) return;
111
+ const text = await io.document(root, path);
112
+ if (text === undefined) return;
113
+
114
+ const findings = proseChecks(path, text, terms);
115
+ if (findings.length === 0) return;
116
+ return {
117
+ content: [...content, { type: "text", text: checkBlockText(path, findings) }],
118
+ };
119
+ }
package/lib/changes.ts ADDED
@@ -0,0 +1,448 @@
1
+ /**
2
+ * Change checks (specs/terms.md, Section 5.4): the validation of a change set, the base workspace,
3
+ * the line pairing, the introduced findings, and the label occurrences in changed lines.
4
+ *
5
+ * The functions are pure: the change set is supplied by the caller, and the library reads no
6
+ * revision and runs no Git command. The inputs of `checkChanges` are those of `checkWorkspace`,
7
+ * with the change set appended.
8
+ */
9
+
10
+ import {
11
+ analyseWorkspace,
12
+ checkWorkspace,
13
+ type CheckFinding,
14
+ type WorkspaceCheck,
15
+ } from "./checks.ts";
16
+ import { TERMS_PATH, parseTermsFile } from "./terms-file.ts";
17
+ import { compareUtf16, normalise, quote } from "./text.ts";
18
+
19
+ /** A change of a change set (specs/terms.md, Section 5.4). */
20
+ export interface Change {
21
+ /** The changed file's path in the workspace. */
22
+ readonly path: string;
23
+ /** The file's text in the base workspace; null when it has no file at the base path. */
24
+ readonly before: string | null;
25
+ /** The file's path in the base workspace when it was moved; absent means `path`. */
26
+ readonly from?: string | undefined;
27
+ }
28
+
29
+ /** A label occurrence in a changed line (specs/terms.md, Section 5.4). */
30
+ export interface LabelOccurrence {
31
+ readonly id: string;
32
+ readonly label: string;
33
+ readonly meaning: string;
34
+ readonly path: string;
35
+ readonly line: number;
36
+ readonly column: number;
37
+ /** The occurrence's source text, normalised (Section 4.1). */
38
+ readonly text: string;
39
+ }
40
+
41
+ /** The check of a change set: the introduced findings and the label occurrences. */
42
+ export interface ChangeCheck extends WorkspaceCheck {
43
+ readonly occurrences: readonly LabelOccurrence[];
44
+ }
45
+
46
+ const CHANGE_PATH_RULE = `must be ${TERMS_PATH} or a workspace path ending with .md`;
47
+
48
+ const ENCODER = new TextEncoder();
49
+ const UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
50
+ const LINE_ENDING = /\r\n|\r|\n/;
51
+
52
+ // ---------------------------------------------------------------------------------------------
53
+ // Validation (specs/terms-tool.md, Section 1.2)
54
+
55
+ /** True when `path` is a workspace path (Section 1.1). */
56
+ function isWorkspacePath(path: string): boolean {
57
+ if (path === "") {
58
+ return false;
59
+ }
60
+ return path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
61
+ }
62
+
63
+ /** True when a `path` or `from` meets condition 1 of Section 5.4. */
64
+ function isChangePath(path: string): boolean {
65
+ return path === TERMS_PATH || (path.endsWith(".md") && isWorkspacePath(path));
66
+ }
67
+
68
+ /** True when `text` holds a lone surrogate: a UTF-16 code unit without its pair. */
69
+ function hasLoneSurrogate(text: string): boolean {
70
+ for (let i = 0; i < text.length; i++) {
71
+ const unit = text.charCodeAt(i);
72
+ if (unit >= 0xd800 && unit <= 0xdbff) {
73
+ const next = text.charCodeAt(i + 1);
74
+ if (!(next >= 0xdc00 && next <= 0xdfff)) {
75
+ return true;
76
+ }
77
+ i++;
78
+ } else if (unit >= 0xdc00 && unit <= 0xdfff) {
79
+ return true;
80
+ }
81
+ }
82
+ return false;
83
+ }
84
+
85
+ /** A change's base path: its `from`, else its `path` (Section 5.4). */
86
+ function basePathOf(change: Change): string {
87
+ return change.from ?? change.path;
88
+ }
89
+
90
+ /**
91
+ * The error text of the first failing check of specs/terms-tool.md, Section 1.2, for a change set,
92
+ * or `undefined` when the change set is valid (Section 5.4). Items are examined in order; for each,
93
+ * its `path`, then its `from` when set, then the item as a whole.
94
+ */
95
+ export function validateChanges(changes: readonly Change[]): string | undefined {
96
+ for (const [i, change] of changes.entries()) {
97
+ const at = `changes[${i}]`;
98
+ if (!isChangePath(change.path)) {
99
+ return `${at}.path ${CHANGE_PATH_RULE}`;
100
+ }
101
+ if (change.from !== undefined) {
102
+ if (!isChangePath(change.from)) {
103
+ return `${at}.from ${CHANGE_PATH_RULE}`;
104
+ }
105
+ if ((change.from === TERMS_PATH) !== (change.path === TERMS_PATH)) {
106
+ return `${at}.from must be ${TERMS_PATH} exactly when path is`;
107
+ }
108
+ }
109
+ if (change.from !== undefined && change.before === null) {
110
+ return `${at}.from needs a before text`;
111
+ }
112
+ if (change.before !== null && hasLoneSurrogate(change.before)) {
113
+ return `${at}.before holds a lone surrogate`;
114
+ }
115
+ const earlier = changes.slice(0, i);
116
+ if (earlier.some((other) => other.path === change.path)) {
117
+ return `${at}.path repeats ${quote(change.path)}`;
118
+ }
119
+ const basePath = basePathOf(change);
120
+ if (earlier.some((other) => basePathOf(other) === basePath)) {
121
+ const field = change.from === undefined ? "path" : "from";
122
+ return `${at}.${field} repeats the base path ${quote(basePath)}`;
123
+ }
124
+ }
125
+ return undefined;
126
+ }
127
+
128
+ // ---------------------------------------------------------------------------------------------
129
+ // Change check (specs/terms.md, Section 5.4)
130
+
131
+ /** One line number of a base text paired with one of a current text; both counted from 1. */
132
+ interface Pair {
133
+ readonly base: number;
134
+ readonly current: number;
135
+ }
136
+
137
+ /**
138
+ * A contiguous range of line numbers, empty when `start` is greater than `end`; the range of a last
139
+ * region ends at `Number.POSITIVE_INFINITY`, which also holds the lines past a text's last line.
140
+ */
141
+ interface LineRange {
142
+ readonly start: number;
143
+ readonly end: number;
144
+ }
145
+
146
+ /** A change with its texts, its line pairing, and its changed lines. */
147
+ interface ChangeAnalysis {
148
+ readonly change: Change;
149
+ readonly basePath: string;
150
+ readonly baseLines: readonly string[];
151
+ readonly currentLines: readonly string[];
152
+ readonly pairs: readonly Pair[];
153
+ /** The current lines that are in no pair. */
154
+ readonly changed: ReadonlySet<number>;
155
+ }
156
+
157
+ /** The base workspace of a change set (Section 5.4). */
158
+ interface BaseWorkspace {
159
+ readonly termsBytes: Uint8Array | undefined;
160
+ readonly documents: ReadonlyMap<string, string>;
161
+ }
162
+
163
+ /** `text` without a leading U+FEFF. */
164
+ function stripBom(text: string): string {
165
+ return text.startsWith("\uFEFF") ? text.slice(1) : text;
166
+ }
167
+
168
+ /** A text decoded as UTF-8 without a leading U+FEFF; the empty text when absent or invalid. */
169
+ function decodeText(bytes: Uint8Array | undefined): string {
170
+ if (bytes === undefined) {
171
+ return "";
172
+ }
173
+ try {
174
+ return stripBom(UTF8.decode(bytes));
175
+ } catch {
176
+ return "";
177
+ }
178
+ }
179
+
180
+ /** The lines of a text (Section 5.4): its parts between line endings, without a trailing empty one. */
181
+ function linesOf(text: string): string[] {
182
+ const parts = text.split(LINE_ENDING);
183
+ if (parts.at(-1) === "") {
184
+ parts.pop();
185
+ }
186
+ return parts;
187
+ }
188
+
189
+ /**
190
+ * The line pairing of a change (Section 5.4): a longest list of equal-line pairs, ascending in both
191
+ * numbers, the smallest sequence `i1, j1, i2, j2, …` among the longest.
192
+ */
193
+ function linePairing(base: readonly string[], current: readonly string[]): Pair[] {
194
+ const m = base.length;
195
+ const n = current.length;
196
+ if (m === 0 || n === 0) {
197
+ return [];
198
+ }
199
+ const width = n + 1;
200
+ // lcs[i, j] is the length of a longest common subsequence of base[i…] and current[j…].
201
+ const lcs = new Int32Array((m + 1) * width);
202
+ for (let i = m - 1; i >= 0; i--) {
203
+ for (let j = n - 1; j >= 0; j--) {
204
+ const down = lcs[(i + 1) * width + j] ?? 0;
205
+ const right = lcs[i * width + j + 1] ?? 0;
206
+ lcs[i * width + j] =
207
+ base[i] === current[j] ? (lcs[(i + 1) * width + j + 1] ?? 0) + 1 : Math.max(down, right);
208
+ }
209
+ }
210
+ const pairs: Pair[] = [];
211
+ let i = 0;
212
+ let j = 0;
213
+ while (i < m && j < n) {
214
+ const remaining = lcs[i * width + j] ?? 0;
215
+ if (remaining === 0) {
216
+ break;
217
+ }
218
+ // The smallest feasible current line for base line i; none means every longest pairing skips i.
219
+ let match = -1;
220
+ for (let b = j; b < n; b++) {
221
+ if (base[i] === current[b] && 1 + (lcs[(i + 1) * width + b + 1] ?? 0) === remaining) {
222
+ match = b;
223
+ break;
224
+ }
225
+ }
226
+ if (match === -1) {
227
+ i++;
228
+ } else {
229
+ pairs.push({ base: i + 1, current: match + 1 });
230
+ i++;
231
+ j = match + 1;
232
+ }
233
+ }
234
+ return pairs;
235
+ }
236
+
237
+ /** The base workspace of a change set (Section 5.4): each change undone. */
238
+ function baseWorkspace(
239
+ termsBytes: Uint8Array,
240
+ documents: ReadonlyMap<string, string>,
241
+ changes: readonly Change[],
242
+ ): BaseWorkspace {
243
+ const removed = new Set<string>();
244
+ for (const change of changes) {
245
+ removed.add(change.path);
246
+ removed.add(basePathOf(change));
247
+ }
248
+ const baseDocuments = new Map<string, string>();
249
+ for (const [path, text] of documents) {
250
+ if (!removed.has(path)) {
251
+ baseDocuments.set(path, text);
252
+ }
253
+ }
254
+ for (const change of changes) {
255
+ const basePath = basePathOf(change);
256
+ const before = change.before;
257
+ if (before !== null && basePath.endsWith(".md") && !before.includes("\u0000")) {
258
+ baseDocuments.set(basePath, stripBom(before));
259
+ }
260
+ }
261
+ const termsChange = changes.find((change) => change.path === TERMS_PATH);
262
+ let baseTermsBytes: Uint8Array | undefined = termsBytes;
263
+ if (termsChange !== undefined) {
264
+ baseTermsBytes = termsChange.before === null ? undefined : ENCODER.encode(termsChange.before);
265
+ }
266
+ return { termsBytes: baseTermsBytes, documents: baseDocuments };
267
+ }
268
+
269
+ /** A change with its base and current texts, its line pairing, and its changed lines. */
270
+ function analyseChange(
271
+ change: Change,
272
+ termsBytes: Uint8Array,
273
+ documents: ReadonlyMap<string, string>,
274
+ ): ChangeAnalysis {
275
+ const baseText = stripBom(change.before ?? "");
276
+ const currentText =
277
+ change.path === TERMS_PATH ? decodeText(termsBytes) : (documents.get(change.path) ?? "");
278
+ const baseLines = linesOf(baseText);
279
+ const currentLines = linesOf(currentText);
280
+ const pairs = linePairing(baseLines, currentLines);
281
+ const paired = new Set(pairs.map((pair) => pair.current));
282
+ const changed = new Set<number>();
283
+ for (let line = 1; line <= currentLines.length; line++) {
284
+ if (!paired.has(line)) {
285
+ changed.add(line);
286
+ }
287
+ }
288
+ return { change, basePath: basePathOf(change), baseLines, currentLines, pairs, changed };
289
+ }
290
+
291
+ /**
292
+ * The base lines of a finding of a change's file (Section 5.4): the base line of its pair, else the
293
+ * lines of the base region that corresponds to the region holding its line. The last region of the
294
+ * base text also holds every line number past its last line.
295
+ */
296
+ function baseRange(analysis: ChangeAnalysis, line: number): LineRange {
297
+ const paired = analysis.pairs.find((pair) => pair.current === line);
298
+ if (paired !== undefined) {
299
+ return { start: paired.base, end: paired.base };
300
+ }
301
+ let k = 0;
302
+ while (k < analysis.pairs.length && (analysis.pairs[k]?.current ?? 0) < line) {
303
+ k++;
304
+ }
305
+ const previous = k === 0 ? 0 : (analysis.pairs[k - 1]?.base ?? 0);
306
+ const next =
307
+ k === analysis.pairs.length
308
+ ? Number.POSITIVE_INFINITY
309
+ : (analysis.pairs[k]?.base ?? Number.POSITIVE_INFINITY);
310
+ return { start: previous + 1, end: next - 1 };
311
+ }
312
+
313
+ /** The key of the group of findings with the same base path, base lines, code, and message. */
314
+ function groupKey(basePath: string, range: LineRange, code: string, message: string): string {
315
+ return JSON.stringify([
316
+ basePath,
317
+ range.start,
318
+ range.end === Number.POSITIVE_INFINITY ? "end" : range.end,
319
+ code,
320
+ message,
321
+ ]);
322
+ }
323
+
324
+ /** The base count of a group: base findings at its base path, on its base lines, with its code. */
325
+ function countBase(
326
+ baseFindings: readonly CheckFinding[],
327
+ basePath: string,
328
+ range: LineRange,
329
+ code: string,
330
+ message: string,
331
+ ): number {
332
+ let count = 0;
333
+ for (const finding of baseFindings) {
334
+ if (
335
+ finding.path === basePath &&
336
+ finding.line >= range.start &&
337
+ finding.line <= range.end &&
338
+ finding.code === code &&
339
+ finding.message === message
340
+ ) {
341
+ count++;
342
+ }
343
+ }
344
+ return count;
345
+ }
346
+
347
+ /** Orders label occurrences by id, then path, line, and column (Section 5.4). */
348
+ function compareOccurrences(a: LabelOccurrence, b: LabelOccurrence): number {
349
+ return (
350
+ compareUtf16(a.id, b.id) ||
351
+ compareUtf16(a.path, b.path) ||
352
+ a.line - b.line ||
353
+ a.column - b.column
354
+ );
355
+ }
356
+
357
+ /** The label occurrences in changed lines (Section 5.4). */
358
+ function labelOccurrences(
359
+ analyses: readonly ChangeAnalysis[],
360
+ termsBytes: Uint8Array,
361
+ documents: ReadonlyMap<string, string>,
362
+ externalOwners: ReadonlyMap<string, string>,
363
+ ): LabelOccurrence[] {
364
+ const changedDocuments = analyses.filter((analysis) => analysis.change.path !== TERMS_PATH);
365
+ if (changedDocuments.length === 0) {
366
+ return [];
367
+ }
368
+ const ws = analyseWorkspace(parseTermsFile(termsBytes), documents, externalOwners);
369
+ const out: LabelOccurrence[] = [];
370
+ for (const analysis of changedDocuments) {
371
+ const doc = ws.documents.get(analysis.change.path);
372
+ if (doc === undefined) {
373
+ continue;
374
+ }
375
+ for (const occurrence of doc.occurrences) {
376
+ const { kind } = occurrence.variant;
377
+ if (kind !== "label" && kind !== "form") {
378
+ continue;
379
+ }
380
+ if (!analysis.changed.has(occurrence.line)) {
381
+ continue;
382
+ }
383
+ const entry = ws.entries.get(occurrence.variant.entry.id)?.entry;
384
+ if (entry === undefined) {
385
+ continue;
386
+ }
387
+ out.push({
388
+ id: entry.id,
389
+ label: entry.label,
390
+ meaning: entry.meaning,
391
+ path: doc.path,
392
+ line: occurrence.line,
393
+ column: occurrence.column,
394
+ text: normalise(occurrence.source),
395
+ });
396
+ }
397
+ }
398
+ return out.toSorted(compareOccurrences);
399
+ }
400
+
401
+ /**
402
+ * The check of a workspace with a change set (specs/terms.md, Section 5.4): the introduced findings
403
+ * and the label occurrences in changed lines. The change set MUST be valid (see `validateChanges`).
404
+ */
405
+ export function checkChanges(
406
+ termsBytes: Uint8Array,
407
+ documents: ReadonlyMap<string, string>,
408
+ externalOwners: ReadonlyMap<string, string>,
409
+ changes: readonly Change[],
410
+ ): ChangeCheck {
411
+ const current = checkWorkspace(termsBytes, documents, externalOwners);
412
+ const base = baseWorkspace(termsBytes, documents, changes);
413
+ const baseFindings =
414
+ base.termsBytes === undefined
415
+ ? []
416
+ : checkWorkspace(base.termsBytes, base.documents, externalOwners).findings;
417
+ const analyses = changes.map((change) => analyseChange(change, termsBytes, documents));
418
+ const byPath = new Map(analyses.map((analysis) => [analysis.change.path, analysis]));
419
+ const groups = new Map<string, { baseCount: number; seen: number }>();
420
+ const introduced: CheckFinding[] = [];
421
+ for (const finding of current.findings) {
422
+ const analysis = byPath.get(finding.path);
423
+ const basePath = analysis === undefined ? finding.path : analysis.basePath;
424
+ const range =
425
+ analysis === undefined
426
+ ? { start: finding.line, end: finding.line }
427
+ : baseRange(analysis, finding.line);
428
+ const key = groupKey(basePath, range, finding.code, finding.message);
429
+ let group = groups.get(key);
430
+ if (group === undefined) {
431
+ group = {
432
+ baseCount: countBase(baseFindings, basePath, range, finding.code, finding.message),
433
+ seen: 0,
434
+ };
435
+ groups.set(key, group);
436
+ }
437
+ group.seen++;
438
+ if (group.seen > group.baseCount) {
439
+ introduced.push(finding);
440
+ }
441
+ }
442
+ return {
443
+ findings: introduced,
444
+ documentCount: current.documentCount,
445
+ termsCount: current.termsCount,
446
+ occurrences: labelOccurrences(analyses, termsBytes, documents, externalOwners),
447
+ };
448
+ }