@bizibot/contracts 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +131 -0
  3. package/conformance/patterns.json +12 -0
  4. package/dist/chunk-6OQSBZG4.js +709 -0
  5. package/dist/chunk-6OQSBZG4.js.map +1 -0
  6. package/dist/chunk-LONUJCLW.js +50 -0
  7. package/dist/chunk-LONUJCLW.js.map +1 -0
  8. package/dist/cli.js +258 -0
  9. package/dist/cli.js.map +1 -0
  10. package/dist/index.js +41 -0
  11. package/dist/index.js.map +1 -0
  12. package/dist/package-T64HPNWA.js +7 -0
  13. package/dist/package-T64HPNWA.js.map +1 -0
  14. package/dist/src/artifacts/discover.d.ts +28 -0
  15. package/dist/src/check/release.d.ts +12 -0
  16. package/dist/src/check/repository.d.ts +19 -0
  17. package/dist/src/check/snapshot.d.ts +37 -0
  18. package/dist/src/check/version-transitions.d.ts +23 -0
  19. package/dist/src/ci.d.ts +20 -0
  20. package/dist/src/cli.d.ts +2 -0
  21. package/dist/src/contracts-file/matcher.d.ts +2 -0
  22. package/dist/src/contracts-file/parse.d.ts +26 -0
  23. package/dist/src/contracts-file/pin.d.ts +10 -0
  24. package/dist/src/contracts-file/ranges.d.ts +11 -0
  25. package/dist/src/contracts-file/resolve.d.ts +16 -0
  26. package/dist/src/index.d.ts +15 -0
  27. package/dist/src/local.d.ts +8 -0
  28. package/dist/src/managed.d.ts +17 -0
  29. package/dist/src/runtime/handoff.d.ts +11 -0
  30. package/dist/src/versioning/paths.d.ts +2 -0
  31. package/dist/src/versioning/validate.d.ts +13 -0
  32. package/dist/src/versioning/version.d.ts +3 -0
  33. package/docs/agents.md +65 -0
  34. package/docs/checks.md +102 -0
  35. package/docs/contracts-file.md +112 -0
  36. package/docs/cross-repo.md +39 -0
  37. package/docs/practices.md +40 -0
  38. package/docs/taxonomy.md +77 -0
  39. package/docs/versioning.md +73 -0
  40. package/docs/workflow.md +49 -0
  41. package/package.json +50 -0
  42. package/skills/contracts-adopt/SKILL.md +70 -0
  43. package/skills/contracts-change/SKILL.md +74 -0
  44. package/skills/contracts-triage/SKILL.md +46 -0
  45. package/skills/contracts-write/SKILL.md +80 -0
  46. package/skills/contracts-write/references/adr.md +34 -0
  47. package/skills/contracts-write/references/design.md +37 -0
  48. package/skills/contracts-write/references/prd.md +49 -0
  49. package/skills/contracts-write/references/procedure.md +34 -0
  50. package/skills/contracts-write/references/spec.md +41 -0
  51. package/skills/contracts-write/references/standard.md +31 -0
  52. package/templates/agents-section.md +16 -0
  53. package/templates/kinds/adr.md +21 -0
  54. package/templates/kinds/design.md +22 -0
  55. package/templates/kinds/prd.md +29 -0
  56. package/templates/kinds/procedure.md +16 -0
  57. package/templates/kinds/spec.md +17 -0
  58. package/templates/kinds/standard.md +16 -0
  59. package/templates/workflows/check.yml +28 -0
  60. package/templates/workflows/release.yml +29 -0
