From 66ce7513f3dc25bcf7efabe903f73898f492d170 Mon Sep 17 00:00:00 2001 From: Paolo Rondot <47555486+PaoloRondot@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:35:46 +0100 Subject: [PATCH 1/3] Stamp refs with the text of their target, and add iref stamp A ref can end in a stamp: `@` and the first 8 hex digits of the SHA-256 of its target's text, as in `sync:/docs/auth.md#token-lifetime@f24671a0`. With a heading, the stamp covers the section and its subsections; without one, the whole file. A byte order mark, line ends, trailing spaces, blank lines, stamps, refs in comments and the comments that hold only refs do not count, so adding or stamping a ref does not make other stamps stale. The other text of comments counts, docstrings too, also when it holds a ref. A ref without a stamp works as before. - `check` fails on a stale stamp (new rule `stale-stamp`), and on a stamp on a directory, or on a file that is binary or cannot be read (`invalid-stamp`). Under the first stale stamp of a section, it lists every ref in the repo to that section, to a section in it or around it, or to its file, also the refs without a stamp. In JSON, each record has its stamp, and a stale one also the list of refs. - `stamp ...` writes the current stamp into the stamped refs in the paths, once someone has checked them, and prints `@old -> @new`. `--to [#heading]` keeps the refs to one file or heading (a heading that the file does not have is an error), and `--add P` also stamps the `P:` refs that have none. A broken ref is not stamped, and it makes the command exit 1, as does a file that it does not write: a symlink to a file outside the paths, or a file that is not valid UTF-8. A file that two paths reach is written once. - A suggested fix keeps the stamp, so that `check` compares it with the new target. A path that the repo has as written, `@` and all, also a file that git ignores, is a path, in a check and in a stamp, and `iref:@3f9a1c2e` is a bare path as before. - `Repo.stamp` caches the stamps of a file until `invalidate`, which now also forgets the symlinks to the file, and tells whether it forgot any. The extension invalidates a file on any change and when its editor closes, because a stamp can cover any file, and rechecks the open documents only when it forgot some. - The README, the guide (with a new "Fix a stale stamp" procedure) and the extension's README describe stamps. Co-Authored-By: Claude Opus 5.5 --- DEVELOPMENT.md | 2 +- README.md | 81 +++++++++++++- packages/cli/src/format.ts | 32 +++++- packages/cli/src/main.ts | 174 +++++++++++++++++++++++++++--- packages/cli/test/cli.test.ts | 160 +++++++++++++++++++++++++++ packages/core/src/check.ts | 40 +++++-- packages/core/src/index.ts | 3 +- packages/core/src/repo.ts | 64 ++++++++++- packages/core/src/resolve.ts | 4 + packages/core/src/stamp.ts | 118 ++++++++++++++++++++ packages/core/src/syntax.ts | 17 ++- packages/core/test/check.test.ts | 42 +++++++- packages/core/test/stamp.test.ts | 111 +++++++++++++++++++ packages/core/test/syntax.test.ts | 19 ++++ packages/vscode/README.md | 3 +- packages/vscode/src/extension.ts | 12 ++- packages/vscode/src/repos.ts | 10 +- skills/iref/SKILL.md | 67 ++++++++++-- 18 files changed, 911 insertions(+), 48 deletions(-) create mode 100644 packages/core/src/stamp.ts create mode 100644 packages/core/test/stamp.test.ts diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 75b1ad2..96591b5 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -7,7 +7,7 @@ design is in the "Proposal: Cross-File Reference System" doc (2026-10-19). | Folder | Package | Contents | | ------------------ | ---------------------------- | ------------------------------------------------------------------------ | -| `packages/core/` | `@interref/core` | Comment lexer, scanner, path resolution, Markdown headings, checks. Used by both tools. | +| `packages/core/` | `@interref/core` | Comment lexer, scanner, path resolution, Markdown headings, stamps, checks. Used by both tools. | | `packages/cli/` | `@normal-computing/interref` | The command-line tool. Its commands are `interref` and `iref`. | | `packages/vscode/` | `vscode-interref` | The VS Code extension. Attached to each GitHub release as a `.vsix`. | diff --git a/README.md b/README.md index 8059a62..0645a79 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ iref:./relative/to/this/file iref:../also/relative iref:/some/doc.md#heading-slug iref:#heading-in-this-file +sync:/some/doc.md#heading-slug@3f9a1c2e ``` - A path starts with `/` (from the repo root), `./` or `../` (from the directory of the file that @@ -67,6 +68,7 @@ iref:#heading-in-this-file - Percent-encode spaces, `#` and `%` in paths (`%20`, `%23`, `%25`). - The ref ends at whitespace, a quote, a backtick or a bracket. A trailing `-->`, `*/` or `. , ; : ! ?` is not part of it. +- A ref can end in a [stamp](#stamps): `@` and 8 hex digits. - Write `iref\:` to show the syntax in a comment without making a ref. ### Where a ref counts @@ -143,6 +145,78 @@ Note: some site generators, for example MkDocs, make heading ids differently fro merges repeated hyphens. Use the GitHub form. When a slug is wrong, `interref check` and the editor suggest the nearest correct slug. +### Stamps + +A stamp ends a ref: `@` and the first 8 hex digits of the SHA-256 of the target's text. It records +the text that someone checked the ref against. When that text changes, `interref check` fails on the +ref (`stale-stamp`), so that someone reads the change and updates the file that holds the ref. + +```typescript +// TTL must match the docs: sync:/docs/auth.md#token-lifetime@f24671a0 +``` + +- With a heading fragment, the stamp covers the section: the heading and its subsections, up to the + next heading of the same or a higher level. Without one, it covers the whole file. A directory, or + a file that is binary or cannot be read, has no stamp (`invalid-stamp`). +- A byte order mark, line ends, trailing spaces and blank lines do not count. Neither do stamps, + refs in comments, comments that hold only refs, and the spaces next to them. Thus adding a ref to + a section, or stamping one, does not make the stamps of other refs to it stale. +- The other text of comments counts, doc comments and docstrings too: a changed docstring makes the + stamps of the refs to its file stale, also when the docstring holds a ref. +- A ref without a stamp works as before: a change to its target does not fail the check. +- A path that the repo has as written, such as `/lib/v@1a2b3c4d`, is a path, not a stamp. + +Do not write a stamp by hand. `interref stamp ...` writes the current stamp into each +stamped ref in the files, once you have checked that they agree with their targets. +`--add sync` also stamps the `sync:` refs that have no stamp yet: + +```console +$ interref stamp --add sync src config +config/auth.yaml:3:9 sync:/docs/auth.md#token-lifetime stamped @f24671a0 +src/auth/session.ts:1:29 sync:/docs/auth.md#token-lifetime stamped @f24671a0 +2 refs stamped (3 refs in 3 files) +``` + +After a change to the section, `interref check` shows each stale stamp. Under the first one of a +section, it lists every ref in the repo to that section, also those without a stamp, and the refs to +a section in it or around it and to its whole file: + +```console +$ interref check +config/auth.yaml:3:9 error sync:/docs/auth.md#token-lifetime@f24671a0 docs/auth.md#token-lifetime changed since this ref was stamped [stale-stamp] + refs to docs/auth.md#token-lifetime: + config/auth.yaml:3:9 sync:/docs/auth.md#token-lifetime@f24671a0 + src/auth/notes.py:1:7 iref:/docs/auth.md#token-lifetime + src/auth/session.ts:1:29 sync:/docs/auth.md#token-lifetime@f24671a0 +src/auth/session.ts:1:29 error sync:/docs/auth.md#token-lifetime@f24671a0 docs/auth.md#token-lifetime changed since this ref was stamped [stale-stamp] +2 broken refs (3 refs in 5 files) +``` + +With `--format json`, each record has its `stamp`, and a stale one also has the list of `refs` to +the section. + +To see what changed, find the commit that wrote the stamp, then compare the target with it: + +```sh +git log -1 --format=%H -S'@f24671a0' -- src/auth/session.ts +git diff -- docs/auth.md +``` + +Update each file in the list to agree with the new text. Then stamp only the refs that you +checked: `--to` keeps the refs to one file, or to one heading with `#`. A heading that the file does +not have is an error. + +```console +$ interref stamp src/auth/session.ts config/auth.yaml --to docs/auth.md#token-lifetime +config/auth.yaml:3:9 sync:/docs/auth.md#token-lifetime@f24671a0 @f24671a0 -> @9c41e7b2 +src/auth/session.ts:1:29 sync:/docs/auth.md#token-lifetime@f24671a0 @f24671a0 -> @9c41e7b2 +2 refs stamped (2 refs in 2 files) +``` + +A fix that `check` suggests for a moved file or heading keeps the stamp, so `check` still compares +it with the new target. `stamp` does not write through a symlink (the file that it points to is +stamped when it is in the paths too), and does not rewrite a file that is not valid UTF-8. + ## CLI Run it from anywhere in the repo that you want to check: @@ -156,6 +230,7 @@ src/auth/session.ts:3:5 error iref:/docs/auth.md#tokn no heading #tokn in doc | Command | Output | | ------------------------------------- | ------------------------------------------------------------------------ | | `interref check [...]` | Broken refs in the repo, or under the paths. Exit 1 if any. | +| `interref stamp ... [--to ]` | Write the current [stamp](#stamps) into the stamped refs in the paths, or only into those to `` (or `#`). `--add P` also stamps the `P:` refs that have none. | | `interref links ... [--to ]` | Refs that the files hold and where each one goes. | | `interref backlinks ...` | Refs in the repo that point at the files or directories. | | `interref graph []` | The link graph: `--format dot` (default), `mermaid`, `json` or `drawio`. | @@ -172,7 +247,9 @@ src/auth/session.ts:3:5 error iref:/docs/auth.md#tokn no heading #tokn in doc | `-v`, `--version` | Show the version. | Exit codes: 0 clean, 1 broken refs, 2 usage, git, config file, network or editor error. `links` and -`backlinks` also exit 1 when a ref that they list is broken. +`backlinks` also exit 1 when a ref that they list is broken, and `stamp` when a ref that it would +stamp is broken, or when it does not write a file: a symlink to a file outside the paths, or a file +that is not valid UTF-8. ### Paths from stdin @@ -265,6 +342,8 @@ source of the guide is [skills/iref/SKILL.md](skills/iref/SKILL.md). | `reserved-authority` | error | The ref uses `iref://` (or `sync://`, …), kept for cross-repo refs. | | `case-mismatch` | error | The path differs from a repo path only by case. | | `invalid-encoding` | error | The percent-encoding is bad. | +| `stale-stamp` | error | The target's text changed since the ref was stamped. | +| `invalid-stamp` | error | The stamp is on a directory, or on a file that is binary or cannot be read. | | `target-ignored` | warn | The target is untracked or ignored by git. | ### Config file diff --git a/packages/cli/src/format.ts b/packages/cli/src/format.ts index ba03f83..78ac631 100644 --- a/packages/cli/src/format.ts +++ b/packages/cli/src/format.ts @@ -1,6 +1,14 @@ /** Text, JSON and SARIF renderings of ref records. */ -import { displayPath, LineIndex, RULE_SEVERITY, type RefRecord, type Repo, type RuleId } from "@interref/core"; +import { + displayPath, + LineIndex, + RULE_SEVERITY, + type RefRecord, + type Repo, + type ResolvedTarget, + type RuleId, +} from "@interref/core"; export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; @@ -8,6 +16,17 @@ export function location(record: RefRecord): string { return `${record.source.path}:${record.source.line}:${record.source.col}`; } +/** The line of `check` for a ref that has a problem, with its fixes. */ +export function problemLine(record: RefRecord): string { + const hint = record.suggestions.length > 0 ? ` (fix: ${record.suggestions.join(" or ")})` : ""; + return `${location(record)} ${record.status} ${record.raw} ${record.message ?? ""} [${record.rule ?? ""}]${hint}`; +} + +/** What a stamp covers: a file, or the section of a heading such as `docs/spec.md#tokens`. */ +export function sectionOf(target: ResolvedTarget): string { + return target.fragment === undefined ? target.path : `${target.path}#${target.fragment.slug}`; +} + export function describeTarget(record: RefRecord): string { const target = record.target; if (target === undefined) return "?"; @@ -19,8 +38,8 @@ export function describeTarget(record: RefRecord): string { /** The record as the proposal's JSON shape, without editor-only offsets. */ export function recordJson(record: RefRecord): { [key: string]: JsonValue } { const json: { [key: string]: JsonValue } = { - source: { path: record.source.path, line: record.source.line, col: record.source.col }, - raw: record.raw, + ...refJson(record), + ...(record.stamp === undefined ? {} : { stamp: record.stamp }), target: null, status: record.status, }; @@ -37,6 +56,11 @@ export function recordJson(record: RefRecord): { [key: string]: JsonValue } { return json; } +/** Where a ref is written, and the ref. */ +export function refJson(record: RefRecord): { [key: string]: JsonValue } { + return { source: { path: record.source.path, line: record.source.line, col: record.source.col }, raw: record.raw }; +} + /** Prints `values` as one JSON array, or one value per line for ndjson. */ export function printJson(values: readonly JsonValue[], format: "json" | "ndjson"): void { if (format === "json") console.log(JSON.stringify(values, null, 2)); @@ -93,6 +117,8 @@ const RULE_TEXT: Readonly> = { "case-mismatch": "Path differs from a repo path only by case", "unsupported-fragment": "Only heading fragments are supported", "invalid-encoding": "Bad percent-encoding", + "stale-stamp": "Target text changed since the ref was stamped", + "invalid-stamp": "A directory, or a file that is binary or cannot be read, has no stamp", "target-ignored": "Target is untracked or ignored by git", }; diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index 7965d33..349ff22 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -1,28 +1,35 @@ #!/usr/bin/env node /** interref: outgoing refs, backlinks, broken refs and the link graph of a git repo. */ -import { readFileSync } from "node:fs"; +import { lstatSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; import { basename, resolve } from "node:path"; import { parseArgs } from "node:util"; import { ConfigError, GitError, graphView, + parseFragment, RefGraph, Repo, scanRepo, + sectionLines, + similarSlugs, toDot, toDrawio, toMermaid, type RefRecord, + type ResolvedTarget, } from "@interref/core"; import { contextBlock, describeTarget, location, printJson, + problemLine, recordJson, + refJson, sarif, + sectionOf, type ContextOptions, type JsonValue, } from "./format.js"; @@ -48,6 +55,7 @@ Commands: links ... [--to ] Refs written in the files, optionally only those that reach backlinks ... Refs in the repo that point at the files or directories check [...] Report broken refs in the repo or under the paths + stamp ... [--to ] Write the current stamp of the target into each stamped ref in the paths graph [] Export the link graph, whole repo or around one file (> x.drawio) install-extension Install or update the VS Code extension from the newest GitHub release @@ -57,6 +65,8 @@ Options: -C N, -A N, -B N Show N lines of context around each ref where it is written -T N, --show-target N Show N lines of the target, from the heading or the top --format F text | json | ndjson, plus sarif for check; dot | mermaid | json | drawio for graph + --add P stamp: also stamp the P: refs that have no stamp (repeat for more protocols) + --to # stamp: only the refs to that heading (--to : to the file or its headings) --editor CMD install-extension: the editor's command (default code; also cursor, windsurf, codium) --prerelease install-extension: also use prereleases --check install-extension: only tell if an update is available @@ -71,6 +81,9 @@ links and backlinks also exit 1 when a ref that they list is broken. Once a day, the CLI asks npm for a newer stable version. INTERREF_NO_UPDATE_CHECK=1 turns this off. A ref starts with a protocol name from the config file: iref: or sync: by default. Only heading fragments (#some-heading) are supported for now. iref is a short name for interref. +A ref can end in a stamp, @ and 8 hex digits of the SHA-256 of its target's text (iref:/a.md#b@3f9a1c2e). +check fails when the target changes; stamp writes the new stamp once you have checked the ref. +Stamp only the refs that you checked: --to keeps the refs to one file or heading. The guide is an Agent Skill file. Read it for best practices, or save it as a skill, for example ${NAME} --guide > .claude/skills/iref/SKILL.md or ${NAME} --guide > .agents/skills/iref/SKILL.md @@ -87,6 +100,7 @@ const OPTIONS = { "show-target": { type: "string", short: "T" }, format: { type: "string" }, to: { type: "string" }, + add: { type: "string", multiple: true }, editor: { type: "string" }, prerelease: { type: "boolean" }, check: { type: "boolean" }, @@ -266,34 +280,169 @@ function commandBacklinks(repo: Repo, values: Values, positionals: readonly stri return printRecords(repo, shown, values, outputFormat); } +/** Whether `path` is one of the roots or under one. Without roots (no arguments), every path is. */ +function under(roots: readonly string[] | undefined): (path: string) => boolean { + return (path) => roots === undefined || roots.some((root) => root === "" || path === root || path.startsWith(`${root}/`)); +} + +const plural = (n: number, noun: string): string => `${n} ${noun}${n === 1 ? "" : "s"}`; + function commandCheck(repo: Repo, values: Values, positionals: readonly string[]): number { const outputFormat = format(values.format, ["text", "json", "ndjson", "sarif"] as const); // With -, an empty list checks nothing; with no arguments, the whole repo. const roots = positionals.length === 0 ? undefined : repoPaths(repo, positionals); - const include = (path: string): boolean => - roots === undefined || roots.some((root) => root === "" || path === root || path.startsWith(`${root}/`)); - const scan = scanRepo(repo, include); + const scan = scanRepo(repo, under(roots)); const problems = scan.records.filter((record) => record.status !== "ok"); const errors = problems.filter((record) => record.status === "error").length; + // A section that changed since a stamp, and every ref in the repo to it, to a section in it or + // around it, or to its whole file: each one may need the change. + const changed = (record: RefRecord): ResolvedTarget | undefined => + record.rule === "stale-stamp" ? record.target : undefined; + const all = roots !== undefined && problems.some((record) => changed(record) !== undefined) ? scanRepo(repo).records : scan.records; + const lines = (target: ResolvedTarget): { first: number; last: number } | undefined => + sectionLines(repo.headings(target.path), target.fragment?.slug); + const refsTo = (section: ResolvedTarget): RefRecord[] => { + const outer = lines(section); + return all.filter((ref) => { + if (ref.target?.path !== section.path || ref.target.kind !== "file" || outer === undefined) return false; + // Sections are nested, so two that share a line are the same, or one is in the other. + const inner = lines(ref.target); + return inner !== undefined && inner.first < outer.last && outer.first < inner.last; + }); + }; if (outputFormat === "sarif") console.log(JSON.stringify(sarif(problems), null, 2)); - else if (outputFormat !== "text") printJson(problems.map(recordJson), outputFormat); - else { + else if (outputFormat !== "text") { + const json = problems.map((record) => { + const section = changed(record); + return section === undefined ? recordJson(record) : { ...recordJson(record), refs: refsTo(section).map(refJson) }; + }); + printJson(json, outputFormat); + } else { const context = contextOptions(values); + // The refs to a changed section show once, under its first stale stamp. + const listed = new Set(); for (const record of problems) { - const hint = record.suggestions.length > 0 ? ` (fix: ${record.suggestions.join(" or ")})` : ""; - console.log(`${location(record)} ${record.status} ${record.raw} ${record.message ?? ""} [${record.rule ?? ""}]${hint}`); + console.log(problemLine(record)); for (const extra of contextBlock(repo, record, context)) console.log(extra); + const section = changed(record); + if (section === undefined || listed.has(sectionOf(section))) continue; + listed.add(sectionOf(section)); + console.log(` refs to ${sectionOf(section)}:`); + for (const ref of refsTo(section)) console.log(` ${location(ref)} ${ref.raw}`); } const warnings = problems.length - errors; - const files = `${scan.filesScanned} file${scan.filesScanned === 1 ? "" : "s"}`; - const parts = [`${errors} broken ref${errors === 1 ? "" : "s"}`]; - if (warnings > 0) parts.push(`${warnings} warning${warnings === 1 ? "" : "s"}`); - console.log(`${parts.join(", ")} (${scan.records.length} refs in ${files})`); + const parts = [plural(errors, "broken ref")]; + if (warnings > 0) parts.push(plural(warnings, "warning")); + console.log(`${parts.join(", ")} (${scan.records.length} refs in ${plural(scan.filesScanned, "file")})`); } return errors > 0 ? 1 : 0; } +/** The target of `stamp --to`: a file, and the slug of one of its headings after `#`. */ +function stampTarget(repo: Repo, argument: string): { path: string; slug?: string } { + const hash = argument.indexOf("#"); + const path = repoPath(repo, hash < 0 ? argument : argument.slice(0, hash)); + if (hash < 0) return { path }; + const fragment = parseFragment(argument.slice(hash + 1)); + if (!fragment.ok) throw new UsageError(`--to ${argument}: ${fragment.problem.message}`); + const { slug } = fragment.value; + const slugs = repo.headings(path).map((heading) => heading.slug); + if (!slugs.includes(slug)) { + const near = similarSlugs(slug, slugs)[0]; + throw new UsageError(`--to ${argument}: no heading #${slug} in ${path}${near === undefined ? "" : `; did you mean #${near}?`}`); + } + return { path, slug }; +} + +/** + * Writes the current stamp of the target into each stamped ref in the paths, and into the refs of + * the `--add` protocols that have none. `--to` keeps only the refs to one file or heading. A broken + * ref is not stamped: it shows as in `check`. + */ +function commandStamp(repo: Repo, values: Values, positionals: readonly string[]): number { + format(values.format, ["text"] as const); + if (positionals.length === 0) throw new UsageError("stamp needs a path"); + const add = new Set(values.add); + for (const protocol of add) { + if (!repo.config.protocols.includes(protocol)) { + throw new UsageError(`--add ${protocol}: the protocols are ${repo.config.protocols.join(", ")}`); + } + } + const to = values.to === undefined ? undefined : stampTarget(repo, values.to); + const wanted = (record: RefRecord): boolean => + (record.stamp !== undefined || add.has(record.raw.slice(0, record.raw.indexOf(":")))) && + (to === undefined || (record.targetPath === to.path && (to.slug === undefined || record.target?.fragment?.slug === to.slug))); + const scan = scanRepo(repo, under(repoPaths(repo, positionals))); + // The new stamps, by the file that holds the refs. + const edits = new Map(); + let broken = 0; + for (const record of scan.records) { + if (!wanted(record)) continue; + const target = record.target; + const usable = record.status !== "error" || record.rule === "stale-stamp"; + const stamp = usable && target?.kind === "file" ? repo.stamp(target.path, target.fragment?.slug) : undefined; + if (stamp === undefined) { + // A ref to a directory has no stamp; only a ref that already has one is an error. + if (record.status === "error") { + console.log(problemLine(record)); + broken++; + } + continue; + } + if (stamp === record.stamp) continue; + const list = edits.get(record.source.path) ?? []; + list.push({ record, stamp }); + edits.set(record.source.path, list); + } + + // The files written so far, by their real path. A symlink is not written through: the file that it + // points to is written when it is in the paths too. A file that two paths reach is written once: + // a second write would put its stamps at the offsets of the text before the first. + const written = new Map(); + let stamped = 0; + let refused = 0; + for (const [path, list] of edits) { + const file = repo.absolute(path); + if (lstatSync(file).isSymbolicLink()) { + const target = repo.relative(file); + if (target === undefined || !edits.has(target)) { + console.log(`${path} not stamped: a symlink; stamp the file that it points to`); + refused++; + } + continue; + } + const real = realpathSync.native(file); + const same = written.get(real); + if (same !== undefined) { + console.log(`${path} not stamped: the same file as ${same}`); + continue; + } + // Reading replaces the bytes that are not UTF-8, so writing the text back would change them. + let text = repo.text(path) ?? ""; + if (!Buffer.from(text, "utf8").equals(readFileSync(file))) { + console.log(`${path} not stamped: it is not valid UTF-8, and stamp would change its bytes`); + refused++; + continue; + } + for (const { record, stamp } of list.toReversed()) { + const unstamped = record.stamp === undefined ? record.raw : record.raw.slice(0, -record.stamp.length - 1); + text = `${text.slice(0, record.start)}${unstamped}@${stamp}${text.slice(record.end)}`; + } + writeFileSync(file, text); + written.set(real, path); + for (const { record, stamp } of list) { + console.log(`${location(record)} ${record.raw} ${record.stamp === undefined ? "stamped" : `@${record.stamp} ->`} @${stamp}`); + } + stamped += list.length; + } + const parts = [`${plural(stamped, "ref")} stamped`]; + if (broken > 0) parts.push(plural(broken, "broken ref")); + if (refused > 0) parts.push(`${plural(refused, "file")} not stamped`); + console.log(`${parts.join(", ")} (${plural(scan.records.length, "ref")} in ${plural(scan.filesScanned, "file")})`); + return broken > 0 || refused > 0 ? 1 : 0; +} + function commandGraph(repo: Repo, values: Values, positionals: readonly string[]): number { const outputFormat = format(values.format, ["dot", "mermaid", "json", "drawio"] as const); if (positionals.length > 1) throw new UsageError("graph takes at most one file"); @@ -338,6 +487,7 @@ const COMMANDS: Readonly { }); }); +describe("stamps", () => { + let repo = ""; + const run = (...args: string[]): { code: number | null; stdout: string; stderr: string } => { + const result = spawnSync(process.execPath, [CLI, ...args], { cwd: repo, encoding: "utf8" }); + return { code: result.status, stdout: result.stdout, stderr: result.stderr }; + }; + const read = (path: string): string => readFileSync(join(repo, path), "utf8"); + // The stamps of the sections "Tokens" and "Sessions": their lines without the blank ones. + const tokens = createHash("sha256").update("## Tokens\nA token lasts 15 minutes.").digest("hex").slice(0, 8); + const sessions = createHash("sha256").update("## Sessions\nA session ends after 8 hours.").digest("hex").slice(0, 8); + + before(() => { + repo = realpathSync(mkdtempSync(join(tmpdir(), "refs-stamps-"))); + const files: Record = { + ".interref.toml": 'yaml-values = ["model/**"]\n', + "docs/spec.md": "# Spec\n\n## Tokens\n\nA token lasts 15 minutes.\n\n## Sessions\n\nA session ends after 8 hours.\n", + "src/model.py": "# sync:/docs/spec.md#tokens@00000000\nTOKEN_MINUTES = 15\n", + "src/notes.ts": "// iref:/docs/spec.md#tokens\n", + "model/limits.yaml": "tokens:\n spec: sync:/docs/spec.md#tokens\n", + "docs/index.md": "\n\n\n", + }; + for (const [path, content] of Object.entries(files)) { + mkdirSync(dirname(join(repo, path)), { recursive: true }); + writeFileSync(join(repo, path), content); + } + execFileSync("git", ["init", "-q"], { cwd: repo }); + execFileSync("git", ["add", "-A"], { cwd: repo }); + }); + + after(() => rmSync(repo, { recursive: true, force: true })); + + it("check fails on a stale stamp and lists every ref to the changed section, to a section around it and to its file", () => { + const { code, stdout } = run("check"); + assert.equal(code, 1); + assert.equal( + stdout, + [ + "src/model.py:1:3 error sync:/docs/spec.md#tokens@00000000 docs/spec.md#tokens changed since this ref was stamped [stale-stamp]", + " refs to docs/spec.md#tokens:", + " docs/index.md:1:6 iref:/docs/spec.md", + " docs/index.md:2:6 iref:/docs/spec.md#spec", + " model/limits.yaml:2:9 sync:/docs/spec.md#tokens", + " src/model.py:1:3 sync:/docs/spec.md#tokens@00000000", + " src/notes.ts:1:4 iref:/docs/spec.md#tokens", + "1 broken ref (6 refs in 6 files)", + "", + ].join("\n"), + ); + }); + + it("check --format json gives the stamp and the refs to the changed section", () => { + const json = JSON.parse(run("check", "src", "--format", "json").stdout) as { + stamp?: string; + rule?: string; + refs?: { source: { path: string; line: number; col: number }; raw: string }[]; + }[]; + assert.equal(json.length, 1); + assert.equal(json[0]?.stamp, "00000000"); + assert.equal(json[0]?.rule, "stale-stamp"); + assert.deepEqual( + json[0]?.refs?.map((ref) => `${ref.source.path}:${ref.source.line}:${ref.source.col} ${ref.raw}`), + [ + "docs/index.md:1:6 iref:/docs/spec.md", + "docs/index.md:2:6 iref:/docs/spec.md#spec", + "model/limits.yaml:2:9 sync:/docs/spec.md#tokens", + "src/model.py:1:3 sync:/docs/spec.md#tokens@00000000", + "src/notes.ts:1:4 iref:/docs/spec.md#tokens", + ], + ); + }); + + it("stamp writes the current stamps, and --add stamps the refs of a protocol that have none", () => { + const { code, stdout } = run("stamp", "src", "model", "--add", "sync"); + assert.equal(code, 0); + assert.equal( + stdout, + [ + `model/limits.yaml:2:9 sync:/docs/spec.md#tokens stamped @${tokens}`, + `src/model.py:1:3 sync:/docs/spec.md#tokens@00000000 @00000000 -> @${tokens}`, + "2 refs stamped (3 refs in 3 files)", + "", + ].join("\n"), + ); + assert.equal(read("src/model.py"), `# sync:/docs/spec.md#tokens@${tokens}\nTOKEN_MINUTES = 15\n`); + assert.equal(read("model/limits.yaml"), `tokens:\n spec: sync:/docs/spec.md#tokens@${tokens}\n`); + assert.equal(read("src/notes.ts"), "// iref:/docs/spec.md#tokens\n"); + assert.equal(run("check").code, 0); + assert.match(run("stamp", "src").stdout, /^0 refs stamped \(2 refs in 2 files\)$/mu); + }); + + it("stamp --to stamps only the refs to that heading, or to that file", () => { + writeFileSync(join(repo, "src/sessions.py"), "# sync:/docs/spec.md#sessions@00000000\n# sync:/docs/spec.md#tokens@00000000\n"); + const heading = run("stamp", "src", "--to", "docs/spec.md#sessions"); + assert.equal(heading.code, 0); + assert.equal( + heading.stdout, + [`src/sessions.py:1:3 sync:/docs/spec.md#sessions@00000000 @00000000 -> @${sessions}`, "1 ref stamped (4 refs in 3 files)", ""].join("\n"), + ); + assert.equal(read("src/sessions.py"), `# sync:/docs/spec.md#sessions@${sessions}\n# sync:/docs/spec.md#tokens@00000000\n`); + assert.match(run("stamp", "src", "--to", "docs/spec.md").stdout, /^1 ref stamped /mu); + assert.equal(read("src/sessions.py"), `# sync:/docs/spec.md#sessions@${sessions}\n# sync:/docs/spec.md#tokens@${tokens}\n`); + }); + + it("stamp rejects an --add protocol that the config does not have, and a heading that the file does not have", () => { + const { code, stderr } = run("stamp", "src", "--add", "nope"); + assert.equal(code, 2); + assert.match(stderr, /^interref: --add nope: the protocols are iref, sync$/mu); + const heading = run("stamp", "src", "--to", "docs/spec.md#Tokens"); + assert.equal(heading.code, 2); + assert.match(heading.stderr, /^interref: --to docs\/spec\.md#Tokens: no heading #Tokens in docs\/spec\.md; did you mean #tokens\?$/mu); + }); +}); + +describe("stamp writes each file once, and only valid UTF-8", () => { + let repo = ""; + const tokens = createHash("sha256").update("## Tokens\nA token lasts 15 minutes.").digest("hex").slice(0, 8); + const sessions = createHash("sha256").update("## Sessions\nA session ends after 8 hours.").digest("hex").slice(0, 8); + const latin1 = Buffer.from("# caf\u00e9 sync:/docs/spec.md#tokens\n", "latin1"); + + before(() => { + repo = realpathSync(mkdtempSync(join(tmpdir(), "refs-stamp-files-"))); + mkdirSync(join(repo, "docs")); + mkdirSync(join(repo, "src")); + writeFileSync(join(repo, "docs/spec.md"), "# Spec\n\n## Tokens\n\nA token lasts 15 minutes.\n\n## Sessions\n\nA session ends after 8 hours.\n"); + writeFileSync(join(repo, "src/model.py"), "# sync:/docs/spec.md#tokens\nTOKEN_MINUTES = 15 # sync:/docs/spec.md#sessions\n"); + symlinkSync("model.py", join(repo, "src/link.py")); + mkdirSync(join(repo, "lib")); + writeFileSync(join(repo, "lib/other.py"), "# sync:/docs/spec.md#tokens\n"); + symlinkSync("../lib/other.py", join(repo, "src/other.py")); + writeFileSync(join(repo, "src/latin1.py"), latin1); + execFileSync("git", ["init", "-q"], { cwd: repo }); + execFileSync("git", ["add", "-A"], { cwd: repo }); + }); + + after(() => rmSync(repo, { recursive: true, force: true })); + + it("skips a symlink and a file that is not valid UTF-8, and exits 1 unless the symlink's file is in the paths", () => { + const result = spawnSync(process.execPath, [CLI, "stamp", "src", "--add", "sync"], { cwd: repo, encoding: "utf8" }); + assert.equal(result.status, 1); + assert.equal( + result.stdout, + [ + "src/latin1.py not stamped: it is not valid UTF-8, and stamp would change its bytes", + `src/model.py:1:3 sync:/docs/spec.md#tokens stamped @${tokens}`, + `src/model.py:2:23 sync:/docs/spec.md#sessions stamped @${sessions}`, + "src/other.py not stamped: a symlink; stamp the file that it points to", + "2 refs stamped, 2 files not stamped (6 refs in 4 files)", + "", + ].join("\n"), + ); + assert.equal(readFileSync(join(repo, "lib/other.py"), "utf8"), "# sync:/docs/spec.md#tokens\n"); + assert.equal( + readFileSync(join(repo, "src/model.py"), "utf8"), + `# sync:/docs/spec.md#tokens@${tokens}\nTOKEN_MINUTES = 15 # sync:/docs/spec.md#sessions@${sessions}\n`, + ); + assert.deepEqual(readFileSync(join(repo, "src/latin1.py")), latin1); + }); +}); + describe("usage errors", () => { it("exit 2", () => { assert.equal(refs().code, 2); diff --git a/packages/core/src/check.ts b/packages/core/src/check.ts index 6d953d5..918937f 100644 --- a/packages/core/src/check.ts +++ b/packages/core/src/check.ts @@ -12,6 +12,7 @@ import { type HeadingFragment, type RuleId, } from "./resolve.js"; +import { literalPath } from "./stamp.js"; import { LineIndex, type RefMatch } from "./syntax.js"; export type Status = "ok" | "warn" | "error"; @@ -30,6 +31,8 @@ export interface RefRecord { /** Offsets of `raw` in the source text. */ readonly start: number; readonly end: number; + /** The stamp at the end of `raw`, without `@`. */ + readonly stamp?: string; /** Set when the path resolved to something that exists, even if the ref has a problem. */ readonly target?: ResolvedTarget; /** The repo path that the ref names, set when the path is valid, also when nothing is there. */ @@ -82,14 +85,23 @@ export function similarPaths(repo: Repo, path: string): string[] { return closest(path, siblings, Math.max(2, Math.floor(posix.basename(path).length / 3))); } +/** Slugs that the author probably meant: a near spelling, or a longer slug that starts with `slug`. */ +export function similarSlugs(slug: string, slugs: readonly string[]): string[] { + const prefixed = slugs.filter((candidate) => slug !== "" && candidate.startsWith(slug)); + const spelled = closest(slug, slugs, Math.max(3, Math.floor(slug.length / 3))); + return [...new Set([...spelled, ...prefixed])].slice(0, MAX_SUGGESTIONS); +} + /** Checks one ref written in `source` (a repo-relative path), with the rule settings of the config. */ -export function checkRef(repo: Repo, source: string, match: RefMatch, lines: LineIndex): RefRecord { +export function checkRef(repo: Repo, source: string, written: RefMatch, lines: LineIndex): RefRecord { + const match = literalPath(repo, source, written); const position = lines.position(match.start); let base: Omit = { source: { path: source, ...position }, raw: match.raw, start: match.start, end: match.end, + ...(match.stamp === undefined ? {} : { stamp: match.stamp }), }; const problem = (rule: RuleId, message: string, suggestions: readonly string[] = [], target?: ResolvedTarget): RefRecord => { const setting = repo.config.rules[rule] ?? RULE_SEVERITY[rule]; @@ -99,15 +111,19 @@ export function checkRef(repo: Repo, source: string, match: RefMatch, lines: Lin }; const fragmentSuffix = match.fragment === undefined ? "" : `#${match.fragment}`; + // A fix keeps the stamp, so that check still compares it with the new target. + const stampSuffix = match.stamp === undefined ? "" : `@${match.stamp}`; const resolved = resolveTarget(source, match.path, match.protocol); if (!resolved.ok) { - const suggestions = resolved.problem.rule === "bare-path" ? [`${match.protocol}:./${match.path}${fragmentSuffix}`] : []; + const suggestions = + resolved.problem.rule === "bare-path" ? [`${match.protocol}:./${match.path}${fragmentSuffix}${stampSuffix}`] : []; return problem(resolved.problem.rule, resolved.problem.message, suggestions); } const { path, style, trailingSlash } = resolved.value; base = { ...base, targetPath: path }; - const rewrite = (to: string, kind: EntryKind, slug = match.fragment): string => + const format = (to: string, kind: EntryKind, slug = match.fragment): string => formatRef(source, to, { style, directory: kind === "directory" && trailingSlash, slug, protocol: match.protocol }); + const rewrite = (to: string, kind: EntryKind, slug = match.fragment): string => format(to, kind, slug) + stampSuffix; let kind = repo.kind(path); let warning: { rule: RuleId; message: string } | undefined; @@ -158,10 +174,7 @@ export function checkRef(repo: Repo, source: string, match: RefMatch, lines: Lin const headings = repo.headings(path); const heading = headings.find((candidate) => candidate.slug === slug); if (heading === undefined) { - const slugs = headings.map((candidate) => candidate.slug); - const prefixed = slugs.filter((candidate) => slug !== "" && candidate.startsWith(slug)); - const spelled = closest(slug, slugs, Math.max(3, Math.floor(slug.length / 3))); - const near = [...new Set([...spelled, ...prefixed])].slice(0, MAX_SUGGESTIONS); + const near = similarSlugs(slug, headings.map((candidate) => candidate.slug)); const hint = near[0] === undefined ? "" : `; did you mean #${near[0]}?`; return problem( "missing-anchor", @@ -173,6 +186,19 @@ export function checkRef(repo: Repo, source: string, match: RefMatch, lines: Lin target = { ...target, line: heading.line }; } + if (match.stamp !== undefined) { + const slug = target.fragment?.slug; + const stamp = kind === "file" ? repo.stamp(path, slug) : undefined; + if (stamp === undefined) { + const what = kind === "directory" ? "a directory" : "a file that is binary or cannot be read"; + return problem("invalid-stamp", `${what} has no stamp`, [format(path, kind)], target); + } + if (stamp !== match.stamp) { + const section = slug === undefined ? path : `${path}#${slug}`; + return problem("stale-stamp", `${section} changed since this ref was stamped`, [], target); + } + } + if (warning !== undefined) return problem(warning.rule, warning.message, [], target); return { ...base, target, status: "ok", suggestions: [] }; } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 3c457be..f420839 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,6 +1,6 @@ export { commentSpans, findRefs, valueSpans } from "./comments.js"; export type { Span } from "./comments.js"; -export { checkRef, checkText, editDistance, scanRepo, similarPaths } from "./check.js"; +export { checkRef, checkText, editDistance, scanRepo, similarPaths, similarSlugs } from "./check.js"; export type { RefRecord, RepoScan, ResolvedTarget, Status } from "./check.js"; export { CONFIG_FILES, ConfigError, DEFAULT_CONFIG, excluder, globToRegExp, loadConfig, parseConfig } from "./config.js"; export type { Config, RuleSetting } from "./config.js"; @@ -14,5 +14,6 @@ export { findRepoRoot, GitError, readTextFromDisk, Repo } from "./repo.js"; export type { EntryKind, TextReader } from "./repo.js"; export { encodeRefPath, formatRef, parseFragment, resolveTarget, RULE_SEVERITY } from "./resolve.js"; export type { HeadingFragment, PathStyle, Problem, Result, RuleId, Severity, Target } from "./resolve.js"; +export { sectionLines } from "./stamp.js"; export { DEFAULT_PROTOCOLS, LineIndex, protocolPattern, scanRefs } from "./syntax.js"; export type { RefMatch } from "./syntax.js"; diff --git a/packages/core/src/repo.ts b/packages/core/src/repo.ts index 6bbdcd5..2c8d2c2 100644 --- a/packages/core/src/repo.ts +++ b/packages/core/src/repo.ts @@ -1,4 +1,4 @@ -/** A snapshot of one git repo: which paths exist, which are tracked, and their headings. */ +/** A snapshot of one git repo: which paths exist, which are tracked, their headings and stamps. */ import { execFile } from "node:child_process"; import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; @@ -6,6 +6,8 @@ import { dirname, isAbsolute, join, relative, sep } from "node:path"; import { promisify } from "node:util"; import { DEFAULT_CONFIG, excluder, globToRegExp, loadConfig, type Config } from "./config.js"; import { extractHeadings, isMarkdownPath, type Heading } from "./markdown.js"; +import { literalPath, stampLines, stampOf } from "./stamp.js"; +import type { RefMatch } from "./syntax.js"; const run = promisify(execFile); @@ -63,6 +65,10 @@ export class Repo { private readonly byLowerCase = new Map(); private readonly children = new Map>(); private readonly headingCache = new Map(); + /** By path: the lines that stamps cover (undefined when the file is not text), and the stamps by slug. */ + private readonly stampCache = new Map }>(); + /** By the real path of a file, the cached paths that are symlinks to it, so that `invalidate` forgets them too. */ + private readonly linksTo = new Map>(); private readonly excluded: (path: string) => boolean; private readonly yamlValues: readonly RegExp[]; @@ -216,6 +222,15 @@ export class Repo { return this.readText(this.absolute(path)); } + /** Notes the real path of a path that is about to be cached, when it is a symlink. */ + private noteLink(path: string): void { + const real = this.relative(this.absolute(path)); + if (real === undefined || real === path) return; + const links = this.linksTo.get(real) ?? new Set(); + links.add(path); + this.linksTo.set(real, links); + } + /** The headings of a Markdown file, cached until `invalidate`. Other files have none. */ headings(path: string): readonly Heading[] { if (!isMarkdownPath(path)) return []; @@ -223,14 +238,53 @@ export class Repo { if (headings === undefined) { const text = this.text(path); headings = text === undefined ? [] : extractHeadings(text); + this.noteLink(path); this.headingCache.set(path, headings); } return headings; } - /** Forgets cached headings for one path, or for all paths. */ - invalidate(path?: string): void { - if (path === undefined) this.headingCache.clear(); - else this.headingCache.delete(path); + /** + * The stamp of a file, or of its section under the heading `slug`, cached until `invalidate`. + * Stamps, refs in comments and the comments that hold only refs do not count (see `stampLines`). + * Undefined for a file that is binary or cannot be read, or when no heading has the slug. + */ + stamp(path: string, slug?: string): string | undefined { + let cached = this.stampCache.get(path); + if (cached === undefined) { + cached = { stamps: new Map() }; + const text = this.text(path); + if (text !== undefined) { + const read = (ref: RefMatch): RefMatch => literalPath(this, path, ref); + cached.lines = stampLines(path, text, this.config.protocols, this.readsYamlValues(path), read); + } + this.noteLink(path); + this.stampCache.set(path, cached); + } + const key = slug === undefined ? "" : `#${slug}`; + if (!cached.stamps.has(key)) { + cached.stamps.set(key, cached.lines === undefined ? undefined : stampOf(cached.lines, this.headings(path), slug)); + } + return cached.stamps.get(key); + } + + /** + * Forgets cached headings and stamps for one path, and for the symlinks to it, or for all paths. + * Returns whether it forgot any, that is whether a ref that was checked may now resolve differently. + */ + invalidate(path?: string): boolean { + if (path === undefined) { + const cached = this.headingCache.size > 0 || this.stampCache.size > 0; + this.headingCache.clear(); + this.stampCache.clear(); + this.linksTo.clear(); + return cached; + } + let forgot = false; + for (const each of [path, ...(this.linksTo.get(path) ?? [])]) { + if (this.headingCache.delete(each)) forgot = true; + if (this.stampCache.delete(each)) forgot = true; + } + return forgot; } } diff --git a/packages/core/src/resolve.ts b/packages/core/src/resolve.ts index e5e0dd6..7f19861 100644 --- a/packages/core/src/resolve.ts +++ b/packages/core/src/resolve.ts @@ -12,6 +12,8 @@ export type RuleId = | "case-mismatch" | "unsupported-fragment" | "invalid-encoding" + | "stale-stamp" + | "invalid-stamp" | "target-ignored"; export type Severity = "error" | "warn"; @@ -25,6 +27,8 @@ export const RULE_SEVERITY: Readonly> = { "case-mismatch": "error", "unsupported-fragment": "error", "invalid-encoding": "error", + "stale-stamp": "error", + "invalid-stamp": "error", "target-ignored": "warn", }; diff --git a/packages/core/src/stamp.ts b/packages/core/src/stamp.ts new file mode 100644 index 0000000..095b98c --- /dev/null +++ b/packages/core/src/stamp.ts @@ -0,0 +1,118 @@ +/** + * Stamps. A ref can end in `@` and 8 hex digits, for example `#tokens@3f9a1c2e`: the start of the + * SHA-256 of its target's text when someone last checked the ref. When the target changes, the stamp + * no longer matches, and `check` reports the ref. + */ + +import { createHash } from "node:crypto"; +import { commentSpans, findRefs, type Span } from "./comments.js"; +import type { Heading } from "./markdown.js"; +import type { Repo } from "./repo.js"; +import { resolveTarget } from "./resolve.js"; +import { DEFAULT_PROTOCOLS, scanRefs, type RefMatch } from "./syntax.js"; + +/** The spaces after a removed comment or ref. */ +const SPACES = /[ \t]*/uy; + +/** A letter or a digit. A comment that has none besides its refs holds only refs. */ +const WORD = /[\p{L}\p{N}]/u; + +/** + * The ref without its stamp when the repo has its path as written, `@` and all, such as + * `/lib/v@1a2b3c4d`: in the file list, or on disk only, as a file that git ignores. + */ +export function literalPath(repo: Repo, source: string, match: RefMatch): RefMatch { + if (match.stamp === undefined || match.fragment !== undefined) return match; + const path = `${match.path}@${match.stamp}`; + const resolved = resolveTarget(source, path, match.protocol); + if (!resolved.ok || (repo.kind(resolved.value.path) ?? repo.kindOnDisk(resolved.value.path)) === undefined) return match; + return { ...match, path, stamp: undefined }; +} + +/** + * The lines of a file that its stamps cover. A comment that holds only refs does not count. In + * another comment, its refs do not count. Neither do the spaces after a removed comment or ref, or + * the spaces before it when none follow, so that `a b` reads `a b` and `text ref"""` + * reads `text"""`. The other text of comments counts, doc comments and docstrings too. With `values` + * (a YAML file that the config names in `yaml-values`), a ref in a value counts, but its stamp does + * not; `read` tells a stamp from the end of a path such as `/lib/v@1a2b3c4d` (see `literalPath`). A + * removed span keeps its line breaks, so each line keeps its number. A byte order mark, line ends + * (also a lone `\r`) and trailing spaces do not count. + */ +export function stampLines( + path: string, + text: string, + protocols: readonly string[] = DEFAULT_PROTOCOLS, + values = false, + read: (ref: RefMatch) => RefMatch = (ref) => ref, +): string[] { + const removed: Span[] = []; + // Removes a span and the spaces after it, or the spaces before it when none follow. + const remove = (start: number, end: number): void => { + SPACES.lastIndex = end; + const after = SPACES.exec(text)?.[0].length ?? 0; + let first = start; + if (after === 0) while (first > 0 && (text[first - 1] === " " || text[first - 1] === "\t")) first--; + removed.push({ start: first, end: end + after }); + }; + for (const comment of commentSpans(path, text) ?? []) { + const body = text.slice(comment.start, comment.end); + const refs = scanRefs(body, protocols); + if (refs.length === 0) continue; + const rest = refs.reduceRight((kept, ref) => kept.slice(0, ref.start) + kept.slice(ref.end), body); + if (!WORD.test(rest)) remove(comment.start, comment.end); + else for (const ref of refs) remove(comment.start + ref.start, comment.start + ref.end); + } + if (values) { + for (const ref of findRefs(path, text, protocols, true)) { + const stamp = ref.stamp === undefined ? undefined : read(ref).stamp; + if (stamp !== undefined) removed.push({ start: ref.end - stamp.length - 1, end: ref.end }); + } + } + let kept = ""; + let at = 0; + for (const span of removed.sort((a, b) => a.start - b.start)) { + if (span.end <= at) continue; + const start = Math.max(span.start, at); + kept += text.slice(at, start) + text.slice(start, span.end).replace(/[^\r\n]+/gu, ""); + at = span.end; + } + kept += text.slice(at); + // Each line of the file, with the lines that a lone `\r` makes joined by `\n` and blank ones dropped. + return kept + .replace(/^/u, "") + .split("\n") + .map((line) => + line + .split("\r") + .map((part) => part.trimEnd()) + .filter((part) => part !== "") + .join("\n"), + ); +} + +/** + * The lines of the section under the heading `slug`, from `first` up to `last` (not included, and + * 0-based): the heading and its subsections, up to the next heading of the same or a higher level. + * Without a slug, the whole file. Undefined when no heading has the slug. + */ +export function sectionLines(headings: readonly Heading[], slug?: string): { first: number; last: number } | undefined { + if (slug === undefined) return { first: 0, last: Number.POSITIVE_INFINITY }; + const index = headings.findIndex((heading) => heading.slug === slug); + const heading = headings[index]; + if (heading === undefined) return undefined; + const next = headings.slice(index + 1).find((candidate) => candidate.level <= heading.level); + return { first: heading.line - 1, last: next === undefined ? Number.POSITIVE_INFINITY : next.line - 1 }; +} + +/** + * The stamp of a file from its `stampLines`, or of its section under the heading `slug` (see + * `sectionLines`). Blank lines do not count, so with `stampLines`, adding a ref to the text does not + * change its stamp. Undefined when no heading has the slug. + */ +export function stampOf(lines: readonly string[], headings: readonly Heading[] = [], slug?: string): string | undefined { + const section = sectionLines(headings, slug); + if (section === undefined) return undefined; + const kept = lines.slice(section.first, section.last).filter((line) => line !== ""); + return createHash("sha256").update(kept.join("\n")).digest("hex").slice(0, 8); +} diff --git a/packages/core/src/syntax.ts b/packages/core/src/syntax.ts index e5b37f2..b893d80 100644 --- a/packages/core/src/syntax.ts +++ b/packages/core/src/syntax.ts @@ -27,8 +27,16 @@ export interface RefMatch { readonly path: string; /** The fragment without `#`, or undefined when the ref has no fragment. */ readonly fragment: string | undefined; + /** The stamp without `@`, or undefined when the ref has no stamp. */ + readonly stamp: string | undefined; } +/** + * A stamp ends a ref: `@` and 8 hex digits of the SHA-256 of the target's text (see `stamp.ts`). + * A path or a fragment comes before it, so `iref:@3f9a1c2e` is a bare path, as it was before stamps. + */ +const STAMP = /(?<=[^:#])@([0-9a-f]{8})$/u; + const TRAILING_PUNCTUATION = /[.,;:!?]$/u; /** @@ -63,14 +71,17 @@ export function scanRefs(text: string, protocols: readonly string[] = DEFAULT_PR const raw = trimRef(text, start, match[0], prefixLength); // A prefix with no path and no fragment, such as `# iref: ` in Python, is not a ref. if (raw.length === prefixLength) continue; - const hash = raw.indexOf("#"); + const stamp = STAMP.exec(raw)?.[1]; + const target = stamp === undefined ? raw : raw.slice(0, -stamp.length - 1); + const hash = target.indexOf("#"); refs.push({ raw, protocol, start, end: start + raw.length, - path: hash < 0 ? raw.slice(prefixLength) : raw.slice(prefixLength, hash), - fragment: hash < 0 ? undefined : raw.slice(hash + 1), + path: hash < 0 ? target.slice(prefixLength) : target.slice(prefixLength, hash), + fragment: hash < 0 ? undefined : target.slice(hash + 1), + stamp, }); } return refs; diff --git a/packages/core/test/check.test.ts b/packages/core/test/check.test.ts index 5974d85..8ef3b44 100644 --- a/packages/core/test/check.test.ts +++ b/packages/core/test/check.test.ts @@ -1,4 +1,5 @@ import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; import { mkdirSync, renameSync } from "node:fs"; import { join } from "node:path"; import { after, before, describe, it } from "node:test"; @@ -21,8 +22,10 @@ describe("checkText", () => { "src/db/config.go": "package db\n", "src/db/pool.go": "// iref:./config.go\n", "src/Readme.md": "# Readme\n", + "assets/logo.png": "\u0089PNG\r\n\u001a\n\u0000\u0000", + "lib/a@3f9a1c2e": "text\n", }, - { "notes/draft.md": "# Draft\n", "build/out.txt": "x\n" }, + { "notes/draft.md": "# Draft\n", "build/out.txt": "x\n", "build/v@1a2b3c4d": "x\n" }, ); repo = await Repo.open(fixture.root); }); @@ -111,6 +114,43 @@ describe("checkText", () => { assert.equal(only("docs/a.md", "iref:/docs/auth.md/").rule, "missing-file"); }); + it("checks stamps, and keeps the stamp in a fix", () => { + const lifetime = createHash("sha256").update("## Token lifetime\nText.").digest("hex").slice(0, 8); + assert.equal(only("src/auth/session.ts", `iref:/docs/auth.md#token-lifetime@${lifetime}`).status, "ok"); + const stale = only("src/auth/session.ts", "iref:/docs/auth.md#token-lifetime@00000000"); + assert.equal(stale.rule, "stale-stamp"); + assert.equal(stale.stamp, "00000000"); + // A fix keeps the stamp, so that the next check compares it with the new target. + assert.deepEqual(only("docs/tokens.md", "iref:./auth.md#token-lifetimes@00000000").suggestions, [ + "iref:./auth.md#token-lifetime@00000000", + ]); + assert.deepEqual(only("src/db/pool.go", "iref:./confg.go@00000000").suggestions, ["iref:./config.go@00000000"]); + assert.deepEqual(only("src/db/pool.go", "sync:config.go@00000000").suggestions, ["sync:./config.go@00000000"]); + assert.deepEqual(only("docs/a.md", "iref:/src/readme.md@00000000").suggestions, ["iref:/src/Readme.md@00000000"]); + }); + + it("reports a stamp on a directory or a binary file, with the ref without it as the fix", () => { + const directory = only("docs/a.md", "iref:/src/db/@00000000"); + assert.equal(directory.rule, "invalid-stamp"); + assert.deepEqual(directory.suggestions, ["iref:/src/db/"]); + const binary = only("docs/a.md", "iref:/assets/logo.png@00000000"); + assert.equal(binary.rule, "invalid-stamp"); + assert.equal(binary.message, "a file that is binary or cannot be read has no stamp"); + assert.deepEqual(binary.suggestions, ["iref:/assets/logo.png"]); + }); + + it("reads a path that ends in @ and 8 hex digits as a path when the repo has it, and a ref with nothing before @ as before", () => { + const literal = only("docs/a.md", "iref:/lib/a@3f9a1c2e"); + assert.equal(literal.status, "ok"); + assert.equal(literal.stamp, undefined); + assert.equal(literal.target?.path, "lib/a@3f9a1c2e"); + assert.equal(only("docs/a.md", "iref:/lib/b@3f9a1c2e").rule, "missing-file"); + const ignored = only("docs/a.md", "iref:/build/v@1a2b3c4d"); + assert.equal(ignored.rule, "target-ignored"); + assert.equal(ignored.stamp, undefined); + assert.equal(only("docs/a.md", "iref:@3f9a1c2e").rule, "bare-path"); + }); + it("finds refs only in comments", () => { const text = [ "// see iref:/docs/auth.md", diff --git a/packages/core/test/stamp.test.ts b/packages/core/test/stamp.test.ts new file mode 100644 index 0000000..4cb70fd --- /dev/null +++ b/packages/core/test/stamp.test.ts @@ -0,0 +1,111 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { symlinkSync } from "node:fs"; +import { join } from "node:path"; +import { after, before, describe, it } from "node:test"; +import { extractHeadings } from "../src/markdown.js"; +import { Repo } from "../src/repo.js"; +import { stampLines, stampOf } from "../src/stamp.js"; +import { DEFAULT_PROTOCOLS } from "../src/syntax.js"; +import { makeRepo } from "./fixture.js"; + +const sha = (text: string): string => createHash("sha256").update(text).digest("hex").slice(0, 8); + +describe("stamps", () => { + const stamp = (text: string, slug?: string, path = "docs/spec.md"): string | undefined => + stampOf(stampLines(path, text), extractHeadings(text), slug); + const spec = "# Spec\n\n## Tokens\n\nA token lasts 15 minutes.\n\n### Renewal\n\nA renewal takes 2 seconds.\n\n## Sessions\n\nA session ends after 8 hours.\n"; + + it("hashes a section with its subsections, without line ends, trailing spaces, blank lines and comments with a ref", () => { + const expected = sha("## Tokens\nA token lasts 15 minutes.\n### Renewal\nA renewal takes 2 seconds."); + assert.equal(stamp(spec, "tokens"), expected); + const edited = spec + .replace("A token lasts 15 minutes.", "A token lasts 15 minutes. \n\n") + .replace("A renewal takes", "A renewal takes") + .replaceAll("\n", "\r\n"); + assert.equal(stamp(`\uFEFF${edited}`, "tokens"), expected); + assert.equal(stamp(spec.replaceAll("\n", "\r")), stamp(spec)); + const changed = spec.replace("2 seconds", "3 seconds"); + assert.notEqual(stamp(changed, "tokens"), expected); + assert.notEqual(stamp(changed), stamp(spec)); + assert.equal(stamp(changed, "sessions"), stamp(spec, "sessions")); + assert.equal(stamp(spec, "nothing"), undefined); + }); + + it("counts the comments that hold no ref, doc comments and docstrings too", () => { + assert.notEqual(stamp(spec.replace("A token lasts 15 minutes.", "A token lasts 15 minutes. "), "tokens"), stamp(spec, "tokens")); + const model = '"""A token lasts 15 minutes."""\nTOKEN_MINUTES = 15 # sync:/docs/spec.md#tokens@3f9a1c2e\n'; + assert.equal(stamp(model, undefined, "src/model.py"), sha('"""A token lasts 15 minutes."""\nTOKEN_MINUTES = 15')); + assert.notEqual(stamp(model.replace("15 minutes", "30 minutes"), undefined, "src/model.py"), stamp(model, undefined, "src/model.py")); + }); + + it("counts the other text of a comment that holds a ref, but not the ref and the spaces next to it", () => { + const model = (docstring: string): string | undefined => stamp(`${docstring}\nTOKEN_MINUTES = 15\n`, undefined, "src/model.py"); + const plain = model('"""Tokens last 15 minutes."""'); + assert.equal(model('"""Tokens last 15 minutes. sync:/docs/spec.md#tokens@3f9a1c2e"""'), plain); + assert.notEqual(model('"""Tokens last 30 minutes. sync:/docs/spec.md#tokens@3f9a1c2e"""'), plain); + const note = spec.replace("A token lasts 15 minutes.", "A token lasts 15 minutes. "); + assert.equal(stamp(note.replace("configurable -->", "configurable sync:/src/x.py -->"), "tokens"), stamp(note, "tokens")); + assert.equal(stamp(note.replace("TTL is", "TTL iref:/src/x.py is"), "tokens"), stamp(note, "tokens")); + assert.notEqual(stamp(note.replace("configurable", "fixed"), "tokens"), stamp(note, "tokens")); + }); + + it("ends the section of a setext heading at the text of the next heading of its level", () => { + const setext = "Spec\n====\n\nTokens\n------\n\nA token lasts 15 minutes.\n\nSessions\n--------\n\nA session ends after 8 hours.\n"; + assert.equal(stamp(setext, "tokens"), sha("Tokens\n------\nA token lasts 15 minutes.")); + assert.equal(stamp(setext.replace("Sessions", "Logins"), "tokens"), sha("Tokens\n------\nA token lasts 15 minutes.")); + assert.equal(stamp(setext, "spec"), stamp(setext)); + }); + + it("leaves out the stamps of the refs in the values of a YAML file, but not the refs", () => { + const yaml = (ref: string): string[] => stampLines("model/limits.yaml", `tokens:\n spec: ${ref}\n`, DEFAULT_PROTOCOLS, true); + assert.deepEqual(yaml("sync:/docs/spec.md#tokens@3f9a1c2e"), yaml("sync:/docs/spec.md#tokens")); + assert.notDeepEqual(yaml("sync:/docs/spec.md#sessions"), yaml("sync:/docs/spec.md#tokens")); + }); +}); + +describe("Repo.stamp", () => { + let fixture: ReturnType; + + before(() => { + fixture = makeRepo({ + ".interref.toml": 'yaml-values = ["model/**"]\n', + "docs/spec.md": "# Spec\n\n## Tokens\n\nA token lasts 15 minutes.\n", + "src/model.py": "TOKEN_MINUTES = 15\n", + "lib/a@3f9a1c2e": "text\n", + "model/a1.yaml": "path: iref:/lib/a@3f9a1c2e\n", + "model/a2.yaml": "path: iref:/lib/a@00000000\n", + "model/b1.yaml": "path: iref:/lib/b@3f9a1c2e\n", + "model/b2.yaml": "path: iref:/lib/b@00000000\n", + }); + symlinkSync("spec.md", join(fixture.root, "docs/current.md")); + }); + after(() => fixture.dispose()); + + it("counts the end of a path such as /lib/a@3f9a1c2e in a YAML value, but not a stamp", async () => { + const repo = await Repo.open(fixture.root); + assert.notEqual(repo.stamp("model/a1.yaml"), repo.stamp("model/a2.yaml")); + assert.equal(repo.stamp("model/b1.yaml"), repo.stamp("model/b2.yaml")); + }); + + it("forgets the stamps and headings of a symlink when the file that it points to changes", async () => { + const repo = await Repo.open(fixture.root); + assert.equal(repo.stamp("docs/current.md", "tokens"), repo.stamp("docs/spec.md", "tokens")); + assert.equal(repo.invalidate("docs/spec.md"), true); + assert.equal(repo.invalidate("docs/spec.md"), false); + assert.equal(repo.headings("docs/current.md").length, 2); + assert.equal(repo.invalidate("docs/spec.md"), true); + }); + + it("caches the stamps of a file, and invalidate tells whether it forgot any", async () => { + const repo = await Repo.open(fixture.root); + assert.equal(repo.invalidate("docs/spec.md"), false); + assert.equal(repo.stamp("docs/spec.md", "tokens"), sha("## Tokens\nA token lasts 15 minutes.")); + assert.equal(repo.invalidate("src/model.py"), false); + assert.equal(repo.invalidate("docs/spec.md"), true); + assert.equal(repo.invalidate("docs/spec.md"), false); + assert.equal(repo.stamp("src/model.py"), sha("TOKEN_MINUTES = 15")); + assert.equal(repo.invalidate(), true); + assert.equal(repo.invalidate(), false); + }); +}); diff --git a/packages/core/test/syntax.test.ts b/packages/core/test/syntax.test.ts index 7465e0e..0c6e1a9 100644 --- a/packages/core/test/syntax.test.ts +++ b/packages/core/test/syntax.test.ts @@ -11,6 +11,25 @@ describe("scanRefs", () => { assert.deepEqual(raws("-- mirrored in iref:/src/models/user.py"), ["iref:/src/models/user.py"]); }); + it("splits a stamp off the end of a ref, and reads a ref without one as before", () => { + const parts = (text: string): unknown[] => + scanRefs(text).map((ref) => [ref.raw, ref.path, ref.fragment, ref.stamp]); + assert.deepEqual(parts("sync:/a.md#b@3f9a1c2e iref:/a.md@3f9a1c2e."), [ + ["sync:/a.md#b@3f9a1c2e", "/a.md", "b", "3f9a1c2e"], + ["iref:/a.md@3f9a1c2e", "/a.md", undefined, "3f9a1c2e"], + ]); + assert.deepEqual(parts("iref:/a.md#b iref:/lib/@scope/x.ts iref:/a@3F9A1C2E"), [ + ["iref:/a.md#b", "/a.md", "b", undefined], + ["iref:/lib/@scope/x.ts", "/lib/@scope/x.ts", undefined, undefined], + ["iref:/a@3F9A1C2E", "/a@3F9A1C2E", undefined, undefined], + ]); + // With nothing before `@`, there is no stamp, so the ref is wrong as it was before stamps. + assert.deepEqual(parts("iref:@3f9a1c2e iref:/a.md#@3f9a1c2e"), [ + ["iref:@3f9a1c2e", "@3f9a1c2e", undefined, undefined], + ["iref:/a.md#@3f9a1c2e", "/a.md", "@3f9a1c2e", undefined], + ]); + }); + it("splits path and fragment", () => { const [ref] = scanRefs("x iref:../api.md#auth y"); assert.equal(ref?.path, "../api.md"); diff --git a/packages/vscode/README.md b/packages/vscode/README.md index 76867e6..2800d25 100644 --- a/packages/vscode/README.md +++ b/packages/vscode/README.md @@ -4,7 +4,8 @@ This extension makes `iref:` links in comments clickable, and it shows broken li - Cmd/Ctrl+click a ref to open its target. A heading fragment opens the file at that heading. - Hover over a ref to see the start of its target. -- Broken refs show in Problems. Cmd/Ctrl+. offers fixes. +- Broken refs and stale stamps show in Problems. Cmd/Ctrl+. offers fixes. After you check a ref with a + stale stamp, run `interref stamp --to ` to write the new stamp. - "Copy ref" in the editor or explorer context menu copies `iref:/path#heading`. - In a comment, or in a YAML value that can be a ref, type `iref:/`, `iref:./` or `#` to get completions for paths and headings. `iref:`, `sync:` and the other protocols in the config file diff --git a/packages/vscode/src/extension.ts b/packages/vscode/src/extension.ts index 5f61e59..9ba37c4 100644 --- a/packages/vscode/src/extension.ts +++ b/packages/vscode/src/extension.ts @@ -37,15 +37,19 @@ export function activate(context: vscode.ExtensionContext): void { }), ); - // Headings live in file text, so edits to one file can fix or break refs in another. + // Headings and stamps live in file text, so edits to one file can fix or break refs in another. repos.onDidChange(() => diagnostics.scheduleAll(), undefined, context.subscriptions); context.subscriptions.push( vscode.workspace.onDidOpenTextDocument((document) => diagnostics.schedule(document, 0)), - vscode.workspace.onDidCloseTextDocument((document) => diagnostics.forget(document)), + vscode.workspace.onDidCloseTextDocument((document) => { + diagnostics.forget(document); + // Closed without saving: the cache may hold headings and stamps of the unsaved text. + repos.invalidate(document.uri); + }), vscode.workspace.onDidChangeTextDocument((event) => { if (event.contentChanges.length === 0) return; diagnostics.schedule(event.document); - if (isMarkdownPath(event.document.uri.fsPath)) repos.invalidate(event.document.uri); + repos.invalidate(event.document.uri); }), vscode.workspace.onDidChangeConfiguration((event) => { if (!event.affectsConfiguration("interref")) return; @@ -67,7 +71,7 @@ export function activate(context: vscode.ExtensionContext): void { watcher.onDidDelete(refreshSoon), watcher.onDidChange((uri) => { if (INDEX_FILES.has(basename(uri.fsPath))) refreshSoon(); - else if (isMarkdownPath(uri.fsPath)) repos.invalidate(uri); + else repos.invalidate(uri); }), { dispose: () => clearTimeout(refreshTimer) }, ); diff --git a/packages/vscode/src/repos.ts b/packages/vscode/src/repos.ts index b2cbe40..fba1ba8 100644 --- a/packages/vscode/src/repos.ts +++ b/packages/vscode/src/repos.ts @@ -82,14 +82,18 @@ export class Repos implements vscode.Disposable { this.changed.fire(); } - /** Forgets cached headings of a file that changed. */ + /** + * Forgets cached headings and stamps of a file that changed. Fires `onDidChange` only when there + * were some, since a file that no checked ref has read cannot change how refs resolve. + */ invalidate(uri: vscode.Uri): void { if (uri.scheme !== "file") return; + let forgot = false; for (const repo of this.loaded) { const path = repo.relative(uri.fsPath); - if (path !== undefined) repo.invalidate(path); + if (path !== undefined && repo.invalidate(path)) forgot = true; } - this.changed.fire(); + if (forgot) this.changed.fire(); } dispose(): void { diff --git a/skills/iref/SKILL.md b/skills/iref/SKILL.md index 1fd0f21..2f8d426 100644 --- a/skills/iref/SKILL.md +++ b/skills/iref/SKILL.md @@ -1,6 +1,6 @@ --- name: iref -description: Add, edit and check interref links (iref:, sync:) between files of a git repo. Use when you write a comment that points to another file, spec section or doc heading; when two files must stay in sync (for example a spec and its model); when you move, rename or delete a file or heading in a repo that has refs; when you review a change or a pull request for inconsistency between linked files; or when you run `iref check`, `iref links`, `iref backlinks` or `iref graph`. +description: Add, edit, stamp and check interref links (iref:, sync:) between files of a git repo. Use when you write a comment that points to another file, spec section or doc heading; when two files must stay in sync (for example a spec and its model); when you move, rename or delete a file or heading in a repo that has refs; when `iref check` reports a stale stamp; when you review a change or a pull request for inconsistency between linked files; or when you run `iref check`, `iref stamp`, `iref links`, `iref backlinks` or `iref graph`. --- # Use iref @@ -28,6 +28,7 @@ iref:../also/relative iref:/some/doc.md#heading-slug iref:#heading-in-this-file iref:/some/directory/ +sync:/some/doc.md#heading-slug@3f9a1c2e ``` - Use `iref:#heading` only in a Markdown file. Other files have no headings. @@ -53,6 +54,26 @@ headings. For example, `## Faults, overflow and reset` becomes are errors. Point to the most specific heading that the code depends on, not only to the page. +### Stamps + +A ref can end in a stamp: `@` and 8 hex digits of the SHA-256 of the target's +text, as in `sync:/docs/auth.md#token-lifetime@f24671a0`. The stamp says that +someone checked the ref against that text. When the text changes, `iref check` +fails on the ref (`stale-stamp`). + +- With a heading, the stamp covers the section: the heading and its + subsections. Without a heading, it covers the whole file. A directory, or a + file that is binary or cannot be read, has no stamp (`invalid-stamp`). +- Line ends, trailing spaces, blank lines, stamps, refs in comments and the + comments that hold only refs do not count. Adding a ref to a section does + not make other stamps stale. The other text of comments counts, docstrings + too. +- A ref without a stamp works as before. +- Never write or change a stamp by hand. Stamp only the refs that you + reviewed: after you checked the refs in a file to a target, run + `iref stamp --to #`. `--add sync` also stamps + the `sync:` refs that have none. + ## Put the ref in a comment A ref counts only in a comment, with one exception: in the YAML files that @@ -122,7 +143,8 @@ repo root. | Command | Use | |---|---| -| `iref check [...]` | Find broken refs. Exit 1 if there is one. Each error tells the rule and, if possible, a fix. | +| `iref check [...]` | Find broken refs. Exit 1 if there is one. Each error tells the rule and, if possible, a fix. Under a stale stamp, it lists every ref to the changed section, to a section in it or around it, and to its file. | +| `iref stamp ... --to #` | Write the current stamp into each stamped ref in the paths to that heading (`--to `: to the file or its headings; no `--to`: all). Add `--add sync` to also stamp the `sync:` refs that have none. Exit 1 if one of them is broken or a file is not written. | | `iref links ...` | Show the refs in the files and their targets. Exit 1 if one is broken. | | `iref links --to ` | Show only the refs that reach the second file. Add `-r` to see each chain. | | `iref backlinks ...` | Show the refs in the repo that point to the files or directories. Exit 1 if one is broken. Give a path without `#fragment`. | @@ -147,7 +169,9 @@ lines around each ref), `-T N` (show the first N lines of the target), of the file. 4. Run `iref check`. Fix all errors. A new target file gives a `target-ignored` warning until you `git add` it. -5. Run the project's tests and docs build. A changed docstring or an HTML +5. If the other refs of the same protocol in the repo have stamps, stamp the + new ones: `iref stamp --add sync --to #`. +6. Run the project's tests and docs build. A changed docstring or an HTML comment can change output that a check reads. ### Move or rename a file or a heading @@ -167,12 +191,41 @@ lines around each ref), `-T N` (show the first N lines of the target), If there is no fix, use the refs that you recorded in step 1 and the new path or heading. +5. A fix keeps the stamp of the ref. If the text of the target changed, for + example a renamed heading, the stamp is now stale: follow "Fix a stale + stamp". ### Change a file that has sync refs 1. Run `iref links ` and `iref backlinks `. 2. For each `sync:` link, read the other file and update it to agree with your change. +3. Run `iref check`. A stamp on a ref to the section that you changed is now + stale. Follow "Fix a stale stamp". + +### Fix a stale stamp + +1. Run `iref check`. Under the first stale stamp of a section, it lists every + ref in the repo to that section, also the refs without a stamp, and the + refs to a section in it or around it and to its whole file. +2. Find what changed in the section since the ref was stamped. Find the commit + that wrote the stamp, then compare the target with it: + + ```sh + git log -1 --format=%H -S'@' -- + git diff -- + ``` + +3. For each ref in the list, read the file that holds it and update the file + to agree with the section. If you are not sure that it agrees, tell the + user and do not stamp it. +4. Run `iref check`. Fix the errors other than the stale stamps that you + checked. +5. Run `iref stamp ... --to #` with the files that + you checked. Stamp only the refs that you reviewed: the stamp says that + its file agrees with the target. Without `--to`, `iref stamp` also stamps + the other stamped refs in the files. +6. Run `iref check` again. ### Check a set of changes for inconsistency @@ -196,9 +249,9 @@ changed | iref backlinks - # refs to the changed files: the target changed ``` 1. Run the two commands. Each one exits 1 if a ref that it lists is broken. - Fix the broken refs. `iref check` with no paths shows all problems, also the - ones that were there before the change. Do not fix those unless the user - asks. + Fix the broken refs. For a stale stamp, follow "Fix a stale stamp". + `iref check` with no paths shows all problems, also the ones that were + there before the change. Do not fix those unless the user asks. 2. Keep only the `sync:` links: add `| grep ' sync:'` to each command. A line that is in the output of both commands is a link where both sides changed: `{ changed | iref links -; changed | iref backlinks -; } | sort | uniq -d`. @@ -241,6 +294,8 @@ heading fragment, so you can filter by `#heading-slug`. | `escapes-root` | `..` goes above the repo root. | | `case-mismatch` | The path differs from a repo path only in case. | | `invalid-encoding` | The percent-encoding is bad. | +| `stale-stamp` | The target's text changed since the ref was stamped. | +| `invalid-stamp` | The stamp is on a directory, or on a file that is binary or cannot be read. | | `reserved-authority` | The ref uses `iref://`, which is kept for cross-repo refs. | | `target-ignored` (warning) | The target is untracked or ignored by git. | From a2893c8acf9786ed375433b85b6b3bc3fb2af9fa Mon Sep 17 00:00:00 2001 From: mondaychen Date: Fri, 4 Dec 2026 10:26:28 -0500 Subject: [PATCH 2/3] Make a stamp always cover the whole target file A heading in a stamped ref no longer limits the stamp to its section. This removes the section line ranges from stamps, check and stamp --to, which now takes only a file. Co-Authored-By: Claude Opus 5.5 --- README.md | 36 ++++++++-------- packages/cli/src/format.ts | 15 +------ packages/cli/src/main.ts | 73 +++++++++++-------------------- packages/cli/test/cli.test.ts | 74 ++++++++++++++++++++------------ packages/core/src/check.ts | 21 +++------ packages/core/src/index.ts | 3 +- packages/core/src/repo.ts | 36 +++++++--------- packages/core/src/stamp.ts | 34 ++++----------- packages/core/test/check.test.ts | 7 ++- packages/core/test/stamp.test.ts | 51 +++++++++------------- skills/iref/SKILL.md | 49 ++++++++++----------- 11 files changed, 173 insertions(+), 226 deletions(-) diff --git a/README.md b/README.md index 0645a79..eadc478 100644 --- a/README.md +++ b/README.md @@ -147,20 +147,21 @@ suggest the nearest correct slug. ### Stamps -A stamp ends a ref: `@` and the first 8 hex digits of the SHA-256 of the target's text. It records -the text that someone checked the ref against. When that text changes, `interref check` fails on the -ref (`stale-stamp`), so that someone reads the change and updates the file that holds the ref. +A stamp ends a ref: `@` and the first 8 hex digits of the SHA-256 of the target file's text. It +records the text that someone checked the ref against. When that text changes, `interref check` +fails on the ref (`stale-stamp`), so that someone reads the change and updates the file that holds +the ref. ```typescript // TTL must match the docs: sync:/docs/auth.md#token-lifetime@f24671a0 ``` -- With a heading fragment, the stamp covers the section: the heading and its subsections, up to the - next heading of the same or a higher level. Without one, it covers the whole file. A directory, or - a file that is binary or cannot be read, has no stamp (`invalid-stamp`). +- The stamp always covers the whole file. A heading fragment does not change this: a change + anywhere in the file makes the stamp stale. A directory, or a file that is binary or cannot be + read, has no stamp (`invalid-stamp`). - A byte order mark, line ends, trailing spaces and blank lines do not count. Neither do stamps, refs in comments, comments that hold only refs, and the spaces next to them. Thus adding a ref to - a section, or stamping one, does not make the stamps of other refs to it stale. + a file, or stamping one, does not make the stamps of other refs to it stale. - The other text of comments counts, doc comments and docstrings too: a changed docstring makes the stamps of the refs to its file stale, also when the docstring holds a ref. - A ref without a stamp works as before: a change to its target does not fail the check. @@ -177,23 +178,22 @@ src/auth/session.ts:1:29 sync:/docs/auth.md#token-lifetime stamped @f24671a0 2 refs stamped (3 refs in 3 files) ``` -After a change to the section, `interref check` shows each stale stamp. Under the first one of a -section, it lists every ref in the repo to that section, also those without a stamp, and the refs to -a section in it or around it and to its whole file: +After a change to the file, `interref check` shows each stale stamp. Under the first one of a file, +it lists every ref in the repo to that file or to one of its headings, also those without a stamp: ```console $ interref check -config/auth.yaml:3:9 error sync:/docs/auth.md#token-lifetime@f24671a0 docs/auth.md#token-lifetime changed since this ref was stamped [stale-stamp] - refs to docs/auth.md#token-lifetime: +config/auth.yaml:3:9 error sync:/docs/auth.md#token-lifetime@f24671a0 docs/auth.md changed since this ref was stamped [stale-stamp] + refs to docs/auth.md: config/auth.yaml:3:9 sync:/docs/auth.md#token-lifetime@f24671a0 src/auth/notes.py:1:7 iref:/docs/auth.md#token-lifetime src/auth/session.ts:1:29 sync:/docs/auth.md#token-lifetime@f24671a0 -src/auth/session.ts:1:29 error sync:/docs/auth.md#token-lifetime@f24671a0 docs/auth.md#token-lifetime changed since this ref was stamped [stale-stamp] +src/auth/session.ts:1:29 error sync:/docs/auth.md#token-lifetime@f24671a0 docs/auth.md changed since this ref was stamped [stale-stamp] 2 broken refs (3 refs in 5 files) ``` With `--format json`, each record has its `stamp`, and a stale one also has the list of `refs` to -the section. +the file. To see what changed, find the commit that wrote the stamp, then compare the target with it: @@ -203,11 +203,11 @@ git diff -- docs/auth.md ``` Update each file in the list to agree with the new text. Then stamp only the refs that you -checked: `--to` keeps the refs to one file, or to one heading with `#`. A heading that the file does -not have is an error. +checked: `--to` keeps the refs to one file and its headings. `--to` with a `#heading` is an error, +because the stamp covers the whole file. ```console -$ interref stamp src/auth/session.ts config/auth.yaml --to docs/auth.md#token-lifetime +$ interref stamp src/auth/session.ts config/auth.yaml --to docs/auth.md config/auth.yaml:3:9 sync:/docs/auth.md#token-lifetime@f24671a0 @f24671a0 -> @9c41e7b2 src/auth/session.ts:1:29 sync:/docs/auth.md#token-lifetime@f24671a0 @f24671a0 -> @9c41e7b2 2 refs stamped (2 refs in 2 files) @@ -230,7 +230,7 @@ src/auth/session.ts:3:5 error iref:/docs/auth.md#tokn no heading #tokn in doc | Command | Output | | ------------------------------------- | ------------------------------------------------------------------------ | | `interref check [...]` | Broken refs in the repo, or under the paths. Exit 1 if any. | -| `interref stamp ... [--to ]` | Write the current [stamp](#stamps) into the stamped refs in the paths, or only into those to `` (or `#`). `--add P` also stamps the `P:` refs that have none. | +| `interref stamp ... [--to ]` | Write the current [stamp](#stamps) into the stamped refs in the paths, or only into those to `` and its headings. `--add P` also stamps the `P:` refs that have none. | | `interref links ... [--to ]` | Refs that the files hold and where each one goes. | | `interref backlinks ...` | Refs in the repo that point at the files or directories. | | `interref graph []` | The link graph: `--format dot` (default), `mermaid`, `json` or `drawio`. | diff --git a/packages/cli/src/format.ts b/packages/cli/src/format.ts index 78ac631..db1a6a7 100644 --- a/packages/cli/src/format.ts +++ b/packages/cli/src/format.ts @@ -1,14 +1,6 @@ /** Text, JSON and SARIF renderings of ref records. */ -import { - displayPath, - LineIndex, - RULE_SEVERITY, - type RefRecord, - type Repo, - type ResolvedTarget, - type RuleId, -} from "@interref/core"; +import { displayPath, LineIndex, RULE_SEVERITY, type RefRecord, type Repo, type RuleId } from "@interref/core"; export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; @@ -22,11 +14,6 @@ export function problemLine(record: RefRecord): string { return `${location(record)} ${record.status} ${record.raw} ${record.message ?? ""} [${record.rule ?? ""}]${hint}`; } -/** What a stamp covers: a file, or the section of a heading such as `docs/spec.md#tokens`. */ -export function sectionOf(target: ResolvedTarget): string { - return target.fragment === undefined ? target.path : `${target.path}#${target.fragment.slug}`; -} - export function describeTarget(record: RefRecord): string { const target = record.target; if (target === undefined) return "?"; diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index 349ff22..699d83b 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -8,17 +8,13 @@ import { ConfigError, GitError, graphView, - parseFragment, RefGraph, Repo, scanRepo, - sectionLines, - similarSlugs, toDot, toDrawio, toMermaid, type RefRecord, - type ResolvedTarget, } from "@interref/core"; import { contextBlock, @@ -29,7 +25,6 @@ import { recordJson, refJson, sarif, - sectionOf, type ContextOptions, type JsonValue, } from "./format.js"; @@ -66,7 +61,7 @@ Options: -T N, --show-target N Show N lines of the target, from the heading or the top --format F text | json | ndjson, plus sarif for check; dot | mermaid | json | drawio for graph --add P stamp: also stamp the P: refs that have no stamp (repeat for more protocols) - --to # stamp: only the refs to that heading (--to : to the file or its headings) + --to stamp: only the refs to that file and its headings --editor CMD install-extension: the editor's command (default code; also cursor, windsurf, codium) --prerelease install-extension: also use prereleases --check install-extension: only tell if an update is available @@ -81,9 +76,10 @@ links and backlinks also exit 1 when a ref that they list is broken. Once a day, the CLI asks npm for a newer stable version. INTERREF_NO_UPDATE_CHECK=1 turns this off. A ref starts with a protocol name from the config file: iref: or sync: by default. Only heading fragments (#some-heading) are supported for now. iref is a short name for interref. -A ref can end in a stamp, @ and 8 hex digits of the SHA-256 of its target's text (iref:/a.md#b@3f9a1c2e). -check fails when the target changes; stamp writes the new stamp once you have checked the ref. -Stamp only the refs that you checked: --to keeps the refs to one file or heading. +A ref can end in a stamp, @ and 8 hex digits of the SHA-256 of its target file's text (iref:/a.md#b@3f9a1c2e). +The stamp covers the whole file, also when the ref has a heading. check fails when the file changes; +stamp writes the new stamp once you have checked the ref. Stamp only the refs that you checked: +--to keeps the refs to one file. The guide is an Agent Skill file. Read it for best practices, or save it as a skill, for example ${NAME} --guide > .claude/skills/iref/SKILL.md or ${NAME} --guide > .agents/skills/iref/SKILL.md @@ -294,42 +290,31 @@ function commandCheck(repo: Repo, values: Values, positionals: readonly string[] const scan = scanRepo(repo, under(roots)); const problems = scan.records.filter((record) => record.status !== "ok"); const errors = problems.filter((record) => record.status === "error").length; - // A section that changed since a stamp, and every ref in the repo to it, to a section in it or - // around it, or to its whole file: each one may need the change. - const changed = (record: RefRecord): ResolvedTarget | undefined => - record.rule === "stale-stamp" ? record.target : undefined; + // A file that changed since a stamp, and every ref in the repo to it or to one of its headings: + // each one may need the change. + const changed = (record: RefRecord): string | undefined => (record.rule === "stale-stamp" ? record.targetPath : undefined); const all = roots !== undefined && problems.some((record) => changed(record) !== undefined) ? scanRepo(repo).records : scan.records; - const lines = (target: ResolvedTarget): { first: number; last: number } | undefined => - sectionLines(repo.headings(target.path), target.fragment?.slug); - const refsTo = (section: ResolvedTarget): RefRecord[] => { - const outer = lines(section); - return all.filter((ref) => { - if (ref.target?.path !== section.path || ref.target.kind !== "file" || outer === undefined) return false; - // Sections are nested, so two that share a line are the same, or one is in the other. - const inner = lines(ref.target); - return inner !== undefined && inner.first < outer.last && outer.first < inner.last; - }); - }; + const refsTo = (path: string): RefRecord[] => all.filter((ref) => ref.target?.path === path && ref.target.kind === "file"); if (outputFormat === "sarif") console.log(JSON.stringify(sarif(problems), null, 2)); else if (outputFormat !== "text") { const json = problems.map((record) => { - const section = changed(record); - return section === undefined ? recordJson(record) : { ...recordJson(record), refs: refsTo(section).map(refJson) }; + const path = changed(record); + return path === undefined ? recordJson(record) : { ...recordJson(record), refs: refsTo(path).map(refJson) }; }); printJson(json, outputFormat); } else { const context = contextOptions(values); - // The refs to a changed section show once, under its first stale stamp. + // The refs to a changed file show once, under its first stale stamp. const listed = new Set(); for (const record of problems) { console.log(problemLine(record)); for (const extra of contextBlock(repo, record, context)) console.log(extra); - const section = changed(record); - if (section === undefined || listed.has(sectionOf(section))) continue; - listed.add(sectionOf(section)); - console.log(` refs to ${sectionOf(section)}:`); - for (const ref of refsTo(section)) console.log(` ${location(ref)} ${ref.raw}`); + const path = changed(record); + if (path === undefined || listed.has(path)) continue; + listed.add(path); + console.log(` refs to ${path}:`); + for (const ref of refsTo(path)) console.log(` ${location(ref)} ${ref.raw}`); } const warnings = problems.length - errors; const parts = [plural(errors, "broken ref")]; @@ -339,25 +324,19 @@ function commandCheck(repo: Repo, values: Values, positionals: readonly string[] return errors > 0 ? 1 : 0; } -/** The target of `stamp --to`: a file, and the slug of one of its headings after `#`. */ -function stampTarget(repo: Repo, argument: string): { path: string; slug?: string } { +/** The file of `stamp --to`. A heading is an error: a stamp covers the whole file. */ +function stampTarget(repo: Repo, argument: string): string { const hash = argument.indexOf("#"); - const path = repoPath(repo, hash < 0 ? argument : argument.slice(0, hash)); - if (hash < 0) return { path }; - const fragment = parseFragment(argument.slice(hash + 1)); - if (!fragment.ok) throw new UsageError(`--to ${argument}: ${fragment.problem.message}`); - const { slug } = fragment.value; - const slugs = repo.headings(path).map((heading) => heading.slug); - if (!slugs.includes(slug)) { - const near = similarSlugs(slug, slugs)[0]; - throw new UsageError(`--to ${argument}: no heading #${slug} in ${path}${near === undefined ? "" : `; did you mean #${near}?`}`); + const path = repo.relative(resolve(hash < 0 ? argument : argument.slice(0, hash))); + if (hash >= 0 && path !== undefined && repo.kind(path) === "file") { + throw new UsageError(`--to ${argument}: give the file without #heading, since a stamp covers the whole file`); } - return { path, slug }; + return repoPath(repo, argument); } /** * Writes the current stamp of the target into each stamped ref in the paths, and into the refs of - * the `--add` protocols that have none. `--to` keeps only the refs to one file or heading. A broken + * the `--add` protocols that have none. `--to` keeps only the refs to one file. A broken * ref is not stamped: it shows as in `check`. */ function commandStamp(repo: Repo, values: Values, positionals: readonly string[]): number { @@ -372,7 +351,7 @@ function commandStamp(repo: Repo, values: Values, positionals: readonly string[] const to = values.to === undefined ? undefined : stampTarget(repo, values.to); const wanted = (record: RefRecord): boolean => (record.stamp !== undefined || add.has(record.raw.slice(0, record.raw.indexOf(":")))) && - (to === undefined || (record.targetPath === to.path && (to.slug === undefined || record.target?.fragment?.slug === to.slug))); + (to === undefined || record.targetPath === to); const scan = scanRepo(repo, under(repoPaths(repo, positionals))); // The new stamps, by the file that holds the refs. const edits = new Map(); @@ -381,7 +360,7 @@ function commandStamp(repo: Repo, values: Values, positionals: readonly string[] if (!wanted(record)) continue; const target = record.target; const usable = record.status !== "error" || record.rule === "stale-stamp"; - const stamp = usable && target?.kind === "file" ? repo.stamp(target.path, target.fragment?.slug) : undefined; + const stamp = usable && target?.kind === "file" ? repo.stamp(target.path) : undefined; if (stamp === undefined) { // A ref to a directory has no stamp; only a ref that already has one is an error. if (record.status === "error") { diff --git a/packages/cli/test/cli.test.ts b/packages/cli/test/cli.test.ts index e1fc936..49bcbfb 100644 --- a/packages/cli/test/cli.test.ts +++ b/packages/cli/test/cli.test.ts @@ -152,9 +152,11 @@ describe("stamps", () => { return { code: result.status, stdout: result.stdout, stderr: result.stderr }; }; const read = (path: string): string => readFileSync(join(repo, path), "utf8"); - // The stamps of the sections "Tokens" and "Sessions": their lines without the blank ones. - const tokens = createHash("sha256").update("## Tokens\nA token lasts 15 minutes.").digest("hex").slice(0, 8); - const sessions = createHash("sha256").update("## Sessions\nA session ends after 8 hours.").digest("hex").slice(0, 8); + // The stamp of docs/spec.md: its lines without the blank ones. It covers the whole file, also in a ref to a heading. + const spec = createHash("sha256") + .update("# Spec\n## Tokens\nA token lasts 15 minutes.\n## Sessions\nA session ends after 8 hours.") + .digest("hex") + .slice(0, 8); before(() => { repo = realpathSync(mkdtempSync(join(tmpdir(), "refs-stamps-"))); @@ -176,16 +178,17 @@ describe("stamps", () => { after(() => rmSync(repo, { recursive: true, force: true })); - it("check fails on a stale stamp and lists every ref to the changed section, to a section around it and to its file", () => { + it("check fails on a stale stamp and lists every ref to the changed file and to its headings", () => { const { code, stdout } = run("check"); assert.equal(code, 1); assert.equal( stdout, [ - "src/model.py:1:3 error sync:/docs/spec.md#tokens@00000000 docs/spec.md#tokens changed since this ref was stamped [stale-stamp]", - " refs to docs/spec.md#tokens:", + "src/model.py:1:3 error sync:/docs/spec.md#tokens@00000000 docs/spec.md changed since this ref was stamped [stale-stamp]", + " refs to docs/spec.md:", " docs/index.md:1:6 iref:/docs/spec.md", " docs/index.md:2:6 iref:/docs/spec.md#spec", + " docs/index.md:3:6 iref:/docs/spec.md#sessions", " model/limits.yaml:2:9 sync:/docs/spec.md#tokens", " src/model.py:1:3 sync:/docs/spec.md#tokens@00000000", " src/notes.ts:1:4 iref:/docs/spec.md#tokens", @@ -195,7 +198,7 @@ describe("stamps", () => { ); }); - it("check --format json gives the stamp and the refs to the changed section", () => { + it("check --format json gives the stamp and the refs to the changed file", () => { const json = JSON.parse(run("check", "src", "--format", "json").stdout) as { stamp?: string; rule?: string; @@ -209,6 +212,7 @@ describe("stamps", () => { [ "docs/index.md:1:6 iref:/docs/spec.md", "docs/index.md:2:6 iref:/docs/spec.md#spec", + "docs/index.md:3:6 iref:/docs/spec.md#sessions", "model/limits.yaml:2:9 sync:/docs/spec.md#tokens", "src/model.py:1:3 sync:/docs/spec.md#tokens@00000000", "src/notes.ts:1:4 iref:/docs/spec.md#tokens", @@ -222,46 +226,60 @@ describe("stamps", () => { assert.equal( stdout, [ - `model/limits.yaml:2:9 sync:/docs/spec.md#tokens stamped @${tokens}`, - `src/model.py:1:3 sync:/docs/spec.md#tokens@00000000 @00000000 -> @${tokens}`, + `model/limits.yaml:2:9 sync:/docs/spec.md#tokens stamped @${spec}`, + `src/model.py:1:3 sync:/docs/spec.md#tokens@00000000 @00000000 -> @${spec}`, "2 refs stamped (3 refs in 3 files)", "", ].join("\n"), ); - assert.equal(read("src/model.py"), `# sync:/docs/spec.md#tokens@${tokens}\nTOKEN_MINUTES = 15\n`); - assert.equal(read("model/limits.yaml"), `tokens:\n spec: sync:/docs/spec.md#tokens@${tokens}\n`); + assert.equal(read("src/model.py"), `# sync:/docs/spec.md#tokens@${spec}\nTOKEN_MINUTES = 15\n`); + assert.equal(read("model/limits.yaml"), `tokens:\n spec: sync:/docs/spec.md#tokens@${spec}\n`); assert.equal(read("src/notes.ts"), "// iref:/docs/spec.md#tokens\n"); assert.equal(run("check").code, 0); assert.match(run("stamp", "src").stdout, /^0 refs stamped \(2 refs in 2 files\)$/mu); }); - it("stamp --to stamps only the refs to that heading, or to that file", () => { - writeFileSync(join(repo, "src/sessions.py"), "# sync:/docs/spec.md#sessions@00000000\n# sync:/docs/spec.md#tokens@00000000\n"); - const heading = run("stamp", "src", "--to", "docs/spec.md#sessions"); - assert.equal(heading.code, 0); + it("stamp --to stamps only the refs to that file, to any of its headings", () => { + writeFileSync( + join(repo, "src/sessions.py"), + "# sync:/docs/spec.md#sessions@00000000\n# sync:/docs/spec.md@00000000\n# sync:/src/notes.ts@00000000\n", + ); + const { code, stdout } = run("stamp", "src", "--to", "docs/spec.md"); + assert.equal(code, 0); assert.equal( - heading.stdout, - [`src/sessions.py:1:3 sync:/docs/spec.md#sessions@00000000 @00000000 -> @${sessions}`, "1 ref stamped (4 refs in 3 files)", ""].join("\n"), + stdout, + [ + `src/sessions.py:1:3 sync:/docs/spec.md#sessions@00000000 @00000000 -> @${spec}`, + `src/sessions.py:2:3 sync:/docs/spec.md@00000000 @00000000 -> @${spec}`, + "2 refs stamped (5 refs in 3 files)", + "", + ].join("\n"), + ); + assert.equal( + read("src/sessions.py"), + `# sync:/docs/spec.md#sessions@${spec}\n# sync:/docs/spec.md@${spec}\n# sync:/src/notes.ts@00000000\n`, ); - assert.equal(read("src/sessions.py"), `# sync:/docs/spec.md#sessions@${sessions}\n# sync:/docs/spec.md#tokens@00000000\n`); - assert.match(run("stamp", "src", "--to", "docs/spec.md").stdout, /^1 ref stamped /mu); - assert.equal(read("src/sessions.py"), `# sync:/docs/spec.md#sessions@${sessions}\n# sync:/docs/spec.md#tokens@${tokens}\n`); }); - it("stamp rejects an --add protocol that the config does not have, and a heading that the file does not have", () => { + it("stamp rejects an --add protocol that the config does not have, and --to with a heading", () => { const { code, stderr } = run("stamp", "src", "--add", "nope"); assert.equal(code, 2); assert.match(stderr, /^interref: --add nope: the protocols are iref, sync$/mu); - const heading = run("stamp", "src", "--to", "docs/spec.md#Tokens"); + const heading = run("stamp", "src", "--to", "docs/spec.md#tokens"); assert.equal(heading.code, 2); - assert.match(heading.stderr, /^interref: --to docs\/spec\.md#Tokens: no heading #Tokens in docs\/spec\.md; did you mean #tokens\?$/mu); + assert.match( + heading.stderr, + /^interref: --to docs\/spec\.md#tokens: give the file without #heading, since a stamp covers the whole file$/mu, + ); }); }); describe("stamp writes each file once, and only valid UTF-8", () => { let repo = ""; - const tokens = createHash("sha256").update("## Tokens\nA token lasts 15 minutes.").digest("hex").slice(0, 8); - const sessions = createHash("sha256").update("## Sessions\nA session ends after 8 hours.").digest("hex").slice(0, 8); + const spec = createHash("sha256") + .update("# Spec\n## Tokens\nA token lasts 15 minutes.\n## Sessions\nA session ends after 8 hours.") + .digest("hex") + .slice(0, 8); const latin1 = Buffer.from("# caf\u00e9 sync:/docs/spec.md#tokens\n", "latin1"); before(() => { @@ -288,8 +306,8 @@ describe("stamp writes each file once, and only valid UTF-8", () => { result.stdout, [ "src/latin1.py not stamped: it is not valid UTF-8, and stamp would change its bytes", - `src/model.py:1:3 sync:/docs/spec.md#tokens stamped @${tokens}`, - `src/model.py:2:23 sync:/docs/spec.md#sessions stamped @${sessions}`, + `src/model.py:1:3 sync:/docs/spec.md#tokens stamped @${spec}`, + `src/model.py:2:23 sync:/docs/spec.md#sessions stamped @${spec}`, "src/other.py not stamped: a symlink; stamp the file that it points to", "2 refs stamped, 2 files not stamped (6 refs in 4 files)", "", @@ -298,7 +316,7 @@ describe("stamp writes each file once, and only valid UTF-8", () => { assert.equal(readFileSync(join(repo, "lib/other.py"), "utf8"), "# sync:/docs/spec.md#tokens\n"); assert.equal( readFileSync(join(repo, "src/model.py"), "utf8"), - `# sync:/docs/spec.md#tokens@${tokens}\nTOKEN_MINUTES = 15 # sync:/docs/spec.md#sessions@${sessions}\n`, + `# sync:/docs/spec.md#tokens@${spec}\nTOKEN_MINUTES = 15 # sync:/docs/spec.md#sessions@${spec}\n`, ); assert.deepEqual(readFileSync(join(repo, "src/latin1.py")), latin1); }); diff --git a/packages/core/src/check.ts b/packages/core/src/check.ts index 918937f..c7791ba 100644 --- a/packages/core/src/check.ts +++ b/packages/core/src/check.ts @@ -85,13 +85,6 @@ export function similarPaths(repo: Repo, path: string): string[] { return closest(path, siblings, Math.max(2, Math.floor(posix.basename(path).length / 3))); } -/** Slugs that the author probably meant: a near spelling, or a longer slug that starts with `slug`. */ -export function similarSlugs(slug: string, slugs: readonly string[]): string[] { - const prefixed = slugs.filter((candidate) => slug !== "" && candidate.startsWith(slug)); - const spelled = closest(slug, slugs, Math.max(3, Math.floor(slug.length / 3))); - return [...new Set([...spelled, ...prefixed])].slice(0, MAX_SUGGESTIONS); -} - /** Checks one ref written in `source` (a repo-relative path), with the rule settings of the config. */ export function checkRef(repo: Repo, source: string, written: RefMatch, lines: LineIndex): RefRecord { const match = literalPath(repo, source, written); @@ -174,7 +167,10 @@ export function checkRef(repo: Repo, source: string, written: RefMatch, lines: L const headings = repo.headings(path); const heading = headings.find((candidate) => candidate.slug === slug); if (heading === undefined) { - const near = similarSlugs(slug, headings.map((candidate) => candidate.slug)); + const slugs = headings.map((candidate) => candidate.slug); + const prefixed = slugs.filter((candidate) => slug !== "" && candidate.startsWith(slug)); + const spelled = closest(slug, slugs, Math.max(3, Math.floor(slug.length / 3))); + const near = [...new Set([...spelled, ...prefixed])].slice(0, MAX_SUGGESTIONS); const hint = near[0] === undefined ? "" : `; did you mean #${near[0]}?`; return problem( "missing-anchor", @@ -186,17 +182,14 @@ export function checkRef(repo: Repo, source: string, written: RefMatch, lines: L target = { ...target, line: heading.line }; } + // A stamp covers the whole file, also in a ref to one of its headings. if (match.stamp !== undefined) { - const slug = target.fragment?.slug; - const stamp = kind === "file" ? repo.stamp(path, slug) : undefined; + const stamp = kind === "file" ? repo.stamp(path) : undefined; if (stamp === undefined) { const what = kind === "directory" ? "a directory" : "a file that is binary or cannot be read"; return problem("invalid-stamp", `${what} has no stamp`, [format(path, kind)], target); } - if (stamp !== match.stamp) { - const section = slug === undefined ? path : `${path}#${slug}`; - return problem("stale-stamp", `${section} changed since this ref was stamped`, [], target); - } + if (stamp !== match.stamp) return problem("stale-stamp", `${path} changed since this ref was stamped`, [], target); } if (warning !== undefined) return problem(warning.rule, warning.message, [], target); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index f420839..3c457be 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,6 +1,6 @@ export { commentSpans, findRefs, valueSpans } from "./comments.js"; export type { Span } from "./comments.js"; -export { checkRef, checkText, editDistance, scanRepo, similarPaths, similarSlugs } from "./check.js"; +export { checkRef, checkText, editDistance, scanRepo, similarPaths } from "./check.js"; export type { RefRecord, RepoScan, ResolvedTarget, Status } from "./check.js"; export { CONFIG_FILES, ConfigError, DEFAULT_CONFIG, excluder, globToRegExp, loadConfig, parseConfig } from "./config.js"; export type { Config, RuleSetting } from "./config.js"; @@ -14,6 +14,5 @@ export { findRepoRoot, GitError, readTextFromDisk, Repo } from "./repo.js"; export type { EntryKind, TextReader } from "./repo.js"; export { encodeRefPath, formatRef, parseFragment, resolveTarget, RULE_SEVERITY } from "./resolve.js"; export type { HeadingFragment, PathStyle, Problem, Result, RuleId, Severity, Target } from "./resolve.js"; -export { sectionLines } from "./stamp.js"; export { DEFAULT_PROTOCOLS, LineIndex, protocolPattern, scanRefs } from "./syntax.js"; export type { RefMatch } from "./syntax.js"; diff --git a/packages/core/src/repo.ts b/packages/core/src/repo.ts index 2c8d2c2..7cfd79e 100644 --- a/packages/core/src/repo.ts +++ b/packages/core/src/repo.ts @@ -65,8 +65,8 @@ export class Repo { private readonly byLowerCase = new Map(); private readonly children = new Map>(); private readonly headingCache = new Map(); - /** By path: the lines that stamps cover (undefined when the file is not text), and the stamps by slug. */ - private readonly stampCache = new Map }>(); + /** By path: the stamp of the file, undefined when the file is not text. */ + private readonly stampCache = new Map(); /** By the real path of a file, the cached paths that are symlinks to it, so that `invalidate` forgets them too. */ private readonly linksTo = new Map>(); private readonly excluded: (path: string) => boolean; @@ -245,27 +245,21 @@ export class Repo { } /** - * The stamp of a file, or of its section under the heading `slug`, cached until `invalidate`. - * Stamps, refs in comments and the comments that hold only refs do not count (see `stampLines`). - * Undefined for a file that is binary or cannot be read, or when no heading has the slug. + * The stamp of a file, cached until `invalidate`. Stamps, refs in comments and the comments that + * hold only refs do not count (see `stampLines`). Undefined for a file that is binary or cannot be + * read. */ - stamp(path: string, slug?: string): string | undefined { - let cached = this.stampCache.get(path); - if (cached === undefined) { - cached = { stamps: new Map() }; - const text = this.text(path); - if (text !== undefined) { - const read = (ref: RefMatch): RefMatch => literalPath(this, path, ref); - cached.lines = stampLines(path, text, this.config.protocols, this.readsYamlValues(path), read); - } - this.noteLink(path); - this.stampCache.set(path, cached); - } - const key = slug === undefined ? "" : `#${slug}`; - if (!cached.stamps.has(key)) { - cached.stamps.set(key, cached.lines === undefined ? undefined : stampOf(cached.lines, this.headings(path), slug)); + stamp(path: string): string | undefined { + if (this.stampCache.has(path)) return this.stampCache.get(path); + const text = this.text(path); + let stamp: string | undefined; + if (text !== undefined) { + const read = (ref: RefMatch): RefMatch => literalPath(this, path, ref); + stamp = stampOf(stampLines(path, text, this.config.protocols, this.readsYamlValues(path), read)); } - return cached.stamps.get(key); + this.noteLink(path); + this.stampCache.set(path, stamp); + return stamp; } /** diff --git a/packages/core/src/stamp.ts b/packages/core/src/stamp.ts index 095b98c..021d930 100644 --- a/packages/core/src/stamp.ts +++ b/packages/core/src/stamp.ts @@ -1,12 +1,12 @@ /** * Stamps. A ref can end in `@` and 8 hex digits, for example `#tokens@3f9a1c2e`: the start of the - * SHA-256 of its target's text when someone last checked the ref. When the target changes, the stamp - * no longer matches, and `check` reports the ref. + * SHA-256 of the text of its target file when someone last checked the ref. A heading fragment does + * not change what the stamp covers: it is always the whole file. When the file changes, the stamp no + * longer matches, and `check` reports the ref. */ import { createHash } from "node:crypto"; import { commentSpans, findRefs, type Span } from "./comments.js"; -import type { Heading } from "./markdown.js"; import type { Repo } from "./repo.js"; import { resolveTarget } from "./resolve.js"; import { DEFAULT_PROTOCOLS, scanRefs, type RefMatch } from "./syntax.js"; @@ -36,7 +36,8 @@ export function literalPath(repo: Repo, source: string, match: RefMatch): RefMat * reads `text"""`. The other text of comments counts, doc comments and docstrings too. With `values` * (a YAML file that the config names in `yaml-values`), a ref in a value counts, but its stamp does * not; `read` tells a stamp from the end of a path such as `/lib/v@1a2b3c4d` (see `literalPath`). A - * removed span keeps its line breaks, so each line keeps its number. A byte order mark, line ends + * removed span keeps its line breaks, so the text before it and after it stays on separate lines. A + * byte order mark, line ends * (also a lone `\r`) and trailing spaces do not count. */ export function stampLines( @@ -92,27 +93,10 @@ export function stampLines( } /** - * The lines of the section under the heading `slug`, from `first` up to `last` (not included, and - * 0-based): the heading and its subsections, up to the next heading of the same or a higher level. - * Without a slug, the whole file. Undefined when no heading has the slug. + * The stamp of a file from its `stampLines`. Blank lines do not count, so with `stampLines`, adding a + * ref to the text does not change its stamp. */ -export function sectionLines(headings: readonly Heading[], slug?: string): { first: number; last: number } | undefined { - if (slug === undefined) return { first: 0, last: Number.POSITIVE_INFINITY }; - const index = headings.findIndex((heading) => heading.slug === slug); - const heading = headings[index]; - if (heading === undefined) return undefined; - const next = headings.slice(index + 1).find((candidate) => candidate.level <= heading.level); - return { first: heading.line - 1, last: next === undefined ? Number.POSITIVE_INFINITY : next.line - 1 }; -} - -/** - * The stamp of a file from its `stampLines`, or of its section under the heading `slug` (see - * `sectionLines`). Blank lines do not count, so with `stampLines`, adding a ref to the text does not - * change its stamp. Undefined when no heading has the slug. - */ -export function stampOf(lines: readonly string[], headings: readonly Heading[] = [], slug?: string): string | undefined { - const section = sectionLines(headings, slug); - if (section === undefined) return undefined; - const kept = lines.slice(section.first, section.last).filter((line) => line !== ""); +export function stampOf(lines: readonly string[]): string { + const kept = lines.filter((line) => line !== ""); return createHash("sha256").update(kept.join("\n")).digest("hex").slice(0, 8); } diff --git a/packages/core/test/check.test.ts b/packages/core/test/check.test.ts index 8ef3b44..0657ac5 100644 --- a/packages/core/test/check.test.ts +++ b/packages/core/test/check.test.ts @@ -115,10 +115,13 @@ describe("checkText", () => { }); it("checks stamps, and keeps the stamp in a fix", () => { - const lifetime = createHash("sha256").update("## Token lifetime\nText.").digest("hex").slice(0, 8); - assert.equal(only("src/auth/session.ts", `iref:/docs/auth.md#token-lifetime@${lifetime}`).status, "ok"); + // A stamp covers the whole file, also in a ref to one of its headings. + const auth = createHash("sha256").update("# Auth\n## Token lifetime\nText.").digest("hex").slice(0, 8); + assert.equal(only("src/auth/session.ts", `iref:/docs/auth.md#token-lifetime@${auth}`).status, "ok"); + assert.equal(only("src/auth/session.ts", `iref:/docs/auth.md@${auth}`).status, "ok"); const stale = only("src/auth/session.ts", "iref:/docs/auth.md#token-lifetime@00000000"); assert.equal(stale.rule, "stale-stamp"); + assert.equal(stale.message, "docs/auth.md changed since this ref was stamped"); assert.equal(stale.stamp, "00000000"); // A fix keeps the stamp, so that the next check compares it with the new target. assert.deepEqual(only("docs/tokens.md", "iref:./auth.md#token-lifetimes@00000000").suggestions, [ diff --git a/packages/core/test/stamp.test.ts b/packages/core/test/stamp.test.ts index 4cb70fd..c1a0a13 100644 --- a/packages/core/test/stamp.test.ts +++ b/packages/core/test/stamp.test.ts @@ -3,7 +3,6 @@ import { createHash } from "node:crypto"; import { symlinkSync } from "node:fs"; import { join } from "node:path"; import { after, before, describe, it } from "node:test"; -import { extractHeadings } from "../src/markdown.js"; import { Repo } from "../src/repo.js"; import { stampLines, stampOf } from "../src/stamp.js"; import { DEFAULT_PROTOCOLS } from "../src/syntax.js"; @@ -12,49 +11,39 @@ import { makeRepo } from "./fixture.js"; const sha = (text: string): string => createHash("sha256").update(text).digest("hex").slice(0, 8); describe("stamps", () => { - const stamp = (text: string, slug?: string, path = "docs/spec.md"): string | undefined => - stampOf(stampLines(path, text), extractHeadings(text), slug); - const spec = "# Spec\n\n## Tokens\n\nA token lasts 15 minutes.\n\n### Renewal\n\nA renewal takes 2 seconds.\n\n## Sessions\n\nA session ends after 8 hours.\n"; + const stamp = (text: string, path = "docs/spec.md"): string => stampOf(stampLines(path, text)); + const spec = "# Spec\n\n## Tokens\n\nA token lasts 15 minutes.\n\n## Sessions\n\nA session ends after 8 hours.\n"; - it("hashes a section with its subsections, without line ends, trailing spaces, blank lines and comments with a ref", () => { - const expected = sha("## Tokens\nA token lasts 15 minutes.\n### Renewal\nA renewal takes 2 seconds."); - assert.equal(stamp(spec, "tokens"), expected); + it("hashes the whole file, without line ends, trailing spaces, blank lines and comments with a ref", () => { + const expected = sha("# Spec\n## Tokens\nA token lasts 15 minutes.\n## Sessions\nA session ends after 8 hours."); + assert.equal(stamp(spec), expected); const edited = spec .replace("A token lasts 15 minutes.", "A token lasts 15 minutes. \n\n") - .replace("A renewal takes", "A renewal takes") + .replace("A session ends", "A session ends") .replaceAll("\n", "\r\n"); - assert.equal(stamp(`\uFEFF${edited}`, "tokens"), expected); - assert.equal(stamp(spec.replaceAll("\n", "\r")), stamp(spec)); - const changed = spec.replace("2 seconds", "3 seconds"); - assert.notEqual(stamp(changed, "tokens"), expected); - assert.notEqual(stamp(changed), stamp(spec)); - assert.equal(stamp(changed, "sessions"), stamp(spec, "sessions")); - assert.equal(stamp(spec, "nothing"), undefined); + assert.equal(stamp(`\uFEFF${edited}`), expected); + assert.equal(stamp(spec.replaceAll("\n", "\r")), expected); + // A change in any section changes the stamp. + assert.notEqual(stamp(spec.replace("8 hours", "9 hours")), expected); + assert.notEqual(stamp(spec.replace("15 minutes", "30 minutes")), expected); }); it("counts the comments that hold no ref, doc comments and docstrings too", () => { - assert.notEqual(stamp(spec.replace("A token lasts 15 minutes.", "A token lasts 15 minutes. "), "tokens"), stamp(spec, "tokens")); + assert.notEqual(stamp(spec.replace("A token lasts 15 minutes.", "A token lasts 15 minutes. ")), stamp(spec)); const model = '"""A token lasts 15 minutes."""\nTOKEN_MINUTES = 15 # sync:/docs/spec.md#tokens@3f9a1c2e\n'; - assert.equal(stamp(model, undefined, "src/model.py"), sha('"""A token lasts 15 minutes."""\nTOKEN_MINUTES = 15')); - assert.notEqual(stamp(model.replace("15 minutes", "30 minutes"), undefined, "src/model.py"), stamp(model, undefined, "src/model.py")); + assert.equal(stamp(model, "src/model.py"), sha('"""A token lasts 15 minutes."""\nTOKEN_MINUTES = 15')); + assert.notEqual(stamp(model.replace("15 minutes", "30 minutes"), "src/model.py"), stamp(model, "src/model.py")); }); it("counts the other text of a comment that holds a ref, but not the ref and the spaces next to it", () => { - const model = (docstring: string): string | undefined => stamp(`${docstring}\nTOKEN_MINUTES = 15\n`, undefined, "src/model.py"); + const model = (docstring: string): string => stamp(`${docstring}\nTOKEN_MINUTES = 15\n`, "src/model.py"); const plain = model('"""Tokens last 15 minutes."""'); assert.equal(model('"""Tokens last 15 minutes. sync:/docs/spec.md#tokens@3f9a1c2e"""'), plain); assert.notEqual(model('"""Tokens last 30 minutes. sync:/docs/spec.md#tokens@3f9a1c2e"""'), plain); const note = spec.replace("A token lasts 15 minutes.", "A token lasts 15 minutes. "); - assert.equal(stamp(note.replace("configurable -->", "configurable sync:/src/x.py -->"), "tokens"), stamp(note, "tokens")); - assert.equal(stamp(note.replace("TTL is", "TTL iref:/src/x.py is"), "tokens"), stamp(note, "tokens")); - assert.notEqual(stamp(note.replace("configurable", "fixed"), "tokens"), stamp(note, "tokens")); - }); - - it("ends the section of a setext heading at the text of the next heading of its level", () => { - const setext = "Spec\n====\n\nTokens\n------\n\nA token lasts 15 minutes.\n\nSessions\n--------\n\nA session ends after 8 hours.\n"; - assert.equal(stamp(setext, "tokens"), sha("Tokens\n------\nA token lasts 15 minutes.")); - assert.equal(stamp(setext.replace("Sessions", "Logins"), "tokens"), sha("Tokens\n------\nA token lasts 15 minutes.")); - assert.equal(stamp(setext, "spec"), stamp(setext)); + assert.equal(stamp(note.replace("configurable -->", "configurable sync:/src/x.py -->")), stamp(note)); + assert.equal(stamp(note.replace("TTL is", "TTL iref:/src/x.py is")), stamp(note)); + assert.notEqual(stamp(note.replace("configurable", "fixed")), stamp(note)); }); it("leaves out the stamps of the refs in the values of a YAML file, but not the refs", () => { @@ -90,7 +79,7 @@ describe("Repo.stamp", () => { it("forgets the stamps and headings of a symlink when the file that it points to changes", async () => { const repo = await Repo.open(fixture.root); - assert.equal(repo.stamp("docs/current.md", "tokens"), repo.stamp("docs/spec.md", "tokens")); + assert.equal(repo.stamp("docs/current.md"), repo.stamp("docs/spec.md")); assert.equal(repo.invalidate("docs/spec.md"), true); assert.equal(repo.invalidate("docs/spec.md"), false); assert.equal(repo.headings("docs/current.md").length, 2); @@ -100,7 +89,7 @@ describe("Repo.stamp", () => { it("caches the stamps of a file, and invalidate tells whether it forgot any", async () => { const repo = await Repo.open(fixture.root); assert.equal(repo.invalidate("docs/spec.md"), false); - assert.equal(repo.stamp("docs/spec.md", "tokens"), sha("## Tokens\nA token lasts 15 minutes.")); + assert.equal(repo.stamp("docs/spec.md"), sha("# Spec\n## Tokens\nA token lasts 15 minutes.")); assert.equal(repo.invalidate("src/model.py"), false); assert.equal(repo.invalidate("docs/spec.md"), true); assert.equal(repo.invalidate("docs/spec.md"), false); diff --git a/skills/iref/SKILL.md b/skills/iref/SKILL.md index 2f8d426..23e5ee6 100644 --- a/skills/iref/SKILL.md +++ b/skills/iref/SKILL.md @@ -56,23 +56,22 @@ only to the page. ### Stamps -A ref can end in a stamp: `@` and 8 hex digits of the SHA-256 of the target's -text, as in `sync:/docs/auth.md#token-lifetime@f24671a0`. The stamp says that -someone checked the ref against that text. When the text changes, `iref check` -fails on the ref (`stale-stamp`). - -- With a heading, the stamp covers the section: the heading and its - subsections. Without a heading, it covers the whole file. A directory, or a - file that is binary or cannot be read, has no stamp (`invalid-stamp`). +A ref can end in a stamp: `@` and 8 hex digits of the SHA-256 of the target +file's text, as in `sync:/docs/auth.md#token-lifetime@f24671a0`. The stamp says +that someone checked the ref against that text. When the text changes, +`iref check` fails on the ref (`stale-stamp`). + +- The stamp always covers the whole file, also when the ref has a heading. A + change anywhere in the file makes the stamp stale. A directory, or a file + that is binary or cannot be read, has no stamp (`invalid-stamp`). - Line ends, trailing spaces, blank lines, stamps, refs in comments and the - comments that hold only refs do not count. Adding a ref to a section does - not make other stamps stale. The other text of comments counts, docstrings - too. + comments that hold only refs do not count. Adding a ref to a file does not + make other stamps stale. The other text of comments counts, docstrings too. - A ref without a stamp works as before. - Never write or change a stamp by hand. Stamp only the refs that you reviewed: after you checked the refs in a file to a target, run - `iref stamp --to #`. `--add sync` also stamps - the `sync:` refs that have none. + `iref stamp --to `. `--add sync` also stamps the `sync:` + refs that have none. ## Put the ref in a comment @@ -143,8 +142,8 @@ repo root. | Command | Use | |---|---| -| `iref check [...]` | Find broken refs. Exit 1 if there is one. Each error tells the rule and, if possible, a fix. Under a stale stamp, it lists every ref to the changed section, to a section in it or around it, and to its file. | -| `iref stamp ... --to #` | Write the current stamp into each stamped ref in the paths to that heading (`--to `: to the file or its headings; no `--to`: all). Add `--add sync` to also stamp the `sync:` refs that have none. Exit 1 if one of them is broken or a file is not written. | +| `iref check [...]` | Find broken refs. Exit 1 if there is one. Each error tells the rule and, if possible, a fix. Under a stale stamp, it lists every ref to the changed file and to its headings. | +| `iref stamp ... --to ` | Write the current stamp into each stamped ref in the paths to that file and its headings (no `--to`: all). Add `--add sync` to also stamp the `sync:` refs that have none. Exit 1 if one of them is broken or a file is not written. | | `iref links ...` | Show the refs in the files and their targets. Exit 1 if one is broken. | | `iref links --to ` | Show only the refs that reach the second file. Add `-r` to see each chain. | | `iref backlinks ...` | Show the refs in the repo that point to the files or directories. Exit 1 if one is broken. Give a path without `#fragment`. | @@ -170,7 +169,7 @@ lines around each ref), `-T N` (show the first N lines of the target), 4. Run `iref check`. Fix all errors. A new target file gives a `target-ignored` warning until you `git add` it. 5. If the other refs of the same protocol in the repo have stamps, stamp the - new ones: `iref stamp --add sync --to #`. + new ones: `iref stamp --add sync --to `. 6. Run the project's tests and docs build. A changed docstring or an HTML comment can change output that a check reads. @@ -200,15 +199,15 @@ lines around each ref), `-T N` (show the first N lines of the target), 1. Run `iref links ` and `iref backlinks `. 2. For each `sync:` link, read the other file and update it to agree with your change. -3. Run `iref check`. A stamp on a ref to the section that you changed is now +3. Run `iref check`. A stamp on a ref to the file that you changed is now stale. Follow "Fix a stale stamp". ### Fix a stale stamp -1. Run `iref check`. Under the first stale stamp of a section, it lists every - ref in the repo to that section, also the refs without a stamp, and the - refs to a section in it or around it and to its whole file. -2. Find what changed in the section since the ref was stamped. Find the commit +1. Run `iref check`. Under the first stale stamp of a file, it lists every ref + in the repo to that file or to one of its headings, also the refs without a + stamp. +2. Find what changed in the file since the ref was stamped. Find the commit that wrote the stamp, then compare the target with it: ```sh @@ -217,11 +216,13 @@ lines around each ref), `-T N` (show the first N lines of the target), ``` 3. For each ref in the list, read the file that holds it and update the file - to agree with the section. If you are not sure that it agrees, tell the - user and do not stamp it. + to agree with the target. A change in one section of the target can be + unrelated to a ref to another heading: then the file needs no update, but + still stamp the ref. If you are not sure that it agrees, tell the user and + do not stamp it. 4. Run `iref check`. Fix the errors other than the stale stamps that you checked. -5. Run `iref stamp ... --to #` with the files that +5. Run `iref stamp ... --to ` with the files that you checked. Stamp only the refs that you reviewed: the stamp says that its file agrees with the target. Without `--to`, `iref stamp` also stamps the other stamped refs in the files. From 51a4bd33984cbd605f7412f8cca631cac6a20cda Mon Sep 17 00:00:00 2001 From: mondaychen Date: Fri, 4 Dec 2026 11:03:20 -0500 Subject: [PATCH 3/3] Keep stamps when a ref is added in more comment forms, and stamp a hard-linked file once - A line in the middle of a comment that has no letters or digits besides its refs, such as ` *` in a doc comment, does not count. Thus adding the line ` * ref`, or writing a ref on a line ` *`, does not change the stamp. - A comment that holds only refs and markers that have letters does not count: `REM` in Batch and VB, `=begin`/`=end` in Ruby, `=pod`, `=begin comment` and `=for comment` in Perl, `{% comment %}` in Jinja, `#+begin_comment` in Org, `\begin{comment}` in LaTeX, and the prefix of a Python docstring such as `r"""`. - stampLines removes a byte order mark before it finds the comments, so a BOM does not hide a docstring on the first line. - stamp finds a file that two paths reach by its device and inode, so a file that two hard links reach is written once. Before, the second write put a second stamp on the ref. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/main.ts | 12 +++-- packages/cli/test/cli.test.ts | 35 ++++++++++++- packages/core/src/stamp.ts | 85 +++++++++++++++++++++++--------- packages/core/test/stamp.test.ts | 44 +++++++++++++++++ 4 files changed, 148 insertions(+), 28 deletions(-) diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index 699d83b..d326e0e 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -1,7 +1,7 @@ #!/usr/bin/env node /** interref: outgoing refs, backlinks, broken refs and the link graph of a git repo. */ -import { lstatSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; +import { lstatSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs"; import { basename, resolve } from "node:path"; import { parseArgs } from "node:util"; import { @@ -375,9 +375,10 @@ function commandStamp(repo: Repo, values: Values, positionals: readonly string[] edits.set(record.source.path, list); } - // The files written so far, by their real path. A symlink is not written through: the file that it - // points to is written when it is in the paths too. A file that two paths reach is written once: - // a second write would put its stamps at the offsets of the text before the first. + // The files written so far, by their device and inode (a hard link has its own real path), or by + // their real path where the file system gives no inode. A symlink is not written through: the file + // that it points to is written when it is in the paths too. A file that two paths reach is written + // once: a second write would put its stamps at the offsets of the text before the first. const written = new Map(); let stamped = 0; let refused = 0; @@ -391,7 +392,8 @@ function commandStamp(repo: Repo, values: Values, positionals: readonly string[] } continue; } - const real = realpathSync.native(file); + const { dev, ino } = statSync(file, { bigint: true }); + const real = ino === 0n ? realpathSync.native(file) : `${dev}:${ino}`; const same = written.get(real); if (same !== undefined) { console.log(`${path} not stamped: the same file as ${same}`); diff --git a/packages/cli/test/cli.test.ts b/packages/cli/test/cli.test.ts index 49bcbfb..187a371 100644 --- a/packages/cli/test/cli.test.ts +++ b/packages/cli/test/cli.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { execFileSync, spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; -import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { linkSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { after, before, describe, it } from "node:test"; @@ -322,6 +322,39 @@ describe("stamp writes each file once, and only valid UTF-8", () => { }); }); +describe("stamp writes a file that two hard links reach once", () => { + let repo = ""; + const spec = createHash("sha256").update("# Spec").digest("hex").slice(0, 8); + + before(() => { + repo = realpathSync(mkdtempSync(join(tmpdir(), "refs-stamp-links-"))); + mkdirSync(join(repo, "docs")); + mkdirSync(join(repo, "src")); + writeFileSync(join(repo, "docs/spec.md"), "# Spec\n"); + writeFileSync(join(repo, "src/a.py"), "# sync:/docs/spec.md\n"); + linkSync(join(repo, "src/a.py"), join(repo, "src/b.py")); + execFileSync("git", ["init", "-q"], { cwd: repo }); + execFileSync("git", ["add", "-A"], { cwd: repo }); + }); + + after(() => rmSync(repo, { recursive: true, force: true })); + + it("stamps the refs of the first path, and skips the second", () => { + const result = spawnSync(process.execPath, [CLI, "stamp", "src", "--add", "sync"], { cwd: repo, encoding: "utf8" }); + assert.equal(result.status, 0); + assert.equal( + result.stdout, + [ + `src/a.py:1:3 sync:/docs/spec.md stamped @${spec}`, + "src/b.py not stamped: the same file as src/a.py", + "1 ref stamped (2 refs in 2 files)", + "", + ].join("\n"), + ); + assert.equal(readFileSync(join(repo, "src/b.py"), "utf8"), `# sync:/docs/spec.md@${spec}\n`); + }); +}); + describe("usage errors", () => { it("exit 2", () => { assert.equal(refs().code, 2); diff --git a/packages/core/src/stamp.ts b/packages/core/src/stamp.ts index 021d930..b04955e 100644 --- a/packages/core/src/stamp.ts +++ b/packages/core/src/stamp.ts @@ -14,9 +14,25 @@ import { DEFAULT_PROTOCOLS, scanRefs, type RefMatch } from "./syntax.js"; /** The spaces after a removed comment or ref. */ const SPACES = /[ \t]*/uy; -/** A letter or a digit. A comment that has none besides its refs holds only refs. */ +/** A letter or a digit. A comment that has none besides its refs and its markers holds only refs. */ const WORD = /[\p{L}\p{N}]/u; +/** + * The comment markers that have letters, at the start of a comment: `REM` in Batch and VB, `=begin` + * in Ruby, `=pod` and `=begin comment` or `=for comment` in Perl, `\begin{comment}` in LaTeX, + * `{% comment %}` in Jinja, `#+begin_comment` in Org, and the prefix of a Python docstring such as + * `r"""`. They are not words of the comment. + */ +const OPEN_MARKER = + /^[ \t@]*(?:rem(?=[ \t]|$)|=(?:begin|for)[ \t]+comment\b|=[a-z]\w*|\\begin\{comment\}|\{%-?[ \t]*comment[ \t]*-?%\}|#\+begin_comment|[rubft]{1,2}(?=["']))/iu; + +/** + * The comment markers that have letters, at the end of a comment, as `OPEN_MARKER`. In Perl, the + * `=end comment` before `=cut` is one too. + */ +const CLOSE_MARKER = + /(?:(? b` reads `a b` and `text ref"""` - * reads `text"""`. The other text of comments counts, doc comments and docstrings too. With `values` + * The lines of a file that its stamps cover. A comment that holds only refs (and its markers, also + * markers such as `REM`) does not count. In another comment, its refs do not count. Neither do the + * spaces after a removed comment or ref, or the spaces before it when none follow, so that + * `a b` reads `a b` and `text ref"""` reads `text"""`. A line in the middle of a comment + * that has no letters or digits besides its refs does not count either, with a ref or without one, + * such as ` *` in a doc comment: so adding the line ` * ref`, or writing the ref on a line ` *`, does + * not change the stamp. The other text of comments counts, doc comments and docstrings too. With `values` * (a YAML file that the config names in `yaml-values`), a ref in a value counts, but its stamp does * not; `read` tells a stamp from the end of a path such as `/lib/v@1a2b3c4d` (see `literalPath`). A * removed span keeps its line breaks, so the text before it and after it stays on separate lines. A - * byte order mark, line ends - * (also a lone `\r`) and trailing spaces do not count. + * byte order mark, line ends (also a lone `\r`) and trailing spaces do not count. The byte order mark + * is removed before the comments are found, so that it does not hide a docstring on the first line. */ export function stampLines( path: string, - text: string, + source: string, protocols: readonly string[] = DEFAULT_PROTOCOLS, values = false, read: (ref: RefMatch) => RefMatch = (ref) => ref, ): string[] { + const text = source.replace(/^\uFEFF/u, ""); const removed: Span[] = []; // Removes a span and the spaces after it, or the spaces before it when none follow. const remove = (start: number, end: number): void => { @@ -59,10 +79,16 @@ export function stampLines( for (const comment of commentSpans(path, text) ?? []) { const body = text.slice(comment.start, comment.end); const refs = scanRefs(body, protocols); - if (refs.length === 0) continue; - const rest = refs.reduceRight((kept, ref) => kept.slice(0, ref.start) + kept.slice(ref.end), body); - if (!WORD.test(rest)) remove(comment.start, comment.end); - else for (const ref of refs) remove(comment.start + ref.start, comment.start + ref.end); + const rest = withoutRefs(body, refs, 0); + if (refs.length > 0 && !WORD.test(rest.replace(OPEN_MARKER, "").replace(CLOSE_MARKER, ""))) { + remove(comment.start, comment.end); + continue; + } + for (const line of middleLines(text, comment)) { + const onLine = refs.filter((ref) => comment.start + ref.start >= line.start && comment.start + ref.end <= line.end); + if (!WORD.test(withoutRefs(text.slice(line.start, line.end), onLine, line.start - comment.start))) removed.push(line); + } + for (const ref of refs) remove(comment.start + ref.start, comment.start + ref.end); } if (values) { for (const ref of findRefs(path, text, protocols, true)) { @@ -80,16 +106,31 @@ export function stampLines( } kept += text.slice(at); // Each line of the file, with the lines that a lone `\r` makes joined by `\n` and blank ones dropped. - return kept - .replace(/^/u, "") - .split("\n") - .map((line) => - line - .split("\r") - .map((part) => part.trimEnd()) - .filter((part) => part !== "") - .join("\n"), - ); + return kept.split("\n").map((line) => + line + .split("\r") + .map((part) => part.trimEnd()) + .filter((part) => part !== "") + .join("\n"), + ); +} + +/** The lines of a comment after its first line break and before its last one. */ +function middleLines(text: string, comment: Span): Span[] { + const lines: Span[] = []; + const breaks = /\r\n?|\n/gu; + breaks.lastIndex = comment.start; + let start: number | undefined; + for (let found = breaks.exec(text); found !== null && found.index < comment.end; found = breaks.exec(text)) { + if (start !== undefined) lines.push({ start, end: found.index }); + start = found.index + found[0].length; + } + return lines; +} + +/** `text` without `refs`, whose offsets are from `offset` before the start of `text`. */ +function withoutRefs(text: string, refs: readonly RefMatch[], offset: number): string { + return refs.reduceRight((kept, ref) => kept.slice(0, ref.start - offset) + kept.slice(ref.end - offset), text); } /** diff --git a/packages/core/test/stamp.test.ts b/packages/core/test/stamp.test.ts index c1a0a13..8c278b0 100644 --- a/packages/core/test/stamp.test.ts +++ b/packages/core/test/stamp.test.ts @@ -46,6 +46,50 @@ describe("stamps", () => { assert.notEqual(stamp(note.replace("configurable", "fixed")), stamp(note)); }); + it("does not count a line of a doc comment that holds only a ref and the comment's leader", () => { + const code = (comment: string): string => stamp(`${comment}\nexport const TTL = 15;\n`, "src/model.ts"); + const plain = code("/**\n * Token lifetime.\n */"); + assert.equal(code("/**\n * Token lifetime.\n * sync:/docs/spec.md@3f9a1c2e\n */"), plain); + assert.equal(code("/**\n * Token lifetime.\n * - sync:/docs/spec.md iref:/docs/a.md\n */"), plain); + assert.equal(stamp("/* Token lifetime.\n * iref:/a.md\n */\nx;\n", "src/a.c"), stamp("/* Token lifetime.\n */\nx;\n", "src/a.c")); + // A ref on a line that holds only the leader, and a line with the leader alone, do not count. + const separated = "/**\n * Token lifetime.\n *\n * Details.\n */"; + assert.equal(code(separated.replace(" *\n", " * sync:/docs/spec.md\n")), code(separated)); + assert.equal(code(separated), code("/**\n * Token lifetime.\n * Details.\n */")); + assert.equal(code(separated.replaceAll("\n", "\r")), code(separated)); + // The words on the line of a ref still count. + assert.notEqual(code("/**\n * Token lifetime.\n * See sync:/docs/spec.md\n */"), plain); + }); + + it("does not count a comment that holds only refs and markers that have letters", () => { + const same = (path: string, code: string, comment: string): void => { + assert.equal(stamp(`${code}${comment}\n`, path), stamp(code, path), `${path}: ${comment}`); + }; + same("run.bat", "@echo off\nset TTL=15\n", "REM iref:/a.py"); + same("run.bat", "@echo off\nset TTL=15\n", "@rem iref:/a.py"); + same("model.vb", "Dim ttl = 15\n", "Rem iref:/a.py"); + same("model.rb", "TTL = 15\n", "=begin\niref:/a.py\n=end"); + same("model.pl", "my $ttl = 15;\n", "=pod\n\niref:/a.py\n\n=cut"); + same("model.pl", "my $ttl = 15;\n", "=begin comment\n\niref:/a.py\n\n=end comment\n\n=cut"); + same("model.pl", "my $ttl = 15;\n", "=for comment iref:/a.py\n\n=cut"); + same("model.py", "TTL = 15\n", 'r"""iref:/a.py"""'); + // A marker word that is not at the start or the end of the comment still counts. + assert.notEqual(stamp("x = 1\n# rem iref:/a.py\n", "model.py"), stamp("x = 1\n", "model.py")); + assert.notEqual(stamp("TTL = 15\n=head1 NAME\niref:/a.py\n=cut\n", "model.pl"), stamp("TTL = 15\n", "model.pl")); + }); + + it("finds the comments after it removes a byte order mark", () => { + const model = '"""sync:/docs/spec.md"""\nx = 1\n'; + assert.equal(stamp(`\uFEFF${model}`, "src/model.py"), stamp(model, "src/model.py")); + assert.equal(stamp(model, "src/model.py"), sha("x = 1")); + }); + + it("finds the same comments as check when a string holds a lone line end", () => { + // check finds this ref, so stamp writes a stamp into it: the stamp of the file must not change. + const code = 'char *s = "a\r"; // sync:/docs/spec.md\nint y;\n'; + assert.equal(stamp(code.replace("spec.md", "spec.md@3f9a1c2e"), "src/a.c"), stamp(code, "src/a.c")); + }); + it("leaves out the stamps of the refs in the values of a YAML file, but not the refs", () => { const yaml = (ref: string): string[] => stampLines("model/limits.yaml", `tokens:\n spec: ${ref}\n`, DEFAULT_PROTOCOLS, true); assert.deepEqual(yaml("sync:/docs/spec.md#tokens@3f9a1c2e"), yaml("sync:/docs/spec.md#tokens"));