repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/the-system/documents.ts
RawFile outline
- SCHEMA_VERSION line 9
- SystemDocumentError line 11
- code line 12
- constructor line 14
- nearestMarker line 21
- discoverProjectRoot line 35
- resolveGovernedPath line 50
- DOCUMENT_TYPES line 66
- DocumentType line 73
- SystemConfig line 74
- InspectedSystemConfig line 79
- ParsedDocumentId line 83
- ResearchMetadata line 89
- SpecMetadata line 94
- PhaseMetadata line 100
- PlanMetadata line 108
- IssueMetadata line 117
- DocumentMetadata line 124
- Diagnostic line 130
- AuthoredDocument line 135
- BundleDocumentSource line 139
- BundleDocumentRecord line 140
- BundleDocumentIndex line 145
- BundleDiscovery line 149
- PREFIX line 154
- SLUG line 155
- ID_CHARS line 156
- TYPE_BY_TOKEN line 157
- DIRECTORY_BY_TYPE line 160
- directoryForType line 168
- objectValue line 172
- exactKeys line 183
- positiveInteger line 197
- duplicateTopLevelKeys line 199
- parseSystemConfig line 239
- inspectSystemConfig line 283
- parseDocumentId line 313
- validateDocumentPath line 338
- requiredStringField line 361
- optionalUniqueStrings line 370
- requiredUniqueStrings line 388
- statusField line 400
- projectMetadata line 410
- reference line 423
- dependencies line 433
- parseAuthoredDocument line 512
- diagnostic line 523
- compareDiagnostics line 528
- scanBundleAssets line 532
- discoverDocumentBundles line 558
- references line 648
- dependencyReferences line 672
- diagnosticIdentity line 676
- indexBundleDocuments line 679
- visit line 807
- validateBundleCandidate line 838
import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs";
import path from "node:path";
import {
type FrontmatterMap,
type MarkdownDocumentError,
parseRichMarkdown,
} from "./markdown.ts";
export const SCHEMA_VERSION = 3;
export class SystemDocumentError extends Error {
readonly code: string;
constructor(code: string, message: string) {
super(message);
this.code = code;
this.name = "SystemDocumentError";
}
}
const nearestMarker = (
cwd: string,
marker: string,
markerExists: (candidate: string) => boolean,
) => {
let current = path.resolve(cwd);
while (true) {
if (markerExists(path.join(current, marker))) return current;
const parent = path.dirname(current);
if (parent === current) return undefined;
current = parent;
}
};
export function discoverProjectRoot(
cwd: string,
markerExists = existsSync,
): string {
const resolvedCwd = path.resolve(cwd);
const jj = nearestMarker(resolvedCwd, ".jj", markerExists);
const git = nearestMarker(resolvedCwd, ".git", markerExists);
if (jj && git && jj !== git)
throw new SystemDocumentError(
"root.conflict",
`Conflicting project roots: Git ${git}; JJ ${jj}`,
);
return jj ?? git ?? resolvedCwd;
}
export function resolveGovernedPath(root: string, candidate: string): string {
const normalizedRoot = path.resolve(root);
const target = path.resolve(normalizedRoot, candidate);
const relative = path.relative(normalizedRoot, target);
if (
relative === ".." ||
relative.startsWith(`..${path.sep}`) ||
path.isAbsolute(relative)
)
throw new SystemDocumentError(
"path.outside-root",
`Path is outside project root: ${candidate}`,
);
return target;
}
export const DOCUMENT_TYPES = [
"spec",
"phase",
"plan",
"issue",
"research",
] as const;
export type DocumentType = (typeof DOCUMENT_TYPES)[number];
export type SystemConfig = Readonly<{
prefix: string;
schemaVersion: number;
title?: string;
}>;
export type InspectedSystemConfig = Readonly<{
config: SystemConfig;
legacyStyleVersion?: number;
}>;
export type ParsedDocumentId = Readonly<{
id: string;
prefix: string;
type: DocumentType;
token: string;
}>;
export type ResearchMetadata = Readonly<{
id: string;
type: "research";
title: string;
}>;
export type SpecMetadata = Readonly<{
id: string;
type: "spec";
title: string;
research?: readonly string[];
}>;
export type PhaseMetadata = Readonly<{
id: string;
type: "phase";
title: string;
spec: string;
status: "draft" | "done";
depends_on?: readonly string[];
}>;
export type PlanMetadata = Readonly<{
id: string;
type: "plan";
title: string;
spec: string;
phase?: string;
status: "draft" | "done";
depends_on?: readonly string[];
}>;
export type IssueMetadata = Readonly<{
id: string;
type: "issue";
title: string;
status: "open" | "done";
specs: readonly string[];
}>;
export type DocumentMetadata =
| ResearchMetadata
| SpecMetadata
| PhaseMetadata
| PlanMetadata
| IssueMetadata;
export type Diagnostic = Readonly<{
code: string;
path: string;
message: string;
}>;
export type AuthoredDocument = Readonly<{
metadata: DocumentMetadata;
frontmatter: FrontmatterMap;
}>;
export type BundleDocumentSource = Readonly<{ path: string; markdown: string }>;
export type BundleDocumentRecord = Readonly<{
path: string;
metadata: DocumentMetadata;
frontmatter: FrontmatterMap;
}>;
export type BundleDocumentIndex = Readonly<{
documents: readonly BundleDocumentRecord[];
diagnostics: readonly Diagnostic[];
}>;
export type BundleDiscovery = Readonly<{
sources: readonly BundleDocumentSource[];
diagnostics: readonly Diagnostic[];
}>;
const PREFIX = /^[A-Z][A-Z0-9]{1,7}$/;
const SLUG = "[a-z0-9]+(?:-[a-z0-9]+)*";
const ID_CHARS = "[A-Z0-9_-]{8}";
const TYPE_BY_TOKEN = new Map(
DOCUMENT_TYPES.map((type) => [type.toUpperCase(), type]),
);
const DIRECTORY_BY_TYPE: Readonly<Record<DocumentType, string>> = {
spec: "specs",
phase: "phases",
plan: "plans",
issue: "issues",
research: "research",
};
export function directoryForType(type: DocumentType): string {
return DIRECTORY_BY_TYPE[type];
}
const objectValue = (
value: unknown,
label: string,
): Record<string, unknown> => {
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new SystemDocumentError(
"json.shape",
`${label} must be a JSON object`,
);
return value as Record<string, unknown>;
};
const exactKeys = (
value: Record<string, unknown>,
required: readonly string[],
) => {
const actual = Object.keys(value).sort();
if (
required.some((key) => !(key in value)) ||
actual.some((key) => !required.includes(key))
)
throw new SystemDocumentError(
"json.keys",
`Expected keys ${[...required].sort().join(", ")}; received ${actual.join(", ")}`,
);
};
const positiveInteger = (value: unknown) =>
typeof value === "number" && Number.isInteger(value) && value > 0;
const duplicateTopLevelKeys = (source: string): string[] => {
const keys: string[] = [];
const duplicates = new Set<string>();
let depth = 0;
let index = 0;
while (index < source.length) {
const character = source[index];
if (character === "{") {
depth += 1;
index += 1;
continue;
}
if (character === "}") {
depth -= 1;
index += 1;
continue;
}
if (character !== '"') {
index += 1;
continue;
}
const start = index++;
let escaped = false;
while (index < source.length) {
const current = source[index++];
if (!escaped && current === '"') break;
escaped = !escaped && current === "\\";
if (current !== "\\") escaped = false;
}
if (depth !== 1) continue;
let cursor = index;
while (/\s/.test(source[cursor] ?? "")) cursor += 1;
if (source[cursor] !== ":") continue;
const key = JSON.parse(source.slice(start, index)) as string;
if (keys.includes(key)) duplicates.add(key);
keys.push(key);
}
return [...duplicates].sort();
};
export function parseSystemConfig(source: string): SystemConfig {
let parsed: unknown;
try {
parsed = JSON.parse(source);
} catch {
throw new SystemDocumentError("config.invalid-json", "Invalid config JSON");
}
const duplicates = duplicateTopLevelKeys(source);
if (duplicates.length)
throw new SystemDocumentError(
"config.duplicate-key",
`Duplicate config keys: ${duplicates.join(", ")}`,
);
const value = objectValue(parsed, "Config");
const keys = Object.keys(value).sort();
const validKeys = ["prefix", "schemaVersion", "title"];
if (
!("prefix" in value) ||
!("schemaVersion" in value) ||
keys.some((key) => !validKeys.includes(key))
)
throw new SystemDocumentError(
"json.keys",
`Expected keys prefix, schemaVersion[, title]; received ${keys.join(", ")}`,
);
if (typeof value.prefix !== "string" || !PREFIX.test(value.prefix))
throw new SystemDocumentError("config.prefix", "Invalid project prefix");
if (!positiveInteger(value.schemaVersion))
throw new SystemDocumentError(
"config.version",
"Schema version must be a positive integer",
);
if (
"title" in value &&
(typeof value.title !== "string" || value.title.trim() === "")
)
throw new SystemDocumentError("config.title", "Invalid project title");
return {
prefix: value.prefix,
schemaVersion: value.schemaVersion as number,
...(typeof value.title === "string" ? { title: value.title } : {}),
};
}
export function inspectSystemConfig(source: string): InspectedSystemConfig {
try {
return { config: parseSystemConfig(source) };
} catch (currentError) {
let parsed: unknown;
try {
parsed = JSON.parse(source);
} catch {
throw currentError;
}
if (duplicateTopLevelKeys(source).length > 0) throw currentError;
let value: Record<string, unknown>;
try {
value = objectValue(parsed, "Legacy config");
exactKeys(value, ["prefix", "schemaVersion", "styleVersion"]);
} catch {
throw currentError;
}
if (value.schemaVersion !== 1 || !positiveInteger(value.styleVersion))
throw currentError;
const config = parseSystemConfig(
JSON.stringify({
prefix: value.prefix,
schemaVersion: value.schemaVersion,
}),
);
return { config, legacyStyleVersion: value.styleVersion as number };
}
}
export function parseDocumentId(
source: string,
expectedPrefix?: string,
): ParsedDocumentId {
const match = new RegExp(
`^([A-Z][A-Z0-9]{1,7})-(SPEC|PHASE|PLAN|ISSUE|RESEARCH)-(${ID_CHARS})$`,
).exec(source);
if (!match)
throw new SystemDocumentError(
"id.invalid",
`Invalid document ID: ${source}`,
);
if (expectedPrefix && match[1] !== expectedPrefix)
throw new SystemDocumentError(
"id.prefix",
`Document ID must use prefix ${expectedPrefix}: ${source}`,
);
return {
id: source,
prefix: match[1] as string,
type: TYPE_BY_TOKEN.get(match[2]) as DocumentType,
token: match[3] as string,
};
}
export function validateDocumentPath(
documentPath: string,
metadata: DocumentMetadata,
prefix: string,
): void {
const parsed = parseDocumentId(metadata.id, prefix);
const expectedDirectory = DIRECTORY_BY_TYPE[metadata.type];
const pattern = new RegExp(`^${metadata.id}-${SLUG}$`);
const parts = documentPath.split("/");
if (
parsed.type !== metadata.type ||
parts.length !== 4 ||
parts[0] !== ".system" ||
parts[1] !== expectedDirectory ||
!pattern.test(parts[2] ?? "") ||
parts[3] !== "index.md"
)
throw new SystemDocumentError(
"document.path",
`Bundle path mismatch for ${metadata.id}: ${documentPath}`,
);
}
const requiredStringField = (fields: FrontmatterMap, key: string): string => {
const value = fields.get(key);
if (typeof value !== "string" || value.trim() === "")
throw new SystemDocumentError(
"metadata.value",
`${key} must be a non-empty string`,
);
return value;
};
const optionalUniqueStrings = (
fields: FrontmatterMap,
key: string,
): readonly string[] | undefined => {
const value = fields.get(key);
if (value === undefined) return undefined;
if (!Array.isArray(value) || value.some((item) => typeof item !== "string"))
throw new SystemDocumentError(
"metadata.value",
`${key} must be a string array`,
);
if (new Set(value).size !== value.length)
throw new SystemDocumentError(
"metadata.duplicate",
`${key} must contain unique values`,
);
return value as readonly string[];
};
const requiredUniqueStrings = (
fields: FrontmatterMap,
key: string,
): readonly string[] => {
const value = optionalUniqueStrings(fields, key);
if (!value)
throw new SystemDocumentError(
"metadata.value",
`${key} must be a string array`,
);
return value;
};
const statusField = <T extends string>(
fields: FrontmatterMap,
allowed: readonly T[],
message: string,
): T => {
const status = requiredStringField(fields, "status");
if (!allowed.includes(status as T))
throw new SystemDocumentError("metadata.status", message);
return status as T;
};
const projectMetadata = (
fields: FrontmatterMap,
prefix: string,
): DocumentMetadata => {
const id = requiredStringField(fields, "id");
const type = requiredStringField(fields, "type");
const title = requiredStringField(fields, "title");
const own = parseDocumentId(id, prefix);
if (own.type !== type)
throw new SystemDocumentError(
"metadata.identity",
`Metadata ID/type mismatch: ${id} / ${type}`,
);
const reference = (key: string, expected: DocumentType) => {
const value = requiredStringField(fields, key);
const parsed = parseDocumentId(value, prefix);
if (parsed.type !== expected)
throw new SystemDocumentError(
"metadata.reference-type",
`${key} must reference ${expected}: ${value}`,
);
return value;
};
const dependencies = (expected: "phase" | "plan") => {
const values = optionalUniqueStrings(fields, "depends_on");
if (!values) return undefined;
for (const value of values) {
const parsed = parseDocumentId(value, prefix);
if (parsed.type !== expected)
throw new SystemDocumentError(
"metadata.reference-type",
`depends_on must reference ${expected}: ${value}`,
);
}
return values;
};
switch (type) {
case "research":
return { id, type, title };
case "spec": {
const research = optionalUniqueStrings(fields, "research");
if (research) for (const item of research) parseDocumentId(item, prefix);
return research ? { id, type, title, research } : { id, type, title };
}
case "phase": {
const depends_on = dependencies("phase");
return {
id,
type,
title,
spec: reference("spec", "spec"),
status: statusField(
fields,
["draft", "done"],
"Phase status must be draft or done",
),
...(depends_on ? { depends_on } : {}),
};
}
case "plan": {
const phase = fields.get("phase");
const depends_on = dependencies("plan");
if (phase !== undefined && typeof phase !== "string")
throw new SystemDocumentError(
"metadata.value",
"phase must be a string",
);
if (typeof phase === "string") parseDocumentId(phase, prefix);
return {
id,
type,
title,
spec: reference("spec", "spec"),
...(typeof phase === "string" ? { phase } : {}),
status: statusField(
fields,
["draft", "done"],
"Plan status must be draft or done",
),
...(depends_on ? { depends_on } : {}),
};
}
case "issue":
return {
id,
type,
title,
status: statusField(
fields,
["open", "done"],
"Issue status must be open or done",
),
specs: requiredUniqueStrings(fields, "specs"),
};
default:
throw new SystemDocumentError(
"metadata.type",
`Unsupported metadata type: ${type}`,
);
}
};
export function parseAuthoredDocument(
source: string,
prefix: string,
): AuthoredDocument {
const parsed = parseRichMarkdown(source);
return {
metadata: projectMetadata(parsed.frontmatter, prefix),
frontmatter: parsed.frontmatter,
};
}
const diagnostic = (
code: string,
diagnosticPath: string,
message: string,
): Diagnostic => ({ code, path: diagnosticPath, message });
const compareDiagnostics = (left: Diagnostic, right: Diagnostic) =>
left.path.localeCompare(right.path) ||
left.code.localeCompare(right.code) ||
left.message.localeCompare(right.message);
const scanBundleAssets = (
absolute: string,
relative: string,
findings: Diagnostic[],
): void => {
for (const entry of readdirSync(absolute, { withFileTypes: true }).sort(
(left, right) => left.name.localeCompare(right.name),
)) {
if (relative.split("/").length === 3 && entry.name === "index.md") continue;
const childAbsolute = path.join(absolute, entry.name);
const childRelative = `${relative}/${entry.name}`;
const stats = lstatSync(childAbsolute, { throwIfNoEntry: false });
if (!stats) continue;
if (stats.isSymbolicLink())
findings.push(
diagnostic(
"bundle.symbolic-link",
childRelative,
`Bundle path is a symbolic link: ${childRelative}`,
),
);
else if (stats.isDirectory())
scanBundleAssets(childAbsolute, childRelative, findings);
}
};
export function discoverDocumentBundles(root: string): BundleDiscovery {
const sources: BundleDocumentSource[] = [];
const diagnostics: Diagnostic[] = [];
const systemRoot = path.join(root, ".system");
if (lstatSync(systemRoot, { throwIfNoEntry: false })?.isSymbolicLink())
return {
sources,
diagnostics: [
diagnostic(
"bundle.symbolic-link",
".system",
"Bundle path is a symbolic link: .system",
),
],
};
for (const directory of Object.values(DIRECTORY_BY_TYPE)) {
const relativeDirectory = `.system/${directory}`;
const absoluteDirectory = path.join(root, relativeDirectory);
const directoryStats = lstatSync(absoluteDirectory, {
throwIfNoEntry: false,
});
if (!directoryStats?.isDirectory() || directoryStats.isSymbolicLink())
continue;
for (const entry of readdirSync(absoluteDirectory, {
withFileTypes: true,
}).sort((left, right) => left.name.localeCompare(right.name))) {
const bundleRelative = `${relativeDirectory}/${entry.name}`;
const bundleAbsolute = path.join(absoluteDirectory, entry.name);
const bundleStats = lstatSync(bundleAbsolute, { throwIfNoEntry: false });
if (bundleStats?.isSymbolicLink()) {
diagnostics.push(
diagnostic(
"bundle.symbolic-link",
bundleRelative,
`Bundle path is a symbolic link: ${bundleRelative}`,
),
);
continue;
}
if (!bundleStats?.isDirectory()) {
diagnostics.push(
diagnostic(
"bundle.expected-directory",
bundleRelative,
`Expected a document bundle directory: ${bundleRelative}`,
),
);
continue;
}
const indexRelative = `${bundleRelative}/index.md`;
const indexAbsolute = path.join(bundleAbsolute, "index.md");
const indexStats = lstatSync(indexAbsolute, { throwIfNoEntry: false });
if (!indexStats)
diagnostics.push(
diagnostic(
"bundle.missing-index",
bundleRelative,
`Bundle is missing index.md: ${bundleRelative}`,
),
);
else if (indexStats.isSymbolicLink())
diagnostics.push(
diagnostic(
"bundle.symbolic-link",
indexRelative,
`Bundle path is a symbolic link: ${indexRelative}`,
),
);
else if (!indexStats.isFile())
diagnostics.push(
diagnostic(
"bundle.expected-file",
indexRelative,
`Expected a regular index.md: ${indexRelative}`,
),
);
else
sources.push({
path: indexRelative,
markdown: readFileSync(indexAbsolute, "utf8"),
});
scanBundleAssets(bundleAbsolute, bundleRelative, diagnostics);
}
}
return {
sources: sources.sort((left, right) => left.path.localeCompare(right.path)),
diagnostics: diagnostics.sort(compareDiagnostics),
};
}
const references = (
metadata: DocumentMetadata,
): readonly (readonly [string, DocumentType])[] => {
switch (metadata.type) {
case "spec":
return (metadata.research ?? []).map((id) => [id, "research"] as const);
case "phase":
return [
[metadata.spec, "spec"],
...(metadata.depends_on ?? []).map((id) => [id, "phase"] as const),
];
case "plan":
return [
[metadata.spec, "spec"],
...(metadata.phase ? ([[metadata.phase, "phase"]] as const) : []),
...(metadata.depends_on ?? []).map((id) => [id, "plan"] as const),
];
case "issue":
return metadata.specs.map((spec) => [spec, "spec"] as const);
default:
return [];
}
};
const dependencyReferences = (metadata: DocumentMetadata): readonly string[] =>
metadata.type === "phase" || metadata.type === "plan"
? (metadata.depends_on ?? [])
: [];
const diagnosticIdentity = (item: Diagnostic) =>
JSON.stringify([item.path, item.code, item.message]);
export function indexBundleDocuments(
sources: readonly BundleDocumentSource[],
prefix: string,
): BundleDocumentIndex {
const documents: BundleDocumentRecord[] = [];
const graphEligible: BundleDocumentRecord[] = [];
const diagnostics: Diagnostic[] = [];
for (const item of [...sources].sort((left, right) =>
left.path.localeCompare(right.path),
)) {
try {
const parsed = parseAuthoredDocument(item.markdown, prefix);
let pathValid = true;
try {
validateDocumentPath(item.path, parsed.metadata, prefix);
} catch (error) {
pathValid = false;
diagnostics.push(
diagnostic("document.path", item.path, (error as Error).message),
);
}
const record = {
path: item.path,
metadata: parsed.metadata,
frontmatter: parsed.frontmatter,
};
documents.push(record);
if (pathValid) graphEligible.push(record);
} catch (error) {
const value = error as SystemDocumentError | MarkdownDocumentError;
diagnostics.push(
diagnostic(
"document.metadata",
item.path,
`${value.code}: ${value.message}`,
),
);
}
}
const groups = new Map<string, BundleDocumentRecord[]>();
for (const document of graphEligible)
groups.set(document.metadata.id, [
...(groups.get(document.metadata.id) ?? []),
document,
]);
for (const [id, records] of groups) {
if (records.length < 2) continue;
const paths = records.map((record) => record.path).sort();
for (const record of records)
diagnostics.push(
diagnostic(
"graph.duplicate-id",
record.path,
`Duplicate ID ${id}: ${paths.join(", ")}`,
),
);
}
const unique = new Map(
[...groups].flatMap(([id, records]) => {
const [record] = records;
return records.length === 1 && record ? [[id, record] as const] : [];
}),
);
for (const document of graphEligible) {
for (const [targetId, expectedType] of references(document.metadata)) {
const referencedType = parseDocumentId(targetId, prefix).type;
const target = unique.get(targetId);
if (referencedType !== expectedType)
diagnostics.push(
diagnostic(
"graph.forbidden-edge",
document.path,
`${document.metadata.id} must reference ${expectedType}; ${targetId} is ${referencedType}`,
),
);
else if (!target)
diagnostics.push(
diagnostic(
"graph.dangling-reference",
document.path,
`${document.metadata.id} references missing ${targetId}`,
),
);
else if (target.metadata.type !== expectedType)
diagnostics.push(
diagnostic(
"graph.forbidden-edge",
document.path,
`${document.metadata.id} must reference ${expectedType}; ${targetId} is ${target.metadata.type}`,
),
);
}
if (document.metadata.type === "plan" && document.metadata.phase) {
const phase = unique.get(document.metadata.phase);
if (
phase?.metadata.type === "phase" &&
phase.metadata.spec !== document.metadata.spec
)
diagnostics.push(
diagnostic(
"graph.forbidden-edge",
document.path,
`${document.metadata.phase} belongs to ${phase.metadata.spec}, not ${document.metadata.spec}`,
),
);
}
if (
document.metadata.type === "phase" ||
document.metadata.type === "plan"
) {
for (const dependencyId of dependencyReferences(document.metadata)) {
const dependency = unique.get(dependencyId);
if (
dependency?.metadata.type === document.metadata.type &&
dependency.metadata.spec !== document.metadata.spec
)
diagnostics.push(
diagnostic(
"graph.forbidden-edge",
document.path,
`${dependencyId} belongs to ${dependency.metadata.spec}, not ${document.metadata.spec}`,
),
);
}
}
}
const visiting = new Set<string>();
const visited = new Set<string>();
const visit = (document: BundleDocumentRecord, stack: readonly string[]) => {
const id = document.metadata.id;
if (visited.has(id)) return;
if (visiting.has(id)) {
const start = stack.indexOf(id);
diagnostics.push(
diagnostic(
"graph.dependency-cycle",
document.path,
`Dependency cycle: ${[...stack.slice(start), id].join(" -> ")}`,
),
);
return;
}
visiting.add(id);
for (const dependencyId of [
...dependencyReferences(document.metadata),
].sort()) {
const dependency = unique.get(dependencyId);
if (dependency?.metadata.type === document.metadata.type)
visit(dependency, [...stack, id]);
}
visiting.delete(id);
visited.add(id);
};
for (const document of graphEligible)
if (document.metadata.type === "phase" || document.metadata.type === "plan")
visit(document, []);
return { documents, diagnostics: diagnostics.sort(compareDiagnostics) };
}
export function validateBundleCandidate(
current: readonly BundleDocumentSource[],
candidate: BundleDocumentSource,
prefix: string,
): readonly Diagnostic[] {
const baseline = new Set(
indexBundleDocuments(current, prefix).diagnostics.map(diagnosticIdentity),
);
const next = indexBundleDocuments(
[...current.filter((source) => source.path !== candidate.path), candidate],
prefix,
);
return next.diagnostics.filter(
(item) =>
item.path === candidate.path ||
(!baseline.has(diagnosticIdentity(item)) &&
item.code !== "graph.duplicate-id"),
);
}