@@ -0,0 +1,709 @@
1
+ // src/versioning/version.ts
2
+ import { inc, valid } from "semver";
3
+
4
+ // src/artifacts/discover.ts
5
+ import { valid as validSemver } from "semver";
6
+ import { parseDocument } from "yaml";
7
+ var DEFAULT_KIND_FOLDERS = { prd: "docs/prds", adr: "docs/adr", spec: "docs/specs", design: "docs/designs", standard: "docs/standards", procedure: "docs/procedures" };
8
+ var statuses = /* @__PURE__ */ new Set(["proposed", "accepted", "deprecated", "superseded"]);
9
+ var slugPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\/[a-z0-9]+(?:-[a-z0-9]+)*)*$/;
10
+ var ignoredNames = /* @__PURE__ */ new Set(["INDEX", "README"]);
11
+ var extractFrontmatter = (source) => {
12
+ if (!source.startsWith("---\n") && !source.startsWith("---\r\n")) return {};
13
+ const newline = source.startsWith("---\r\n") ? "\r\n" : "\n";
14
+ const openingLength = 3 + newline.length;
15
+ const close = source.indexOf(`${newline}---`, openingLength - newline.length);
16
+ const afterClose = close === -1 ? "" : source.slice(close + newline.length + 3);
17
+ if (close === -1 || afterClose !== "" && !afterClose.startsWith(newline)) {
18
+ return { error: "frontmatter is missing its closing delimiter" };
19
+ }
20
+ return { source: source.slice(openingLength, close) };
21
+ };
22
+ var versionFromSource = (source) => {
23
+ const block = extractFrontmatter(source);
24
+ if (block.source === void 0 || block.error) return void 0;
25
+ const document = parseDocument(block.source);
26
+ if (document.errors.length) return void 0;
27
+ const version = document.toJSON().version;
28
+ return typeof version === "string" && validSemver(version) === version ? version : void 0;
29
+ };
30
+ var discoverArtifact = (path, source, folders = DEFAULT_KIND_FOLDERS) => {
31
+ const normalized = path.replace(/^\.\//, "").replace(/\\/g, "/");
32
+ const matches = Object.entries(folders).filter(([, folder2]) => normalized.startsWith(`${folder2}/`) && normalized.endsWith(".md"));
33
+ if (matches.length === 0) return { errors: [] };
34
+ if (matches.length > 1) return { errors: [`${normalized} matches overlapping kind folders`] };
35
+ const [kind, folder] = matches[0];
36
+ const slug = normalized.slice(folder.length + 1, -3);
37
+ if (ignoredNames.has(slug.split("/").at(-1) ?? "")) return { errors: [] };
38
+ if (!slugPattern.test(slug)) return { errors: [`${normalized} has an invalid kebab-case slug`] };
39
+ const block = extractFrontmatter(source);
40
+ if (block.error) return { errors: [block.error] };
41
+ const document = block.source === void 0 ? void 0 : parseDocument(block.source);
42
+ if (document?.errors.length) return { errors: document.errors.map((error) => error.message) };
43
+ const fields = document?.toJSON() ?? {};
44
+ const errors = [];
45
+ if (fields.status !== void 0 && (typeof fields.status !== "string" || !statuses.has(fields.status))) errors.push("status must be proposed, accepted, deprecated, or superseded");
46
+ if (fields.version !== void 0 && (typeof fields.version !== "string" || validSemver(fields.version) !== fields.version)) errors.push("version must be a valid canonical SemVer string");
47
+ if (errors.length) return { errors };
48
+ return { artifact: { id: `${kind}/${slug}`, kind, path: normalized, status: fields.status, ...typeof fields.superseded_by === "string" ? { supersededBy: fields.superseded_by } : {}, version: fields.version }, errors: [] };
49
+ };
50
+
51
+ // src/versioning/version.ts
52
+ var nextVersion = (version, level) => {
53
+ if (!valid(version)) throw new Error(`${version} is not valid SemVer`);
54
+ return inc(version, level);
55
+ };
56
+ var versionArtifactSource = (source, baseVersion, level) => {
57
+ const target = nextVersion(baseVersion, level);
58
+ const block = extractFrontmatter(source);
59
+ if (block.source === void 0) throw new Error("artifact has no frontmatter version field");
60
+ const newline = source.startsWith("---\r\n") ? "\r\n" : "\n";
61
+ const end = source.indexOf(`${newline}---`, 3);
62
+ if (end === -1) throw new Error("artifact has no frontmatter version field");
63
+ const frontmatter = source.slice(0, end + newline.length);
64
+ const versionLine2 = /^version:[ \t]*(?:"[^"]*"|'[^']*'|[^\s#]+)(?<comment>[ \t]*#.*)?[ \t]*\r?$/m;
65
+ if (!versionLine2.test(frontmatter)) throw new Error("artifact has no frontmatter version field");
66
+ const rewritten = frontmatter.replace(versionLine2, (line, ...args) => {
67
+ const groups = args.at(-1);
68
+ return `version: ${target}${groups?.comment ?? ""}${line.endsWith("\r") ? "\r" : ""}`;
69
+ });
70
+ return rewritten + source.slice(end + newline.length);
71
+ };
72
+
73
+ // src/versioning/validate.ts
74
+ var name = (artifact) => artifact?.id ?? "new artifact";
75
+ var validateArtifactVersionTransition = (transition) => {
76
+ const { base, current, changed, changedBeyondVersion = false } = transition;
77
+ if (!current || !changed) return [];
78
+ if (!base) {
79
+ return current.version === void 0 || current.version === "0.1.0" ? [] : [{ artifact: name(current), message: "a new versioned artifact must start at 0.1.0" }];
80
+ }
81
+ if (base.version === void 0) {
82
+ return current.version === void 0 || current.version === "0.1.0" ? [] : [{ artifact: name(current), message: "an existing artifact may opt into versioning only at 0.1.0" }];
83
+ }
84
+ if (current.version === void 0) {
85
+ return [{ artifact: name(current), message: "an existing artifact version must not be removed" }];
86
+ }
87
+ if (!changedBeyondVersion) {
88
+ return current.version === base.version ? [] : [{ artifact: name(current), message: `an unchanged artifact must retain its base version ${base.version}` }];
89
+ }
90
+ const expected = ["major", "minor", "patch"].map((level) => nextVersion(base.version, level));
91
+ return expected.includes(current.version) ? [] : [{ artifact: name(current), message: `a changed artifact version must move exactly one SemVer step from ${base.version}` }];
92
+ };
93
+
94
+ // src/check/version-transitions.ts
95
+ var checkArtifactVersionTransitions = (changes, { baseHasContracts = true } = {}) => {
96
+ if (!baseHasContracts) return { errors: [] };
97
+ const errors = changes.flatMap(({ base, current, status, changedBeyondVersion, previousSource }) => {
98
+ const previousVersion = status === "renamed" && previousSource !== void 0 ? versionFromSource(previousSource) : void 0;
99
+ const renameBase = !base && current && previousVersion ? { ...current, version: previousVersion } : base;
100
+ return validateArtifactVersionTransition(
101
+ {
102
+ base: renameBase,
103
+ current,
104
+ changed: status !== "deleted",
105
+ changedBeyondVersion
106
+ }
107
+ );
108
+ });
109
+ return { errors };
110
+ };
111
+
112
+ // src/contracts-file/matcher.ts
113
+ var normalizePath = (path) => {
114
+ if (!path || path.startsWith("/") || path.startsWith("./") || path.includes("\\") || path.split("/").some((part) => part === "." || part === ".." || !part)) throw new Error(`path must be normalized and repository-relative: ${path}`);
115
+ return path;
116
+ };
117
+ var splitSegments = (pattern) => {
118
+ const segments = [];
119
+ let segment = "";
120
+ let escaped = false;
121
+ for (const character of pattern) {
122
+ if (escaped) {
123
+ segment += `\\${character}`;
124
+ escaped = false;
125
+ } else if (character === "\\") escaped = true;
126
+ else if (character === "/") {
127
+ segments.push(segment);
128
+ segment = "";
129
+ } else segment += character;
130
+ }
131
+ if (escaped) segment += "\\";
132
+ segments.push(segment);
133
+ return segments;
134
+ };
135
+ var matchSegment = (pattern, value) => {
136
+ const memo = /* @__PURE__ */ new Map();
137
+ const visit = (patternIndex, valueIndex) => {
138
+ const key = `${patternIndex}:${valueIndex}`;
139
+ const cached = memo.get(key);
140
+ if (cached !== void 0) return cached;
141
+ let result;
142
+ if (patternIndex === pattern.length) result = valueIndex === value.length;
143
+ else if (pattern[patternIndex] === "\\") result = valueIndex < value.length && pattern[patternIndex + 1] === value[valueIndex] && visit(patternIndex + 2, valueIndex + 1);
144
+ else if (pattern[patternIndex] === "*") result = visit(patternIndex + 1, valueIndex) || valueIndex < value.length && visit(patternIndex, valueIndex + 1);
145
+ else if (pattern[patternIndex] === "?") result = valueIndex < value.length && visit(patternIndex + 1, valueIndex + 1);
146
+ else result = valueIndex < value.length && pattern[patternIndex] === value[valueIndex] && visit(patternIndex + 1, valueIndex + 1);
147
+ memo.set(key, result);
148
+ return result;
149
+ };
150
+ return visit(0, 0);
151
+ };
152
+ var validatePattern = (rawPattern) => {
153
+ if (rawPattern.length === 0 || rawPattern.length > 1024) throw new Error("pattern must contain 1 to 1024 characters");
154
+ const pattern = rawPattern.startsWith("/") ? rawPattern.slice(1) : rawPattern;
155
+ if (pattern.includes("//")) throw new Error("pattern must not contain an empty segment");
156
+ const segments = splitSegments(pattern.endsWith("/") ? pattern.slice(0, -1) : pattern);
157
+ if (segments.length > 128) throw new Error("pattern exceeds 128 segments");
158
+ for (const segment of segments) {
159
+ let escaped = false;
160
+ for (let index = 0; index < segment.length; index += 1) {
161
+ const character = segment[index];
162
+ if (escaped) {
163
+ escaped = false;
164
+ continue;
165
+ }
166
+ if (character === "\\") {
167
+ escaped = true;
168
+ continue;
169
+ }
170
+ if (character === "*" && segment[index + 1] === "*" && segment !== "**") throw new Error("globstar must occupy a complete segment");
171
+ }
172
+ }
173
+ };
174
+ var matchesPattern = (path, rawPattern) => {
175
+ const normalizedPath = normalizePath(path);
176
+ validatePattern(rawPattern);
177
+ const rootAnchored = rawPattern.startsWith("/");
178
+ const pattern = rootAnchored ? rawPattern.slice(1) : rawPattern;
179
+ const directory = pattern.endsWith("/");
180
+ const segments = splitSegments(directory ? pattern.slice(0, -1) : pattern).filter((segment, index, all) => segment !== "**" || all[index - 1] !== "**");
181
+ const pathSegments = normalizedPath.split("/");
182
+ const anchored = rootAnchored || segments.length > 1;
183
+ const starts = anchored ? [0] : pathSegments.map((_, index) => index);
184
+ return starts.some((start) => {
185
+ const memo = /* @__PURE__ */ new Map();
186
+ const visit = (patternIndex, pathIndex) => {
187
+ const key = `${patternIndex}:${pathIndex}`;
188
+ const cached = memo.get(key);
189
+ if (cached !== void 0) return cached;
190
+ let result;
191
+ if (patternIndex === segments.length) result = directory ? pathIndex < pathSegments.length : true;
192
+ else if (segments[patternIndex] === "**") result = visit(patternIndex + 1, pathIndex) || pathIndex < pathSegments.length && visit(patternIndex, pathIndex + 1);
193
+ else result = pathIndex < pathSegments.length && matchSegment(segments[patternIndex], pathSegments[pathIndex]) && visit(patternIndex + 1, pathIndex + 1);
194
+ memo.set(key, result);
195
+ return result;
196
+ };
197
+ return visit(0, start);
198
+ });
199
+ };
200
+
201
+ // src/contracts-file/parse.ts
202
+ var entryPattern = /^(?:(?<repository>[a-z0-9_.-]+\/[a-z0-9_.-]+):)?(?<id>[a-z]+\/[a-z0-9_./-]+)@(?<range>.+)$/i;
203
+ var splitFields = (line) => {
204
+ const fields = [];
205
+ let field = "";
206
+ let escaped = false;
207
+ for (const character of line.trim()) {
208
+ if (escaped) {
209
+ field += `\\${character}`;
210
+ escaped = false;
211
+ } else if (character === "\\") {
212
+ escaped = true;
213
+ } else if (/\s/.test(character)) {
214
+ if (field) fields.push(field);
215
+ field = "";
216
+ } else {
217
+ field += character;
218
+ }
219
+ }
220
+ if (escaped) field += "\\";
221
+ if (field) fields.push(field);
222
+ return fields;
223
+ };
224
+ var parseContractsFile = (source) => {
225
+ const lines = [];
226
+ const errors = [];
227
+ source.split(/\r?\n/).forEach((rawLine, index) => {
228
+ const line = index + 1;
229
+ const trimmed = rawLine.trim();
230
+ if (!trimmed || trimmed.startsWith("#")) return;
231
+ const [pattern, ...rawEntries] = splitFields(rawLine);
232
+ if (!pattern || rawEntries.length === 0) {
233
+ errors.push({ line, message: "expected a path pattern and at least one entry" });
234
+ return;
235
+ }
236
+ if (pattern.startsWith("!")) {
237
+ errors.push({ line, message: "negation is not valid in CONTRACTS" });
238
+ return;
239
+ }
240
+ try {
241
+ validatePattern(pattern);
242
+ } catch (error) {
243
+ errors.push({ line, message: error instanceof Error ? error.message : "invalid glob pattern" });
244
+ return;
245
+ }
246
+ const entries = [];
247
+ for (const rawEntry of rawEntries) {
248
+ const match = entryPattern.exec(rawEntry);
249
+ if (!match?.groups) {
250
+ if (/^(?:prd|adr|spec|design|standard|procedure)\//.test(rawEntry)) {
251
+ errors.push({ line, message: `invalid versioned entry ${rawEntry}; did you mean <id>@<range>?` });
252
+ continue;
253
+ }
254
+ entries.push({ kind: "linked", path: rawEntry.replace(/\\(.)/g, "$1") });
255
+ continue;
256
+ }
257
+ const { repository, id, range } = match.groups;
258
+ entries.push(repository ? { kind: "external", repository, id, range } : { kind: "versioned", id, range });
259
+ }
260
+ lines.push({ line, pattern, entries });
261
+ });
262
+ return { lines, errors };
263
+ };
264
+
265
+ // src/contracts-file/pin.ts
266
+ import { valid as valid2 } from "semver";
267
+ var parseContractsPin = (source) => {
268
+ const lines = source.split(/\r?\n/);
269
+ const first = lines[0] ?? "";
270
+ const match = /^# @bizibot\/contracts (.+)$/.exec(first);
271
+ if (match) return valid2(match[1]) === match[1] ? { version: match[1] } : { error: "package pin must be an exact SemVer version" };
272
+ if (lines.some((line) => /^# @bizibot\/contracts\s/.test(line))) return { error: "package pin must be the first line of CONTRACTS" };
273
+ return { error: "missing first-line package pin (# @bizibot/contracts <version>)" };
274
+ };
275
+ var withContractsPin = (source, version) => {
276
+ const body = (source ?? "# path pattern governing artifacts\n").split(/\r?\n/).filter((line) => !/^# @bizibot\/contracts\s/.test(line)).join("\n");
277
+ return `# @bizibot/contracts ${version}
278
+ ${body}`;
279
+ };
280
+ var contractsSourceForInit = (source, version, update) => source !== void 0 && parseContractsPin(source).version !== void 0 && !update ? source : withContractsPin(source, version);
281
+
282
+ // src/contracts-file/resolve.ts
283
+ import { validRange } from "semver";
284
+ var keyFor = (entry) => entry.kind === "linked" ? `path:${entry.path}` : entry.kind === "external" ? `external:${entry.repository}:${entry.id}` : `id:${entry.id}`;
285
+ var appliesToSelf = (entry, path, artifact) => entry.kind === "linked" && entry.path === path || artifact !== void 0 && entry.kind === "versioned" && entry.id === artifact.id;
286
+ var resolveGoverningEntryDetails = (path, lines, artifact) => {
287
+ const resolved = /* @__PURE__ */ new Map();
288
+ for (const line of lines) {
289
+ if (!matchesPattern(path, line.pattern)) continue;
290
+ for (const entry of line.entries) if (!appliesToSelf(entry, path, artifact)) resolved.set(keyFor(entry), { entry, line: line.line });
291
+ }
292
+ return [...resolved.values()];
293
+ };
294
+ var resolveGoverningEntries = (path, lines, artifact) => resolveGoverningEntryDetails(path, lines, artifact).map(({ entry }) => entry);
295
+ var resolveArtifactGoverningEntries = (artifact, lines) => resolveGoverningEntries(artifact.path, lines, artifact);
296
+ var findDependentLines = (idOrPath, lines) => lines.filter(
297
+ (line) => line.entries.some((entry) => {
298
+ if (entry.kind === "linked") return entry.path === idOrPath;
299
+ if (entry.kind === "external") return `${entry.repository}:${entry.id}` === idOrPath;
300
+ return entry.id === idOrPath;
301
+ })
302
+ );
303
+ var findArtifactWarnings = (lines, artifacts) => {
304
+ const byPath = new Map(artifacts.map((artifact) => [artifact.path, artifact]));
305
+ const byId = new Map(artifacts.map((artifact) => [artifact.id, artifact]));
306
+ const warnings = [];
307
+ for (const line of lines) for (const entry of line.entries) {
308
+ const artifact = entry.kind === "linked" ? byPath.get(entry.path) : entry.kind === "versioned" ? byId.get(entry.id) : void 0;
309
+ if (artifact?.status === "deprecated") warnings.push({ line: line.line, message: `${artifact.id} is deprecated` });
310
+ if (artifact?.status === "superseded") warnings.push({ line: line.line, message: `${artifact.id} is superseded${artifact.supersededBy ? ` by ${artifact.supersededBy}` : ""}` });
311
+ }
312
+ return warnings;
313
+ };
314
+ var validateLinkedArtifactReferences = (lines, artifacts) => {
315
+ const artifactsByPath = new Map(artifacts.map((artifact) => [artifact.path, artifact]));
316
+ const referencesByArtifact = /* @__PURE__ */ new Map();
317
+ const errors = [];
318
+ for (const line of lines) {
319
+ for (const entry of line.entries) {
320
+ if (entry.kind === "external") {
321
+ if (!validRange(entry.range)) errors.push({ line: line.line, message: `${entry.range} is not a valid SemVer range` });
322
+ continue;
323
+ }
324
+ const artifact = entry.kind === "linked" ? artifactsByPath.get(entry.path) : artifacts.find((candidate) => candidate.id === entry.id);
325
+ if (!artifact) {
326
+ errors.push({ line: line.line, message: `${entry.kind === "linked" ? entry.path : entry.id} does not name a local governing artifact` });
327
+ continue;
328
+ }
329
+ if (entry.kind === "versioned" && !artifact.version) errors.push({ line: line.line, message: `${artifact.id} has no version; use a linked path or add version: 0.1.0 to opt in` });
330
+ if (entry.kind === "versioned" && !validRange(entry.range)) errors.push({ line: line.line, message: `${entry.range} is not a valid SemVer range` });
331
+ const form = entry.kind === "linked" ? "linked" : "versioned";
332
+ const prior = referencesByArtifact.get(artifact.id) ?? [];
333
+ prior.push({ line: line.line, form });
334
+ referencesByArtifact.set(artifact.id, prior);
335
+ }
336
+ }
337
+ for (const [id, references] of referencesByArtifact) {
338
+ if (references.some((reference) => reference.form === "linked") && references.some((reference) => reference.form === "versioned")) {
339
+ errors.push({ line: references[0].line, message: `${id} mixes linked and versioned references on lines ${references.map((reference) => reference.line).join(", ")}` });
340
+ }
341
+ }
342
+ return errors;
343
+ };
344
+
345
+ // src/check/repository.ts
346
+ var checkRepository = (files, paths = Object.keys(files)) => {
347
+ const artifacts = [];
348
+ const errors = [];
349
+ const warnings = [];
350
+ for (const [path, source] of Object.entries(files)) {
351
+ const discovered = discoverArtifact(path, source);
352
+ errors.push(...discovered.errors.map((message) => ({ path, message })));
353
+ if (discovered.artifact) artifacts.push(discovered.artifact);
354
+ }
355
+ const ids = /* @__PURE__ */ new Map();
356
+ for (const artifact of artifacts) {
357
+ const prior = ids.get(artifact.id);
358
+ if (prior) errors.push({ path: artifact.path, message: `${artifact.id} duplicates ${prior.path}` });
359
+ else ids.set(artifact.id, artifact);
360
+ }
361
+ const contracts = files.CONTRACTS;
362
+ if (contracts === void 0) {
363
+ errors.push({ path: "CONTRACTS", message: "missing root CONTRACTS file" });
364
+ return { artifacts, lines: [], errors, warnings };
365
+ }
366
+ const pin = parseContractsPin(contracts);
367
+ if (pin.error) errors.push({ path: "CONTRACTS", line: 1, message: pin.error });
368
+ const parsed = parseContractsFile(contracts);
369
+ errors.push(...parsed.errors.map(({ line, message }) => ({ path: "CONTRACTS", line, message })));
370
+ errors.push(...validateLinkedArtifactReferences(parsed.lines, artifacts).map(({ line, message }) => ({ path: "CONTRACTS", line, message })));
371
+ warnings.push(...findArtifactWarnings(parsed.lines, artifacts).map(({ line, message }) => ({ path: "CONTRACTS", line, message })));
372
+ const normalizedPaths = paths.map((path) => path.replace(/^\.\//, "").replaceAll("\\", "/"));
373
+ warnings.push(...parsed.lines.filter((line) => !normalizedPaths.some((path) => matchesPattern(path, line.pattern))).map((line) => ({ path: "CONTRACTS", line: line.line, message: `dead pattern ${line.pattern}` })));
374
+ return { artifacts, ...pin.version ? { pin: pin.version } : {}, lines: parsed.lines, errors, warnings };
375
+ };
376
+
377
+ // src/contracts-file/ranges.ts
378
+ import { satisfies } from "semver";
379
+ var validateContractRanges = (paths, lines, artifacts) => {
380
+ const byId = new Map(artifacts.map((artifact) => [artifact.id, artifact]));
381
+ const byPath = new Map(artifacts.map((artifact) => [artifact.path, artifact]));
382
+ const violations = /* @__PURE__ */ new Map();
383
+ for (const path of paths) {
384
+ const subject = byPath.get(path);
385
+ for (const { entry, line } of resolveGoverningEntryDetails(path, lines, subject)) {
386
+ if (entry.kind !== "versioned") continue;
387
+ const artifact = byId.get(entry.id);
388
+ if (!artifact?.version || satisfies(artifact.version, entry.range)) continue;
389
+ const key = `${line}:${entry.id}:${entry.range}`;
390
+ const violation = violations.get(key) ?? { line, id: entry.id, version: artifact.version, range: entry.range, paths: [] };
391
+ violation.paths.push(path);
392
+ violations.set(key, violation);
393
+ }
394
+ }
395
+ return [...violations.values()].sort((left, right) => left.line - right.line || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).map(({ line, id, version, range, paths: matchedPaths }) => {
396
+ const paths2 = [...matchedPaths].sort();
397
+ const samples = paths2.slice(0, 3).join(", ");
398
+ const example = paths2.length > 3 ? `${samples}, \u2026` : samples;
399
+ const count = `${paths2.length} ${paths2.length === 1 ? "path" : "paths"}`;
400
+ return { line, message: `${id}@${version} does not satisfy ${range} (${count}, e.g. ${example})` };
401
+ });
402
+ };
403
+
404
+ // src/managed.ts
405
+ var AGENT_SKILL_FOLDERS = {
406
+ claude: ".claude/skills",
407
+ copilot: ".github/skills"
408
+ };
409
+ var MANAGED_MARKER = "@bizibot/contracts";
410
+ var managedProcedureSource = (version, workflow) => `<!-- BEGIN ${MANAGED_MARKER} ${version} (managed: do not edit; run \`contracts init --update\`) -->
411
+
412
+ ${workflow.endsWith("\n") ? workflow : `${workflow}
413
+ `}<!-- END ${MANAGED_MARKER} -->
414
+ `;
415
+ var escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
416
+ var managedSkill = new RegExp(`^(?:${Object.values(AGENT_SKILL_FOLDERS).map(escapeRegex).join("|")})/(contracts-[a-z0-9-]+)/SKILL\\.md$`);
417
+ var versionMarker = new RegExp(`${MANAGED_MARKER.replace("/", "\\/")}\\s+(\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?)`);
418
+ var tarEntry = (archive, path) => {
419
+ let offset = 0;
420
+ while (offset + 512 <= archive.length) {
421
+ const header = archive.subarray(offset, offset + 512);
422
+ const name2 = header.subarray(0, 100).toString("utf8").replace(/\0.*$/, "");
423
+ const size = Number.parseInt(header.subarray(124, 136).toString("utf8").replace(/\0.*$/, "").trim() || "0", 8);
424
+ const start = offset + 512;
425
+ if (name2 === `package/${path}`) return archive.subarray(start, start + size).toString("utf8");
426
+ offset = start + Math.ceil(size / 512) * 512;
427
+ }
428
+ throw new Error(`managed package archive is missing ${path}`);
429
+ };
430
+ var readRegistryFiles = async (version, paths) => {
431
+ const { createHash, timingSafeEqual } = await import("crypto");
432
+ const { gunzipSync } = await import("zlib");
433
+ const registry = (process.env.npm_config_registry ?? "https://registry.npmjs.org").replace(/\/$/, "");
434
+ const metadataResponse = await fetch(`${registry}/${encodeURIComponent("@bizibot/contracts")}/${version}`);
435
+ if (!metadataResponse.ok) throw new Error(`cannot read @bizibot/contracts@${version} registry metadata (${metadataResponse.status})`);
436
+ const metadata = await metadataResponse.json();
437
+ const archiveResponse = await fetch(metadata.dist.tarball);
438
+ if (!archiveResponse.ok) throw new Error(`cannot read @bizibot/contracts@${version} archive (${archiveResponse.status})`);
439
+ const compressed = Buffer.from(await archiveResponse.arrayBuffer());
440
+ const [algorithm, encoded] = metadata.dist.integrity.split("-", 2);
441
+ if (algorithm !== "sha512" || !encoded) throw new Error(`@bizibot/contracts@${version} has no supported SHA-512 integrity`);
442
+ const actual = createHash("sha512").update(compressed).digest();
443
+ const expected = Buffer.from(encoded, "base64");
444
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) throw new Error(`@bizibot/contracts@${version} archive failed integrity verification`);
445
+ const archive = gunzipSync(compressed);
446
+ return Object.fromEntries(paths.map((path) => [path, tarEntry(archive, path)]));
447
+ };
448
+ var loadManagedFileExpectations = async (contents, pin) => {
449
+ const { readFile: readFile2 } = await import("fs/promises");
450
+ const packageJson = await import("./package-T64HPNWA.js");
451
+ const expected = {};
452
+ const resources = /* @__PURE__ */ new Map();
453
+ const versionFor = (source, path) => {
454
+ const version = source.match(versionMarker)?.[1];
455
+ if (!version) throw new Error(`${path} has an invalid @bizibot/contracts managed-file marker`);
456
+ return version;
457
+ };
458
+ if (contents["AGENTS.md"]?.includes(`BEGIN ${MANAGED_MARKER}`)) resources.set("AGENTS.md", { version: versionFor(contents["AGENTS.md"], "AGENTS.md"), path: "templates/agents-section.md", transform: (source) => source });
459
+ if (contents["docs/procedures/contracts-workflow.md"]?.includes(`BEGIN ${MANAGED_MARKER}`)) resources.set("docs/procedures/contracts-workflow.md", { version: versionFor(contents["docs/procedures/contracts-workflow.md"], "docs/procedures/contracts-workflow.md"), path: "docs/workflow.md", transform: (source) => managedProcedureSource("{{version}}", source) });
460
+ for (const path of Object.keys(contents)) {
461
+ const skill = managedSkill.exec(path)?.[1];
462
+ if (skill && contents[path]?.includes(MANAGED_MARKER)) resources.set(path, { version: versionFor(contents[path], path), path: `skills/${skill}/SKILL.md`, transform: (source) => source });
463
+ }
464
+ const cache = /* @__PURE__ */ new Map();
465
+ for (const [target, resource] of resources) {
466
+ if (pin && resource.version !== pin) throw new Error(`${target} has @bizibot/contracts marker ${resource.version}, which does not match CONTRACTS pin ${pin}`);
467
+ let source;
468
+ if (resource.version === packageJson.default.version) source = await readFile2(new URL(`../${resource.path}`, import.meta.url), "utf8");
469
+ else {
470
+ if (!cache.has(resource.version)) cache.set(resource.version, await readRegistryFiles(resource.version, [...resources.values()].filter((entry) => entry.version === resource.version).map((entry) => entry.path)));
471
+ source = cache.get(resource.version)[resource.path];
472
+ }
473
+ expected[target] = resource.transform(source).replaceAll("{{version}}", resource.version);
474
+ }
475
+ return expected;
476
+ };
477
+ var managedFileDiagnostics = (contents, expected) => Object.entries(expected).flatMap(([path, source]) => contents[path] === void 0 || (path === "AGENTS.md" ? contents[path].includes(source) : contents[path] === source) ? [] : [{ path, message: "managed file differs from the installed @bizibot/contracts version; run contracts init --update" }]);
478
+
479
+ // src/check/snapshot.ts
480
+ var versionLine = /^version:[^\r\n]*(?:\r?\n|$)/m;
481
+ var sameExceptVersion = (left, right) => left.replace(versionLine, "version: <contract-version>\n") === right.replace(versionLine, "version: <contract-version>\n");
482
+ var deriveArtifactChanges = (changes, base, current, baseArtifacts, currentArtifacts) => {
483
+ const baseByPath = new Map(baseArtifacts.map((artifact) => [artifact.path, artifact]));
484
+ const currentByPath = new Map(currentArtifacts.map((artifact) => [artifact.path, artifact]));
485
+ return changes.map(({ status, path, previousPath }) => {
486
+ const priorPath = previousPath ?? path;
487
+ const previousSource = base.contents[priorPath];
488
+ const currentSource = current.contents[path];
489
+ return { status, base: baseByPath.get(priorPath), current: currentByPath.get(path), previousSource, changedBeyondVersion: previousSource !== void 0 && currentSource !== void 0 && !sameExceptVersion(previousSource, currentSource) };
490
+ });
491
+ };
492
+ var escapeRegex2 = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
493
+ var kindMarkdown = new RegExp(`^(?:${Object.values(DEFAULT_KIND_FOLDERS).map(escapeRegex2).join("|")})/.+\\.md$`);
494
+ var ignoredMarkdown = /\/(?:INDEX|README)\.md$/;
495
+ var managedSkill2 = new RegExp(`^(?:${Object.values(AGENT_SKILL_FOLDERS).map(escapeRegex2).join("|")})/contracts-[a-z0-9-]+/`);
496
+ var requiresSnapshotContent = (path) => path === "CONTRACTS" || path === "AGENTS.md" || managedSkill2.test(path) || kindMarkdown.test(path) && !ignoredMarkdown.test(path);
497
+ var isGoverningArtifactPath = (path) => kindMarkdown.test(path) && !ignoredMarkdown.test(path);
498
+ var incompleteSnapshotDiagnostics = (snapshot, changes, base) => {
499
+ const required = new Set(snapshot.paths.filter(requiresSnapshotContent));
500
+ if (base) {
501
+ for (const change of changes) if (change.status === "renamed" && change.previousPath && kindMarkdown.test(change.path)) required.add(change.previousPath);
502
+ }
503
+ return [...required].filter((path) => (snapshot.paths.includes(path) || base && changes.some((change) => change.status === "renamed" && change.previousPath === path)) && snapshot.contents[path] === void 0).sort().map((path) => ({ path, message: "incomplete snapshot: required file content is missing" }));
504
+ };
505
+ var compareCodeUnits = (left, right) => left < right ? -1 : left > right ? 1 : 0;
506
+ var diagnosticOrder = (left, right) => {
507
+ const category = compareCodeUnits(left.category, right.category);
508
+ if (category !== 0) return category;
509
+ const leftPath = "path" in left ? left.path : left.artifact;
510
+ const rightPath = "path" in right ? right.path : right.artifact;
511
+ const leftLine = "line" in left ? left.line ?? 0 : 0;
512
+ const rightLine = "line" in right ? right.line ?? 0 : 0;
513
+ return compareCodeUnits(leftPath, rightPath) || leftLine - rightLine || compareCodeUnits(left.message, right.message);
514
+ };
515
+ var checkSnapshot = (input) => {
516
+ const repository = checkRepository(input.snapshot.contents, input.snapshot.paths);
517
+ const baseRepository = checkRepository(input.base.contents, input.base.paths);
518
+ const transitions = checkArtifactVersionTransitions(deriveArtifactChanges(input.changes, input.base, input.snapshot, baseRepository.artifacts, repository.artifacts), {
519
+ baseHasContracts: input.base.contents.CONTRACTS !== void 0
520
+ });
521
+ const ranges = input.targetIsDefaultBranch ? validateContractRanges(input.snapshot.paths, repository.lines, repository.artifacts) : [];
522
+ return {
523
+ errors: [
524
+ ...repository.errors.map((error) => ({ category: "repository", ...error })),
525
+ ...managedFileDiagnostics(input.snapshot.contents, input.managedFiles ?? {}).map((error) => ({ category: "repository", ...error })),
526
+ ...incompleteSnapshotDiagnostics(input.snapshot, input.changes, false).map((error) => ({ category: "repository", ...error })),
527
+ ...incompleteSnapshotDiagnostics(input.base, input.changes, true).map((error) => ({ category: "repository", ...error })),
528
+ ...transitions.errors.map((error) => ({ category: "version", ...error })),
529
+ ...ranges.map((error) => ({ category: "range", path: "CONTRACTS", ...error }))
530
+ ].sort(diagnosticOrder),
531
+ warnings: repository.warnings
532
+ };
533
+ };
534
+
535
+ // src/check/release.ts
536
+ import { lt, valid as valid3 } from "semver";
537
+ var checkReleaseSnapshot = (snapshot, tags) => {
538
+ const repository = checkRepository(snapshot.contents, snapshot.paths);
539
+ const errors = [
540
+ ...repository.errors,
541
+ ...validateContractRanges(snapshot.paths, repository.lines, repository.artifacts).map((error) => ({ path: "CONTRACTS", line: error.line, message: error.message }))
542
+ ];
543
+ const byId = new Map(repository.artifacts.map((artifact) => [artifact.id, artifact]));
544
+ for (const tag of tags) {
545
+ const split = tag.lastIndexOf("@");
546
+ if (split <= 0 || !tag.includes("/")) continue;
547
+ const taggedVersion = tag.slice(split + 1);
548
+ if (!valid3(taggedVersion)) continue;
549
+ const artifact = byId.get(tag.slice(0, split));
550
+ if (!artifact) continue;
551
+ if (!artifact.version) errors.push({ path: artifact.path, message: `${artifact.id} removed its version after tag ${tag}` });
552
+ else if (lt(artifact.version, taggedVersion)) errors.push({ path: artifact.path, message: `${artifact.id}@${artifact.version} is lower than existing tag ${tag}` });
553
+ }
554
+ return { errors, artifacts: repository.artifacts };
555
+ };
556
+ var tagsToCreate = (artifacts, tags) => {
557
+ const existing = new Set(tags);
558
+ return artifacts.flatMap((artifact) => artifact.version && !existing.has(`${artifact.id}@${artifact.version}`) ? [`${artifact.id}@${artifact.version}`] : []);
559
+ };
560
+
561
+ // src/local.ts
562
+ import { execFile as execFileCallback } from "child_process";
563
+ import { readdir, readFile } from "fs/promises";
564
+ import { promisify } from "util";
565
+ import { join, relative } from "path";
566
+ var walk = async (root, directory = root) => {
567
+ const entries = await readdir(directory, { withFileTypes: true });
568
+ const paths = [];
569
+ for (const entry of entries) {
570
+ if (entry.name === ".git" || entry.name === "node_modules" || entry.name === "dist") continue;
571
+ const full = join(directory, entry.name);
572
+ if (entry.isDirectory()) paths.push(...await walk(root, full));
573
+ else if (entry.isFile()) paths.push(relative(root, full).replaceAll("\\", "/"));
574
+ }
575
+ return paths;
576
+ };
577
+ var readLocalSnapshot = async (root) => {
578
+ let paths;
579
+ try {
580
+ paths = (await git(root, ["ls-files", "--cached", "--others", "--exclude-standard"])).split("\n").filter(Boolean).sort();
581
+ } catch {
582
+ paths = (await walk(root)).sort();
583
+ }
584
+ const contents = Object.fromEntries(await Promise.all(paths.filter(requiresSnapshotContent).map(async (path) => [path, await readFile(join(root, path), "utf8")])));
585
+ return { paths, contents };
586
+ };
587
+ var execFile = promisify(execFileCallback);
588
+ var git = async (root, args) => (await execFile("git", args, { cwd: root })).stdout;
589
+ var runGit = git;
590
+ var readGitSnapshot = async (root, revision, additionalContents = []) => {
591
+ const paths = (await git(root, ["ls-tree", "-r", "--name-only", revision])).split("\n").filter(Boolean).sort();
592
+ const contentPaths = paths.filter((path) => requiresSnapshotContent(path) || additionalContents.includes(path));
593
+ const contents = Object.fromEntries(await Promise.all(contentPaths.map(async (path) => [path, await git(root, ["show", `${revision}:${path}`])])));
594
+ return { paths, contents };
595
+ };
596
+ var readLocalChanges = async (root, base) => {
597
+ const output = await git(root, ["diff", "--name-status", "-M", base, "--"]);
598
+ const changes = output.split("\n").filter(Boolean).map((line) => {
599
+ const [rawStatus, first, second] = line.split(" ");
600
+ const status = rawStatus.startsWith("R") ? "renamed" : rawStatus === "A" ? "added" : rawStatus === "D" ? "deleted" : "modified";
601
+ return status === "renamed" ? { status, path: second, previousPath: first } : { status, path: first };
602
+ });
603
+ const changed = new Set(changes.map((change) => change.path));
604
+ const untracked = (await git(root, ["ls-files", "--others", "--exclude-standard"])).split("\n").filter(Boolean);
605
+ return [...changes, ...untracked.filter((path) => !changed.has(path)).map((path) => ({ status: "added", path }))];
606
+ };
607
+ var readLocalBase = async (root) => {
608
+ try {
609
+ const defaultRef = (await git(root, ["symbolic-ref", "refs/remotes/origin/HEAD"])).trim();
610
+ return (await git(root, ["merge-base", "HEAD", defaultRef])).trim();
611
+ } catch {
612
+ return "HEAD^";
613
+ }
614
+ };
615
+
616
+ // src/ci.ts
617
+ var overlayCiSnapshot = (base, overlays) => {
618
+ const paths = new Set(base.paths);
619
+ const contents = { ...base.contents };
620
+ const changes = [];
621
+ for (const overlay of overlays) {
622
+ if (overlay.status === "deleted") {
623
+ paths.delete(overlay.path);
624
+ delete contents[overlay.path];
625
+ } else if (overlay.status === "renamed") {
626
+ if (!overlay.previousPath) throw new Error(`renamed API file ${overlay.path} is missing previousPath`);
627
+ paths.delete(overlay.previousPath);
628
+ delete contents[overlay.previousPath];
629
+ paths.add(overlay.path);
630
+ } else paths.add(overlay.path);
631
+ if (overlay.content !== void 0) contents[overlay.path] = overlay.content;
632
+ changes.push({ status: overlay.status, path: overlay.path, previousPath: overlay.previousPath });
633
+ }
634
+ return { snapshot: { paths: [...paths].sort(), contents }, changes };
635
+ };
636
+ var apiError = (response, url) => new Error(`GitHub API ${response.status} for ${url}`);
637
+ var decodeContent = (content) => Buffer.from(content.replace(/\n/g, ""), "base64").toString("utf8");
638
+ var readGitHubPullRequest = async (repository, pullNumber, token, apiUrl = process.env.GITHUB_API_URL ?? "https://api.github.com", fetcher = fetch) => {
639
+ const request = async (path) => {
640
+ const url = `${apiUrl.replace(/\/$/, "")}${path}`;
641
+ const response = await fetcher(url, { headers: { Accept: "application/vnd.github+json", Authorization: `Bearer ${token}`, "X-GitHub-Api-Version": "2022-11-28" } });
642
+ if (!response.ok) throw apiError(response, url);
643
+ return response.json();
644
+ };
645
+ const [pull, settings] = await Promise.all([request(`/repos/${repository}/pulls/${pullNumber}`), request(`/repos/${repository}`)]);
646
+ const files = [];
647
+ for (let page = 1; ; page += 1) {
648
+ const result = await request(`/repos/${repository}/pulls/${pullNumber}/files?per_page=100&page=${page}`);
649
+ files.push(...result);
650
+ if (result.length < 100) break;
651
+ }
652
+ if (files.length !== pull.changed_files) throw new Error(`GitHub API returned ${files.length} of ${pull.changed_files} changed files; pull requests above GitHub's file-list limit cannot be checked safely`);
653
+ const overlays = [];
654
+ for (const file of files) {
655
+ const status = file.status === "removed" ? "deleted" : file.status;
656
+ const overlay = { status, path: file.filename, ...file.previous_filename ? { previousPath: file.previous_filename } : {} };
657
+ if (status !== "deleted" && requiresSnapshotContent(file.filename)) {
658
+ const value = await request(`/repos/${repository}/contents/${file.filename.split("/").map(encodeURIComponent).join("/")}?ref=${pull.head.sha}`);
659
+ if (value.encoding !== "base64") throw new Error(`GitHub API returned unsupported ${value.encoding} encoding for ${file.filename}`);
660
+ overlay.content = decodeContent(value.content);
661
+ }
662
+ overlays.push(overlay);
663
+ }
664
+ return {
665
+ baseSha: pull.base.sha,
666
+ targetIsDefaultBranch: pull.base.ref === settings.default_branch,
667
+ overlays
668
+ };
669
+ };
670
+
671
+ // src/index.ts
672
+ var JSON_SCHEMA_VERSION = 1;
673
+ var toJsonEnvelope = (data) => ({
674
+ schemaVersion: JSON_SCHEMA_VERSION,
675
+ data
676
+ });
677
+
678
+ export {
679
+ DEFAULT_KIND_FOLDERS,
680
+ versionArtifactSource,
681
+ validateArtifactVersionTransition,
682
+ checkArtifactVersionTransitions,
683
+ parseContractsPin,
684
+ withContractsPin,
685
+ contractsSourceForInit,
686
+ resolveGoverningEntries,
687
+ resolveArtifactGoverningEntries,
688
+ findDependentLines,
689
+ checkRepository,
690
+ validateContractRanges,
691
+ AGENT_SKILL_FOLDERS,
692
+ managedProcedureSource,
693
+ loadManagedFileExpectations,
694
+ deriveArtifactChanges,
695
+ isGoverningArtifactPath,
696
+ checkSnapshot,
697
+ checkReleaseSnapshot,
698
+ tagsToCreate,
699
+ readLocalSnapshot,
700
+ runGit,
701
+ readGitSnapshot,
702
+ readLocalChanges,
703
+ readLocalBase,
704
+ overlayCiSnapshot,
705
+ readGitHubPullRequest,
706
+ JSON_SCHEMA_VERSION,
707
+ toJsonEnvelope
708
+ };
709
+ //# sourceMappingURL=chunk-6OQSBZG4.js.map