@tanziro/plumbline 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohamed Ashref Ben Abdallah
4
+ Copyright (c) 2026 Tanzir (tanziro.com)
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ // A stable entry point, so pnpm can link the command at install time, before dist/ is built.
3
+ import "../dist/index.js";
@@ -0,0 +1,281 @@
1
+ // src/lib.ts
2
+ import { spawnSync } from "child_process";
3
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "fs";
4
+ import { dirname, join, relative, resolve } from "path";
5
+ import { fileURLToPath } from "url";
6
+ import {
7
+ CONTRACT_FILE,
8
+ buildGraph,
9
+ checkContract,
10
+ contractAt,
11
+ createRun,
12
+ currentRun,
13
+ emptyContract,
14
+ finalizeReport,
15
+ findRun,
16
+ hashFile,
17
+ loadContract,
18
+ loadLenses,
19
+ parseContract,
20
+ readRunJson,
21
+ repoRoot,
22
+ resolveScope,
23
+ runDeterministic,
24
+ writeReport,
25
+ writeRunJson
26
+ } from "@tanziro/plumbline-core";
27
+
28
+ // package.json
29
+ var package_default = {
30
+ name: "@tanziro/plumbline",
31
+ version: "1.0.0",
32
+ description: "Plumbline CLI and MCP server: scope, import graph diff, contract checks and reports.",
33
+ license: "MIT",
34
+ type: "module",
35
+ repository: {
36
+ type: "git",
37
+ url: "git+https://github.com/tanzir71/plumbline.git",
38
+ directory: "packages/cli"
39
+ },
40
+ homepage: "https://tanzir71.github.io/plumbline/",
41
+ engines: {
42
+ node: ">=20.12.0"
43
+ },
44
+ bin: {
45
+ plumbline: "./bin/plumbline.js"
46
+ },
47
+ exports: {
48
+ ".": {
49
+ types: "./dist/lib.d.ts",
50
+ import: "./dist/lib.js"
51
+ },
52
+ "./package.json": "./package.json"
53
+ },
54
+ files: [
55
+ "bin",
56
+ "dist",
57
+ "lenses"
58
+ ],
59
+ publishConfig: {
60
+ access: "public"
61
+ },
62
+ scripts: {
63
+ build: "tsup && node ../../scripts/copy-lenses.mjs",
64
+ test: "vitest run",
65
+ typecheck: "tsc --noEmit"
66
+ },
67
+ dependencies: {
68
+ "@modelcontextprotocol/sdk": "^1.32.2",
69
+ "@tanziro/plumbline-core": "workspace:^",
70
+ yaml: "^2.9.1",
71
+ zod: "^4.6.7"
72
+ }
73
+ };
74
+
75
+ // src/lib.ts
76
+ var VERSION = package_default.version;
77
+ var OUTPUT_LIMIT = 8e3;
78
+ var canonical = (path) => existsSync(path) ? realpathSync.native(path) : path;
79
+ function lensDir() {
80
+ const here = dirname(fileURLToPath(import.meta.url));
81
+ const shipped = join(here, "..", "lenses");
82
+ return existsSync(shipped) ? shipped : join(here, "..", "..", "..", "skills", "plumbline", "lenses");
83
+ }
84
+ function listLenses(root) {
85
+ return loadLenses(lensDir(), root);
86
+ }
87
+ function startScope(args) {
88
+ const scope = resolveScope(args);
89
+ const run = createRun(scope.repo);
90
+ const meta = { startedAt: (/* @__PURE__ */ new Date()).toISOString(), target: args.target, base: args.base };
91
+ writeRunJson(run, "run.json", meta);
92
+ writeRunJson(run, "scope.json", scope);
93
+ return { scope, run };
94
+ }
95
+ function contractFor(scope, source) {
96
+ return contractAt(scope.repo, source === "base" ? scope.mergeBase : null);
97
+ }
98
+ function continueOrStart(args) {
99
+ const scope = resolveScope(args);
100
+ const latest = findRun(scope.repo);
101
+ if (latest && !existsSync(join(latest.dir, "report.json"))) {
102
+ const prior = readRunJson(latest, "scope.json");
103
+ if (prior?.headSha === scope.headSha && prior.mergeBase === scope.mergeBase && prior.mode === scope.mode) {
104
+ writeRunJson(latest, "scope.json", scope);
105
+ return { scope, run: latest };
106
+ }
107
+ }
108
+ return startScope(args);
109
+ }
110
+ async function runGraph(args) {
111
+ const { scope, run } = continueOrStart(args);
112
+ const graph = await runDeterministic(scope, contractFor(scope, args.contractFrom ?? "head"));
113
+ writeRunJson(run, "graph.json", graph.diff);
114
+ writeRunJson(run, "check.json", graph.check);
115
+ return { scope, run, graph };
116
+ }
117
+ async function runCheck(args) {
118
+ const root = canonical(repoRoot(args.cwd));
119
+ const contract = args.contract ? loadContract(root, canonical(resolve(args.cwd, args.contract))) : loadContract(root);
120
+ if (args.contract && !contract) throw new Error(`contract not found: ${args.contract}`);
121
+ const graph = await buildGraph(root);
122
+ const result = checkContract(graph, contract ?? emptyContract(), {
123
+ root,
124
+ runSemgrep: args.semgrep,
125
+ allowCustomChecks: args.allowCustomChecks
126
+ });
127
+ const run = currentRun(root);
128
+ writeRunJson(run, "check.json", result);
129
+ return { result, run, hasContract: contract !== null };
130
+ }
131
+ function runProve(args) {
132
+ const root = canonical(repoRoot(args.cwd));
133
+ const test = canonical(resolve(args.cwd, args.test));
134
+ const ref = relative(root, test).replaceAll("\\", "/");
135
+ if (!ref.startsWith(".plumbline/proofs/")) throw new Error("proof tests must live under .plumbline/proofs/");
136
+ if (!existsSync(test)) throw new Error(`test not found: ${args.test}`);
137
+ if (args.command.length === 0) throw new Error("pass the test command after --");
138
+ const options = { cwd: root, encoding: "utf8", timeout: 5 * 60 * 1e3, maxBuffer: 16 * 1024 * 1024, windowsHide: true };
139
+ const quote = (a) => /^[\w@%+=:,./\\-]+$/.test(a) ? a : `"${a.replace(/"/g, '""')}"`;
140
+ const [cmd, ...rest] = args.command;
141
+ const result = process.platform === "win32" ? spawnSync(args.command.map(quote).join(" "), { ...options, shell: true }) : spawnSync(cmd, rest, options);
142
+ const output = `${result.stdout ?? ""}${result.stderr ?? ""}`;
143
+ const record = {
144
+ ref,
145
+ sha256: hashFile(test),
146
+ headSha: resolveHead(root),
147
+ command: args.command.join(" "),
148
+ exitCode: result.status ?? 1,
149
+ output: output.length > OUTPUT_LIMIT ? output.slice(-OUTPUT_LIMIT) : output,
150
+ ...args.passedOnBase === void 0 ? {} : { passedOnBase: args.passedOnBase },
151
+ recordedAt: (/* @__PURE__ */ new Date()).toISOString()
152
+ };
153
+ const run = findRun(root, args.run) ?? createRun(root);
154
+ const prior = readRunJson(run, "proofs.json") ?? [];
155
+ writeRunJson(run, "proofs.json", [...prior.filter((p) => p.ref !== ref), record]);
156
+ return record;
157
+ }
158
+ function resolveHead(root) {
159
+ const result = spawnSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8", windowsHide: true });
160
+ return result.stdout.trim();
161
+ }
162
+ async function runReport(args) {
163
+ const root = repoRoot(args.cwd);
164
+ const found = findRun(root, args.run);
165
+ if (args.run && !found) throw new Error(`run not found: ${args.run}`);
166
+ const run = found ?? createRun(root);
167
+ const meta = readRunJson(run, "run.json");
168
+ const scope = resolveScope({ cwd: root, target: meta?.target, base: args.base ?? meta?.base });
169
+ const contract = contractFor(scope, args.contractFrom ?? "head");
170
+ const graph = await runDeterministic(scope, contract);
171
+ writeRunJson(run, "scope.json", scope);
172
+ writeRunJson(run, "graph.json", graph.diff);
173
+ writeRunJson(run, "check.json", graph.check);
174
+ let modelFile = args.findingsValue;
175
+ if (modelFile === void 0 && args.findings) modelFile = JSON.parse(readFileSync(resolve(args.cwd, args.findings), "utf8"));
176
+ if (modelFile === void 0) modelFile = readRunJson(run, "findings.json") ?? void 0;
177
+ if (modelFile !== void 0) writeRunJson(run, "findings.json", modelFile);
178
+ const lenses = listLenses(root);
179
+ const report = finalizeReport({
180
+ runId: run.id,
181
+ startedAt: new Date(meta?.startedAt ?? Date.now()),
182
+ version: VERSION,
183
+ scope,
184
+ contract,
185
+ graph,
186
+ modelFile,
187
+ recordedProofs: readRunJson(run, "proofs.json") ?? [],
188
+ baseBranch: args.baseBranch,
189
+ useGate: args.useGate,
190
+ useLane: args.useLane,
191
+ lenses
192
+ });
193
+ const paths = writeReport(run, report, lenses);
194
+ return { report, run, paths };
195
+ }
196
+ var IGNORED_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "out", "coverage", "vendor", "test", "tests", "__tests__", "__mocks__", "fixtures", "public", "assets", "static", "types"]);
197
+ function subdirs(dir) {
198
+ if (!existsSync(dir)) return [];
199
+ return readdirSync(dir).filter((n) => !n.startsWith(".") && !IGNORED_DIRS.has(n) && statSync(join(dir, n)).isDirectory()).sort();
200
+ }
201
+ function guessModules(root) {
202
+ const out = {};
203
+ for (const parent of ["src", "lib", "app"]) {
204
+ for (const name of subdirs(join(root, parent))) out[name] ??= `${parent}/${name}/**`;
205
+ }
206
+ for (const parent of ["packages", "apps", "services"]) {
207
+ for (const name of subdirs(join(root, parent))) out[name] ??= `${parent}/${name}/**`;
208
+ }
209
+ return out;
210
+ }
211
+ function renderSkeleton(modules) {
212
+ const names = Object.keys(modules);
213
+ const width = Math.max(0, ...names.map((n) => yamlKey(n).length));
214
+ const moduleLines = names.length > 0 ? names.map((n) => ` ${`${yamlKey(n)}:`.padEnd(width + 2)}["${modules[n]}"]`).join("\n") : ' # app: ["src/app/**"]';
215
+ return `# Plumbline architecture contract. Docs: https://tanzir71.github.io/plumbline/docs/contract/
216
+ version: 1
217
+
218
+ # Module name -> globs. These were guessed from your folders, so check them.
219
+ modules:${names.length > 0 ? "" : " {}"}
220
+ ${moduleLines}
221
+
222
+ # Top to bottom. A lower layer may not import a higher one.
223
+ # layers:
224
+ # - [api]
225
+ # - [billing, orgs]
226
+ # - [db]
227
+
228
+ # Rules Plumbline can prove, plus judgement calls for the model.
229
+ # rules:
230
+ # - id: no-billing-to-orgs
231
+ # forbid: billing -> orgs
232
+ # because: "ADR-012: billing ships on its own"
233
+ # - id: tenant-scope
234
+ # require: "repository methods scope queries by org_id"
235
+ # check: llm
236
+ # paths: ["src/**/repo/**"]
237
+
238
+ proof:
239
+ P0: [failing_test, graph_diff]
240
+ P1: [failing_test, graph_diff, broken_rule]
241
+
242
+ # Fail the CI job when the merge score is below the minimum.
243
+ # gate:
244
+ # - branches: ["main", "release/*"]
245
+ # min_merge_score: 3
246
+
247
+ # Label low-risk PRs. A lane never approves or merges.
248
+ lanes:
249
+ light:
250
+ label: "plumbline:light-review"
251
+ when: { merge_score: 5, max_severity: P3, max_changed_lines: 200 }
252
+ never: ["**/migrations/**", ".github/**"]
253
+ `;
254
+ }
255
+ var yamlKey = (name) => /^[\w/-]+$/.test(name) ? name : JSON.stringify(name);
256
+ function runInit(cwd, force = false) {
257
+ const root = repoRoot(cwd);
258
+ const file = join(root, CONTRACT_FILE);
259
+ if (existsSync(file) && !force) throw new Error(`${CONTRACT_FILE} already exists (use --force to replace it)`);
260
+ const modules = guessModules(root);
261
+ const content = renderSkeleton(modules);
262
+ parseContract(content);
263
+ writeFileSync(file, content);
264
+ return { file, modules: Object.keys(modules), content };
265
+ }
266
+
267
+ export {
268
+ VERSION,
269
+ lensDir,
270
+ listLenses,
271
+ startScope,
272
+ contractFor,
273
+ runGraph,
274
+ runCheck,
275
+ runProve,
276
+ runReport,
277
+ guessModules,
278
+ renderSkeleton,
279
+ runInit
280
+ };
281
+ //# sourceMappingURL=chunk-UUYJFDRT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib.ts","../package.json"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n CONTRACT_FILE,\n buildGraph,\n checkContract,\n contractAt,\n createRun,\n currentRun,\n emptyContract,\n finalizeReport,\n findRun,\n hashFile,\n loadContract,\n loadLenses,\n parseContract,\n readRunJson,\n repoRoot,\n resolveScope,\n runDeterministic,\n writeReport,\n writeRunJson,\n type CheckResult,\n type Contract,\n type GraphRun,\n type Lens,\n type RecordedProof,\n type ReportV1,\n type RunDir,\n type ScopeResult,\n} from \"@tanziro/plumbline-core\";\nimport pkg from \"../package.json\" with { type: \"json\" };\n\nexport const VERSION: string = pkg.version;\n\nconst OUTPUT_LIMIT = 8000;\n\n/**\n * git reports a repo's real path, but the working directory can reach it another way: a symlink,\n * a junction, or a Windows 8.3 short name. Compare real paths so those don't look like different folders.\n */\nconst canonical = (path: string) => (existsSync(path) ? realpathSync.native(path) : path);\n\nexport function lensDir(): string {\n const here = dirname(fileURLToPath(import.meta.url));\n const shipped = join(here, \"..\", \"lenses\");\n return existsSync(shipped) ? shipped : join(here, \"..\", \"..\", \"..\", \"skills\", \"plumbline\", \"lenses\");\n}\n\nexport function listLenses(root?: string): Lens[] {\n return loadLenses(lensDir(), root);\n}\n\ninterface RunMeta {\n startedAt: string;\n target?: string;\n base?: string;\n}\n\nexport interface ScopeArgs {\n cwd: string;\n target?: string;\n base?: string;\n}\n\n/** Pin the scope and start a new run directory. */\nexport function startScope(args: ScopeArgs): { scope: ScopeResult; run: RunDir } {\n const scope = resolveScope(args);\n const run = createRun(scope.repo);\n const meta: RunMeta = { startedAt: new Date().toISOString(), target: args.target, base: args.base };\n writeRunJson(run, \"run.json\", meta);\n writeRunJson(run, \"scope.json\", scope);\n return { scope, run };\n}\n\n/** Which contract judges this run. CI passes \"base\" so a PR cannot relax its own rules. */\nexport function contractFor(scope: ScopeResult, source: \"head\" | \"base\"): Contract {\n return contractAt(scope.repo, source === \"base\" ? scope.mergeBase : null);\n}\n\nexport interface GraphArgs extends ScopeArgs {\n contractFrom?: \"head\" | \"base\";\n}\n\n/** Reuse the latest run when it covers the same commits and has no report yet, so one review stays in one directory. */\nfunction continueOrStart(args: ScopeArgs): { scope: ScopeResult; run: RunDir } {\n const scope = resolveScope(args);\n const latest = findRun(scope.repo);\n if (latest && !existsSync(join(latest.dir, \"report.json\"))) {\n const prior = readRunJson<ScopeResult>(latest, \"scope.json\");\n if (prior?.headSha === scope.headSha && prior.mergeBase === scope.mergeBase && prior.mode === scope.mode) {\n writeRunJson(latest, \"scope.json\", scope);\n return { scope, run: latest };\n }\n }\n return startScope(args);\n}\n\nexport async function runGraph(args: GraphArgs): Promise<{ scope: ScopeResult; run: RunDir; graph: GraphRun }> {\n const { scope, run } = continueOrStart(args);\n const graph = await runDeterministic(scope, contractFor(scope, args.contractFrom ?? \"head\"));\n writeRunJson(run, \"graph.json\", graph.diff);\n writeRunJson(run, \"check.json\", graph.check);\n return { scope, run, graph };\n}\n\nexport interface CheckArgs {\n cwd: string;\n semgrep?: boolean;\n allowCustomChecks?: boolean;\n /** Check a draft contract at this path instead of `plumbline.yml`. */\n contract?: string;\n}\n\n/** Evaluate the contract against the current tree. Needs no base branch. */\nexport async function runCheck(args: CheckArgs): Promise<{ result: CheckResult; run: RunDir; hasContract: boolean }> {\n const root = canonical(repoRoot(args.cwd));\n const contract = args.contract ? loadContract(root, canonical(resolve(args.cwd, args.contract))) : loadContract(root);\n if (args.contract && !contract) throw new Error(`contract not found: ${args.contract}`);\n const graph = await buildGraph(root);\n const result = checkContract(graph, contract ?? emptyContract(), {\n root,\n runSemgrep: args.semgrep,\n allowCustomChecks: args.allowCustomChecks,\n });\n const run = currentRun(root);\n writeRunJson(run, \"check.json\", result);\n return { result, run, hasContract: contract !== null };\n}\n\nexport interface ProveArgs {\n cwd: string;\n test: string;\n command: string[];\n run?: string;\n /** Set after running the same test on the base commit. */\n passedOnBase?: boolean;\n}\n\n/** Run a proof test and record what actually happened. Only these records satisfy the proof gate. */\nexport function runProve(args: ProveArgs): RecordedProof {\n const root = canonical(repoRoot(args.cwd));\n const test = canonical(resolve(args.cwd, args.test));\n const ref = relative(root, test).replaceAll(\"\\\\\", \"/\");\n if (!ref.startsWith(\".plumbline/proofs/\")) throw new Error(\"proof tests must live under .plumbline/proofs/\");\n if (!existsSync(test)) throw new Error(`test not found: ${args.test}`);\n if (args.command.length === 0) throw new Error(\"pass the test command after --\");\n\n const options = { cwd: root, encoding: \"utf8\", timeout: 5 * 60 * 1000, maxBuffer: 16 * 1024 * 1024, windowsHide: true } as const;\n // Windows needs a shell to run .cmd shims such as npm and pnpm, so quote the arguments for it.\n const quote = (a: string) => (/^[\\w@%+=:,./\\\\-]+$/.test(a) ? a : `\"${a.replace(/\"/g, '\"\"')}\"`);\n const [cmd, ...rest] = args.command as [string, ...string[]];\n const result =\n process.platform === \"win32\"\n ? spawnSync(args.command.map(quote).join(\" \"), { ...options, shell: true })\n : spawnSync(cmd, rest, options);\n const output = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`;\n const record: RecordedProof = {\n ref,\n sha256: hashFile(test),\n headSha: resolveHead(root),\n command: args.command.join(\" \"),\n exitCode: result.status ?? 1,\n output: output.length > OUTPUT_LIMIT ? output.slice(-OUTPUT_LIMIT) : output,\n ...(args.passedOnBase === undefined ? {} : { passedOnBase: args.passedOnBase }),\n recordedAt: new Date().toISOString(),\n };\n\n const run = findRun(root, args.run) ?? createRun(root);\n const prior = readRunJson<RecordedProof[]>(run, \"proofs.json\") ?? [];\n writeRunJson(run, \"proofs.json\", [...prior.filter((p) => p.ref !== ref), record]);\n return record;\n}\n\nfunction resolveHead(root: string): string {\n const result = spawnSync(\"git\", [\"rev-parse\", \"HEAD\"], { cwd: root, encoding: \"utf8\", windowsHide: true });\n return result.stdout.trim();\n}\n\nexport interface ReportArgs {\n cwd: string;\n run?: string;\n findings?: string;\n /** Inline findings, used by the MCP tool. */\n findingsValue?: unknown;\n base?: string;\n baseBranch?: string;\n contractFrom?: \"head\" | \"base\";\n useGate?: boolean;\n useLane?: boolean;\n}\n\nexport interface ReportOutput {\n report: ReportV1;\n run: RunDir;\n paths: Record<string, string>;\n}\n\n/**\n * Finalize a run. The scope and graph are recomputed here instead of read from the run directory,\n * so the proof gate checks model findings against the repository, not against editable files.\n */\nexport async function runReport(args: ReportArgs): Promise<ReportOutput> {\n const root = repoRoot(args.cwd);\n const found = findRun(root, args.run);\n if (args.run && !found) throw new Error(`run not found: ${args.run}`);\n const run = found ?? createRun(root);\n\n const meta = readRunJson<RunMeta>(run, \"run.json\");\n const scope = resolveScope({ cwd: root, target: meta?.target, base: args.base ?? meta?.base });\n const contract = contractFor(scope, args.contractFrom ?? \"head\");\n const graph = await runDeterministic(scope, contract);\n writeRunJson(run, \"scope.json\", scope);\n writeRunJson(run, \"graph.json\", graph.diff);\n writeRunJson(run, \"check.json\", graph.check);\n\n let modelFile: unknown = args.findingsValue;\n if (modelFile === undefined && args.findings) modelFile = JSON.parse(readFileSync(resolve(args.cwd, args.findings), \"utf8\"));\n if (modelFile === undefined) modelFile = readRunJson<unknown>(run, \"findings.json\") ?? undefined;\n if (modelFile !== undefined) writeRunJson(run, \"findings.json\", modelFile);\n\n const lenses = listLenses(root);\n const report = finalizeReport({\n runId: run.id,\n startedAt: new Date(meta?.startedAt ?? Date.now()),\n version: VERSION,\n scope,\n contract,\n graph,\n modelFile,\n recordedProofs: readRunJson<RecordedProof[]>(run, \"proofs.json\") ?? [],\n baseBranch: args.baseBranch,\n useGate: args.useGate,\n useLane: args.useLane,\n lenses,\n });\n const paths = writeReport(run, report, lenses);\n return { report, run, paths };\n}\n\nconst IGNORED_DIRS = new Set([\"node_modules\", \"dist\", \"build\", \"out\", \"coverage\", \"vendor\", \"test\", \"tests\", \"__tests__\", \"__mocks__\", \"fixtures\", \"public\", \"assets\", \"static\", \"types\"]);\n\nfunction subdirs(dir: string): string[] {\n if (!existsSync(dir)) return [];\n return readdirSync(dir)\n .filter((n) => !n.startsWith(\".\") && !IGNORED_DIRS.has(n) && statSync(join(dir, n)).isDirectory())\n .sort();\n}\n\n/** Guess modules from the folder structure. */\nexport function guessModules(root: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const parent of [\"src\", \"lib\", \"app\"]) {\n for (const name of subdirs(join(root, parent))) out[name] ??= `${parent}/${name}/**`;\n }\n for (const parent of [\"packages\", \"apps\", \"services\"]) {\n for (const name of subdirs(join(root, parent))) out[name] ??= `${parent}/${name}/**`;\n }\n return out;\n}\n\nexport function renderSkeleton(modules: Record<string, string>): string {\n const names = Object.keys(modules);\n const width = Math.max(0, ...names.map((n) => yamlKey(n).length));\n const moduleLines =\n names.length > 0\n ? names.map((n) => ` ${`${yamlKey(n)}:`.padEnd(width + 2)}[\"${modules[n]}\"]`).join(\"\\n\")\n : ' # app: [\"src/app/**\"]';\n return `# Plumbline architecture contract. Docs: https://tanzir71.github.io/plumbline/docs/contract/\nversion: 1\n\n# Module name -> globs. These were guessed from your folders, so check them.\nmodules:${names.length > 0 ? \"\" : \" {}\"}\n${moduleLines}\n\n# Top to bottom. A lower layer may not import a higher one.\n# layers:\n# - [api]\n# - [billing, orgs]\n# - [db]\n\n# Rules Plumbline can prove, plus judgement calls for the model.\n# rules:\n# - id: no-billing-to-orgs\n# forbid: billing -> orgs\n# because: \"ADR-012: billing ships on its own\"\n# - id: tenant-scope\n# require: \"repository methods scope queries by org_id\"\n# check: llm\n# paths: [\"src/**/repo/**\"]\n\nproof:\n P0: [failing_test, graph_diff]\n P1: [failing_test, graph_diff, broken_rule]\n\n# Fail the CI job when the merge score is below the minimum.\n# gate:\n# - branches: [\"main\", \"release/*\"]\n# min_merge_score: 3\n\n# Label low-risk PRs. A lane never approves or merges.\nlanes:\n light:\n label: \"plumbline:light-review\"\n when: { merge_score: 5, max_severity: P3, max_changed_lines: 200 }\n never: [\"**/migrations/**\", \".github/**\"]\n`;\n}\n\nconst yamlKey = (name: string) => (/^[\\w/-]+$/.test(name) ? name : JSON.stringify(name));\n\nexport function runInit(cwd: string, force = false): { file: string; modules: string[]; content: string } {\n const root = repoRoot(cwd);\n const file = join(root, CONTRACT_FILE);\n if (existsSync(file) && !force) throw new Error(`${CONTRACT_FILE} already exists (use --force to replace it)`);\n const modules = guessModules(root);\n const content = renderSkeleton(modules);\n parseContract(content);\n writeFileSync(file, content);\n return { file, modules: Object.keys(modules), content };\n}\n","{\n \"name\": \"@tanziro/plumbline\",\n \"version\": \"1.0.0\",\n \"description\": \"Plumbline CLI and MCP server: scope, import graph diff, contract checks and reports.\",\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/tanzir71/plumbline.git\",\n \"directory\": \"packages/cli\"\n },\n \"homepage\": \"https://tanzir71.github.io/plumbline/\",\n \"engines\": {\n \"node\": \">=20.12.0\"\n },\n \"bin\": {\n \"plumbline\": \"./bin/plumbline.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/lib.d.ts\",\n \"import\": \"./dist/lib.js\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"bin\",\n \"dist\",\n \"lenses\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"tsup && node ../../scripts/copy-lenses.mjs\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc --noEmit\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/sdk\": \"^1.32.2\",\n \"@tanziro/plumbline-core\": \"workspace:^\",\n \"yaml\": \"^2.9.1\",\n \"zod\": \"^4.6.7\"\n }\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,YAAY,aAAa,cAAc,cAAc,UAAU,qBAAqB;AAC7F,SAA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AAE/E,SAAS,QAAQ,KAAa,QAAQ,OAA6D;AACxG,QAAM,OAAO,SAAS,GAAG;AACzB,QAAM,OAAO,KAAK,MAAM,aAAa;AACrC,MAAI,WAAW,IAAI,KAAK,CAAC,MAAO,OAAM,IAAI,MAAM,GAAG,aAAa,6CAA6C;AAC7G,QAAM,UAAU,aAAa,IAAI;AACjC,QAAM,UAAU,eAAe,OAAO;AACtC,gBAAc,OAAO;AACrB,gBAAc,MAAM,OAAO;AAC3B,SAAO,EAAE,MAAM,SAAS,OAAO,KAAK,OAAO,GAAG,QAAQ;AACxD;","names":[]}
package/dist/index.js ADDED
@@ -0,0 +1,214 @@
1
+ import {
2
+ VERSION,
3
+ runCheck,
4
+ runGraph,
5
+ runInit,
6
+ runProve,
7
+ runReport,
8
+ startScope
9
+ } from "./chunk-UUYJFDRT.js";
10
+
11
+ // src/index.ts
12
+ import { parseArgs } from "util";
13
+ import { ContractError, NothingToReviewError, formatCounts, formatCycle, formatScope, renderMarkdown } from "@tanziro/plumbline-core";
14
+ var HELP = `plumbline ${VERSION}: review the structure, not just the diff.
15
+
16
+ Usage: plumbline <command> [options]
17
+
18
+ Commands
19
+ init Write a plumbline.yml skeleton, guessing modules from folders
20
+ scope [target] Pin the diff range and collect rule files. Target: branch, commit or PR
21
+ graph Diff the JS/TS import graph between base and HEAD
22
+ check Check the contract's forbid and layer rules against the current tree
23
+ prove <test> -- <cmd> Run a proof test under .plumbline/proofs/ and record the result
24
+ report Apply the proof gate, score the run and write the audit trail
25
+ mcp Start the MCP server on stdio
26
+
27
+ Options
28
+ --base <ref> Base branch or ref (default: dev, then main, then master)
29
+ --json Machine-readable output
30
+ --help, --version
31
+
32
+ check --contract <file> --semgrep --allow-custom-checks
33
+ report --gate --run <id> --findings <file> --base-branch <name> --contract-from <head|base>
34
+ prove --run <id> --passed-on-base --failed-on-base
35
+ init --force
36
+
37
+ Exit codes: 0 ok \xB7 1 error, gate failed or rule violated \xB7 2 nothing to review
38
+ `;
39
+ function print(json, value, human) {
40
+ process.stdout.write(`${json ? JSON.stringify(value, null, 2) : human()}
41
+ `);
42
+ }
43
+ var contractFrom = (v) => {
44
+ if (v === void 0 || v === "head" || v === "base") return v;
45
+ throw new Error(`--contract-from must be head or base, not "${v}"`);
46
+ };
47
+ async function main(argv) {
48
+ const [command, ...rest] = argv;
49
+ if (!command || command === "--help" || command === "-h" || command === "help") {
50
+ process.stdout.write(HELP);
51
+ return 0;
52
+ }
53
+ if (command === "--version" || command === "-v") {
54
+ process.stdout.write(`${VERSION}
55
+ `);
56
+ return 0;
57
+ }
58
+ const split = rest.indexOf("--");
59
+ const args = split === -1 ? rest : rest.slice(0, split);
60
+ const passthrough = split === -1 ? [] : rest.slice(split + 1);
61
+ if (args.includes("--help") || args.includes("-h")) {
62
+ process.stdout.write(HELP);
63
+ return 0;
64
+ }
65
+ const { values, positionals } = parseArgs({
66
+ args,
67
+ allowPositionals: true,
68
+ options: {
69
+ base: { type: "string" },
70
+ json: { type: "boolean", default: false },
71
+ force: { type: "boolean", default: false },
72
+ gate: { type: "boolean", default: false },
73
+ run: { type: "string" },
74
+ findings: { type: "string" },
75
+ "base-branch": { type: "string" },
76
+ "contract-from": { type: "string" },
77
+ contract: { type: "string" },
78
+ semgrep: { type: "boolean", default: false },
79
+ "allow-custom-checks": { type: "boolean", default: false },
80
+ "passed-on-base": { type: "boolean", default: false },
81
+ "failed-on-base": { type: "boolean", default: false }
82
+ }
83
+ });
84
+ const cwd = process.cwd();
85
+ const json = values.json;
86
+ switch (command) {
87
+ case "init": {
88
+ const out = runInit(cwd, values.force);
89
+ print(
90
+ json,
91
+ { file: out.file, modules: out.modules },
92
+ () => [`Wrote ${out.file}`, out.modules.length ? `Guessed modules: ${out.modules.join(", ")}` : "No modules guessed. Add them by hand."].join("\n")
93
+ );
94
+ return 0;
95
+ }
96
+ case "scope": {
97
+ const { scope, run } = startScope({ cwd, target: positionals[0], base: values.base });
98
+ print(json, { runId: run.id, ...scope }, () => `${formatScope(scope)}
99
+ RUN: ${run.id}`);
100
+ return 0;
101
+ }
102
+ case "graph": {
103
+ const { run, graph } = await runGraph({ cwd, base: values.base, contractFrom: contractFrom(values["contract-from"]) });
104
+ const d = graph.diff;
105
+ print(
106
+ json,
107
+ { runId: run.id, diff: d, violations: graph.check.violations },
108
+ () => [
109
+ `Import graph: ${d.stats.baseFiles} -> ${d.stats.headFiles} files, ${d.stats.baseEdges} -> ${d.stats.headEdges} edges`,
110
+ `Added edges (${d.added.length})`,
111
+ ...d.added.map((e) => ` + ${e.from} -> ${e.to}${e.typeOnly ? " (type-only)" : ""}`),
112
+ `Removed edges (${d.removed.length})`,
113
+ ...d.removed.map((e) => ` - ${e.from} -> ${e.to}`),
114
+ `New cycles (${d.newCycles.length})`,
115
+ ...d.newCycles.map((c) => ` ${c.level}: ${formatCycle(c)}`),
116
+ `Layer crossings (${d.layerCrossings.length})`,
117
+ ...d.layerCrossings.map((c) => ` ${c.violation ? "VIOLATION " : ""}${c.fromModule} -> ${c.toModule} (${c.from} -> ${c.to})`),
118
+ `Run: ${run.id}`
119
+ ].join("\n")
120
+ );
121
+ return 0;
122
+ }
123
+ case "check": {
124
+ const { result, run, hasContract } = await runCheck({
125
+ cwd,
126
+ contract: values.contract,
127
+ semgrep: values.semgrep,
128
+ allowCustomChecks: values["allow-custom-checks"]
129
+ });
130
+ print(
131
+ json,
132
+ { runId: run.id, hasContract, ...result },
133
+ () => [
134
+ hasContract ? `Contract: ${result.violations.length} violations` : "No plumbline.yml found. Run: plumbline init",
135
+ ...result.violations.map((v) => ` ${v.ruleId}: ${v.from} -> ${v.to}
136
+ ${v.message}${v.because ? ` (${v.because})` : ""}`),
137
+ ...result.cycles.length ? [`Cycles (${result.cycles.length})`, ...result.cycles.map((c) => ` ${c.level}: ${formatCycle(c)}`)] : [],
138
+ ...result.llmRules.length ? [`Judgement rules for the model: ${result.llmRules.map((r) => r.id).join(", ")}`] : [],
139
+ ...result.skippedRules.map((r) => `Skipped ${r.id}: ${r.reason}`)
140
+ ].join("\n")
141
+ );
142
+ return result.violations.length > 0 ? 1 : 0;
143
+ }
144
+ case "prove": {
145
+ const test = positionals[0];
146
+ if (!test) throw new Error("usage: plumbline prove <test> -- <command>");
147
+ const passedOnBase = values["passed-on-base"] ? true : values["failed-on-base"] ? false : void 0;
148
+ const record = runProve({ cwd, test, command: passthrough, run: values.run, passedOnBase });
149
+ print(
150
+ json,
151
+ record,
152
+ () => record.exitCode === 0 ? `Test passed on HEAD, so it proves nothing: ${record.ref}` : `Recorded failing test: ${record.ref} (exit ${record.exitCode})`
153
+ );
154
+ return 0;
155
+ }
156
+ case "report": {
157
+ const out = await runReport({
158
+ cwd,
159
+ run: values.run,
160
+ findings: values.findings,
161
+ base: values.base,
162
+ baseBranch: values["base-branch"],
163
+ contractFrom: contractFrom(values["contract-from"])
164
+ });
165
+ const { report } = out;
166
+ print(
167
+ json,
168
+ report,
169
+ () => [
170
+ renderMarkdown(report).trimEnd(),
171
+ "",
172
+ `Merge score ${report.score.value}/5 (${formatCounts(report.score.counts)})`,
173
+ `Audit trail: ${out.run.dir}`
174
+ ].join("\n")
175
+ );
176
+ if (values.gate && report.gate && !report.gate.pass) {
177
+ process.stderr.write(`plumbline: ${report.gate.reason}
178
+ `);
179
+ return 1;
180
+ }
181
+ return 0;
182
+ }
183
+ case "mcp": {
184
+ const { serveStdio } = await import("./mcp-XABJTEWQ.js");
185
+ await serveStdio();
186
+ return -1;
187
+ }
188
+ default:
189
+ process.stderr.write(`plumbline: unknown command "${command}"
190
+
191
+ ${HELP}`);
192
+ return 1;
193
+ }
194
+ }
195
+ main(process.argv.slice(2)).then((code) => {
196
+ if (code >= 0) process.exitCode = code;
197
+ }).catch((error) => {
198
+ if (error instanceof NothingToReviewError) {
199
+ process.stdout.write(`NOTHING TO REVIEW: ${error.message}
200
+ `);
201
+ process.exitCode = 2;
202
+ return;
203
+ }
204
+ if (error instanceof ContractError) {
205
+ process.stderr.write(`plumbline: invalid contract
206
+ ${error.message}
207
+ `);
208
+ } else {
209
+ process.stderr.write(`plumbline: ${error instanceof Error ? error.message : String(error)}
210
+ `);
211
+ }
212
+ process.exitCode = 1;
213
+ });
214
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { parseArgs } from \"node:util\";\nimport { ContractError, NothingToReviewError, formatCounts, formatCycle, formatScope, renderMarkdown } from \"@tanziro/plumbline-core\";\nimport { VERSION, runCheck, runGraph, runInit, runProve, runReport, startScope } from \"./lib.js\";\n\nconst HELP = `plumbline ${VERSION}: review the structure, not just the diff.\n\nUsage: plumbline <command> [options]\n\nCommands\n init Write a plumbline.yml skeleton, guessing modules from folders\n scope [target] Pin the diff range and collect rule files. Target: branch, commit or PR\n graph Diff the JS/TS import graph between base and HEAD\n check Check the contract's forbid and layer rules against the current tree\n prove <test> -- <cmd> Run a proof test under .plumbline/proofs/ and record the result\n report Apply the proof gate, score the run and write the audit trail\n mcp Start the MCP server on stdio\n\nOptions\n --base <ref> Base branch or ref (default: dev, then main, then master)\n --json Machine-readable output\n --help, --version\n\ncheck --contract <file> --semgrep --allow-custom-checks\nreport --gate --run <id> --findings <file> --base-branch <name> --contract-from <head|base>\nprove --run <id> --passed-on-base --failed-on-base\ninit --force\n\nExit codes: 0 ok · 1 error, gate failed or rule violated · 2 nothing to review\n`;\n\nfunction print(json: boolean, value: unknown, human: () => string): void {\n process.stdout.write(`${json ? JSON.stringify(value, null, 2) : human()}\\n`);\n}\n\nconst contractFrom = (v: string | undefined): \"head\" | \"base\" | undefined => {\n if (v === undefined || v === \"head\" || v === \"base\") return v;\n throw new Error(`--contract-from must be head or base, not \"${v}\"`);\n};\n\nasync function main(argv: string[]): Promise<number> {\n const [command, ...rest] = argv;\n if (!command || command === \"--help\" || command === \"-h\" || command === \"help\") {\n process.stdout.write(HELP);\n return 0;\n }\n if (command === \"--version\" || command === \"-v\") {\n process.stdout.write(`${VERSION}\\n`);\n return 0;\n }\n\n // Everything after `--` belongs to the proof test command.\n const split = rest.indexOf(\"--\");\n const args = split === -1 ? rest : rest.slice(0, split);\n const passthrough = split === -1 ? [] : rest.slice(split + 1);\n\n if (args.includes(\"--help\") || args.includes(\"-h\")) {\n process.stdout.write(HELP);\n return 0;\n }\n\n const { values, positionals } = parseArgs({\n args,\n allowPositionals: true,\n options: {\n base: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n force: { type: \"boolean\", default: false },\n gate: { type: \"boolean\", default: false },\n run: { type: \"string\" },\n findings: { type: \"string\" },\n \"base-branch\": { type: \"string\" },\n \"contract-from\": { type: \"string\" },\n contract: { type: \"string\" },\n semgrep: { type: \"boolean\", default: false },\n \"allow-custom-checks\": { type: \"boolean\", default: false },\n \"passed-on-base\": { type: \"boolean\", default: false },\n \"failed-on-base\": { type: \"boolean\", default: false },\n },\n });\n const cwd = process.cwd();\n const json = values.json as boolean;\n\n switch (command) {\n case \"init\": {\n const out = runInit(cwd, values.force as boolean);\n print(json, { file: out.file, modules: out.modules }, () =>\n [`Wrote ${out.file}`, out.modules.length ? `Guessed modules: ${out.modules.join(\", \")}` : \"No modules guessed. Add them by hand.\"].join(\"\\n\"),\n );\n return 0;\n }\n\n case \"scope\": {\n const { scope, run } = startScope({ cwd, target: positionals[0], base: values.base });\n print(json, { runId: run.id, ...scope }, () => `${formatScope(scope)}\\nRUN: ${run.id}`);\n return 0;\n }\n\n case \"graph\": {\n const { run, graph } = await runGraph({ cwd, base: values.base, contractFrom: contractFrom(values[\"contract-from\"]) });\n const d = graph.diff;\n print(json, { runId: run.id, diff: d, violations: graph.check.violations }, () =>\n [\n `Import graph: ${d.stats.baseFiles} -> ${d.stats.headFiles} files, ${d.stats.baseEdges} -> ${d.stats.headEdges} edges`,\n `Added edges (${d.added.length})`,\n ...d.added.map((e) => ` + ${e.from} -> ${e.to}${e.typeOnly ? \" (type-only)\" : \"\"}`),\n `Removed edges (${d.removed.length})`,\n ...d.removed.map((e) => ` - ${e.from} -> ${e.to}`),\n `New cycles (${d.newCycles.length})`,\n ...d.newCycles.map((c) => ` ${c.level}: ${formatCycle(c)}`),\n `Layer crossings (${d.layerCrossings.length})`,\n ...d.layerCrossings.map((c) => ` ${c.violation ? \"VIOLATION \" : \"\"}${c.fromModule} -> ${c.toModule} (${c.from} -> ${c.to})`),\n `Run: ${run.id}`,\n ].join(\"\\n\"),\n );\n return 0;\n }\n\n case \"check\": {\n const { result, run, hasContract } = await runCheck({\n cwd,\n contract: values.contract,\n semgrep: values.semgrep as boolean,\n allowCustomChecks: values[\"allow-custom-checks\"] as boolean,\n });\n print(json, { runId: run.id, hasContract, ...result }, () =>\n [\n hasContract ? `Contract: ${result.violations.length} violations` : \"No plumbline.yml found. Run: plumbline init\",\n ...result.violations.map((v) => ` ${v.ruleId}: ${v.from} -> ${v.to}\\n ${v.message}${v.because ? ` (${v.because})` : \"\"}`),\n ...(result.cycles.length ? [`Cycles (${result.cycles.length})`, ...result.cycles.map((c) => ` ${c.level}: ${formatCycle(c)}`)] : []),\n ...(result.llmRules.length ? [`Judgement rules for the model: ${result.llmRules.map((r) => r.id).join(\", \")}`] : []),\n ...result.skippedRules.map((r) => `Skipped ${r.id}: ${r.reason}`),\n ].join(\"\\n\"),\n );\n return result.violations.length > 0 ? 1 : 0;\n }\n\n case \"prove\": {\n const test = positionals[0];\n if (!test) throw new Error(\"usage: plumbline prove <test> -- <command>\");\n const passedOnBase = values[\"passed-on-base\"] ? true : values[\"failed-on-base\"] ? false : undefined;\n const record = runProve({ cwd, test, command: passthrough, run: values.run, passedOnBase });\n print(json, record, () =>\n record.exitCode === 0\n ? `Test passed on HEAD, so it proves nothing: ${record.ref}`\n : `Recorded failing test: ${record.ref} (exit ${record.exitCode})`,\n );\n return 0;\n }\n\n case \"report\": {\n const out = await runReport({\n cwd,\n run: values.run,\n findings: values.findings,\n base: values.base,\n baseBranch: values[\"base-branch\"],\n contractFrom: contractFrom(values[\"contract-from\"]),\n });\n const { report } = out;\n print(json, report, () =>\n [\n renderMarkdown(report).trimEnd(),\n \"\",\n `Merge score ${report.score.value}/5 (${formatCounts(report.score.counts)})`,\n `Audit trail: ${out.run.dir}`,\n ].join(\"\\n\"),\n );\n if (values.gate && report.gate && !report.gate.pass) {\n process.stderr.write(`plumbline: ${report.gate.reason}\\n`);\n return 1;\n }\n return 0;\n }\n\n case \"mcp\": {\n const { serveStdio } = await import(\"./mcp.js\");\n await serveStdio();\n return -1;\n }\n\n default:\n process.stderr.write(`plumbline: unknown command \"${command}\"\\n\\n${HELP}`);\n return 1;\n }\n}\n\nmain(process.argv.slice(2))\n .then((code) => {\n if (code >= 0) process.exitCode = code;\n })\n .catch((error: unknown) => {\n if (error instanceof NothingToReviewError) {\n process.stdout.write(`NOTHING TO REVIEW: ${error.message}\\n`);\n process.exitCode = 2;\n return;\n }\n if (error instanceof ContractError) {\n process.stderr.write(`plumbline: invalid contract\\n${error.message}\\n`);\n } else {\n process.stderr.write(`plumbline: ${error instanceof Error ? error.message : String(error)}\\n`);\n }\n process.exitCode = 1;\n });\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,eAAe,sBAAsB,cAAc,aAAa,aAAa,sBAAsB;AAG5G,IAAM,OAAO,aAAa,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0BjC,SAAS,MAAM,MAAe,OAAgB,OAA2B;AACvE,UAAQ,OAAO,MAAM,GAAG,OAAO,KAAK,UAAU,OAAO,MAAM,CAAC,IAAI,MAAM,CAAC;AAAA,CAAI;AAC7E;AAEA,IAAM,eAAe,CAAC,MAAuD;AAC3E,MAAI,MAAM,UAAa,MAAM,UAAU,MAAM,OAAQ,QAAO;AAC5D,QAAM,IAAI,MAAM,8CAA8C,CAAC,GAAG;AACpE;AAEA,eAAe,KAAK,MAAiC;AACnD,QAAM,CAAC,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,MACb;AACA,UAAI,OAAO,QAAQ,OAAO,QAAQ,CAAC,OAAO,KAAK,MAAM;AACnD,gBAAQ,OAAO,MAAM,cAAc,OAAO,KAAK,MAAM;AAAA,CAAI;AACzD,eAAO;AAAA,MACT;AACA,aAAO;AAAA,IACT;AAAA,IAEA,KAAK,OAAO;AACV,YAAM,EAAE,WAAW,IAAI,MAAM,OAAO,mBAAU;AAC9C,YAAM,WAAW;AACjB,aAAO;AAAA,IACT;AAAA,IAEA;AACE,cAAQ,OAAO,MAAM,+BAA+B,OAAO;AAAA;AAAA,EAAQ,IAAI,EAAE;AACzE,aAAO;AAAA,EACX;AACF;AAEA,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,EACvB,KAAK,CAAC,SAAS;AACd,MAAI,QAAQ,EAAG,SAAQ,WAAW;AACpC,CAAC,EACA,MAAM,CAAC,UAAmB;AACzB,MAAI,iBAAiB,sBAAsB;AACzC,YAAQ,OAAO,MAAM,sBAAsB,MAAM,OAAO;AAAA,CAAI;AAC5D,YAAQ,WAAW;AACnB;AAAA,EACF;AACA,MAAI,iBAAiB,eAAe;AAClC,YAAQ,OAAO,MAAM;AAAA,EAAgC,MAAM,OAAO;AAAA,CAAI;AAAA,EACxE,OAAO;AACL,YAAQ,OAAO,MAAM,cAAc,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,CAAI;AAAA,EAC/F;AACA,UAAQ,WAAW;AACrB,CAAC;","names":[]}
package/dist/lib.d.ts ADDED
@@ -0,0 +1,80 @@
1
+ import { ReportV1, RunDir, ScopeResult, Contract, Lens, CheckResult, GraphRun, RecordedProof } from '@tanziro/plumbline-core';
2
+
3
+ declare const VERSION: string;
4
+ declare function lensDir(): string;
5
+ declare function listLenses(root?: string): Lens[];
6
+ interface ScopeArgs {
7
+ cwd: string;
8
+ target?: string;
9
+ base?: string;
10
+ }
11
+ /** Pin the scope and start a new run directory. */
12
+ declare function startScope(args: ScopeArgs): {
13
+ scope: ScopeResult;
14
+ run: RunDir;
15
+ };
16
+ /** Which contract judges this run. CI passes "base" so a PR cannot relax its own rules. */
17
+ declare function contractFor(scope: ScopeResult, source: "head" | "base"): Contract;
18
+ interface GraphArgs extends ScopeArgs {
19
+ contractFrom?: "head" | "base";
20
+ }
21
+ declare function runGraph(args: GraphArgs): Promise<{
22
+ scope: ScopeResult;
23
+ run: RunDir;
24
+ graph: GraphRun;
25
+ }>;
26
+ interface CheckArgs {
27
+ cwd: string;
28
+ semgrep?: boolean;
29
+ allowCustomChecks?: boolean;
30
+ /** Check a draft contract at this path instead of `plumbline.yml`. */
31
+ contract?: string;
32
+ }
33
+ /** Evaluate the contract against the current tree. Needs no base branch. */
34
+ declare function runCheck(args: CheckArgs): Promise<{
35
+ result: CheckResult;
36
+ run: RunDir;
37
+ hasContract: boolean;
38
+ }>;
39
+ interface ProveArgs {
40
+ cwd: string;
41
+ test: string;
42
+ command: string[];
43
+ run?: string;
44
+ /** Set after running the same test on the base commit. */
45
+ passedOnBase?: boolean;
46
+ }
47
+ /** Run a proof test and record what actually happened. Only these records satisfy the proof gate. */
48
+ declare function runProve(args: ProveArgs): RecordedProof;
49
+ interface ReportArgs {
50
+ cwd: string;
51
+ run?: string;
52
+ findings?: string;
53
+ /** Inline findings, used by the MCP tool. */
54
+ findingsValue?: unknown;
55
+ base?: string;
56
+ baseBranch?: string;
57
+ contractFrom?: "head" | "base";
58
+ useGate?: boolean;
59
+ useLane?: boolean;
60
+ }
61
+ interface ReportOutput {
62
+ report: ReportV1;
63
+ run: RunDir;
64
+ paths: Record<string, string>;
65
+ }
66
+ /**
67
+ * Finalize a run. The scope and graph are recomputed here instead of read from the run directory,
68
+ * so the proof gate checks model findings against the repository, not against editable files.
69
+ */
70
+ declare function runReport(args: ReportArgs): Promise<ReportOutput>;
71
+ /** Guess modules from the folder structure. */
72
+ declare function guessModules(root: string): Record<string, string>;
73
+ declare function renderSkeleton(modules: Record<string, string>): string;
74
+ declare function runInit(cwd: string, force?: boolean): {
75
+ file: string;
76
+ modules: string[];
77
+ content: string;
78
+ };
79
+
80
+ export { type CheckArgs, type GraphArgs, type ProveArgs, type ReportArgs, type ReportOutput, type ScopeArgs, VERSION, contractFor, guessModules, lensDir, listLenses, renderSkeleton, runCheck, runGraph, runInit, runProve, runReport, startScope };
package/dist/lib.js ADDED
@@ -0,0 +1,29 @@
1
+ import {
2
+ VERSION,
3
+ contractFor,
4
+ guessModules,
5
+ lensDir,
6
+ listLenses,
7
+ renderSkeleton,
8
+ runCheck,
9
+ runGraph,
10
+ runInit,
11
+ runProve,
12
+ runReport,
13
+ startScope
14
+ } from "./chunk-UUYJFDRT.js";
15
+ export {
16
+ VERSION,
17
+ contractFor,
18
+ guessModules,
19
+ lensDir,
20
+ listLenses,
21
+ renderSkeleton,
22
+ runCheck,
23
+ runGraph,
24
+ runInit,
25
+ runProve,
26
+ runReport,
27
+ startScope
28
+ };
29
+ //# sourceMappingURL=lib.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,106 @@
1
+ import {
2
+ VERSION,
3
+ listLenses,
4
+ runCheck,
5
+ runGraph,
6
+ runReport,
7
+ startScope
8
+ } from "./chunk-UUYJFDRT.js";
9
+
10
+ // src/mcp.ts
11
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
+ import { NothingToReviewError, renderMarkdown } from "@tanziro/plumbline-core";
14
+ import { z } from "zod";
15
+ var repo = z.string().optional().describe("Path inside the git repository. Defaults to the server's working directory.");
16
+ var base = z.string().optional().describe("Base branch or ref. Defaults to dev, then main, then master.");
17
+ var json = (value) => ({ content: [{ type: "text", text: JSON.stringify(value, null, 2) }] });
18
+ async function guarded(fn) {
19
+ try {
20
+ return await fn();
21
+ } catch (error) {
22
+ if (error instanceof NothingToReviewError) return json({ nothingToReview: true, message: error.message });
23
+ return { isError: true, content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }] };
24
+ }
25
+ }
26
+ function createServer(defaultCwd = process.cwd()) {
27
+ const server = new McpServer({ name: "plumbline", version: VERSION });
28
+ const cwd = (path) => path ?? defaultCwd;
29
+ server.registerTool(
30
+ "scope",
31
+ {
32
+ description: "Pin the review scope: diff range, changed files, contract, ADRs and rule files. Starts a run.",
33
+ inputSchema: { repo, base, target: z.string().optional().describe("Branch, commit or PR number to review.") },
34
+ annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: false }
35
+ },
36
+ ({ repo: path, base: ref, target }) => guarded(() => json({ ...startScope({ cwd: cwd(path), base: ref, target }).scope }))
37
+ );
38
+ server.registerTool(
39
+ "graph_diff",
40
+ {
41
+ description: "Diff the JS/TS import graph between base and HEAD: added and removed edges, new cycles, layer crossings.",
42
+ inputSchema: { repo, base },
43
+ annotations: { readOnlyHint: false, openWorldHint: false }
44
+ },
45
+ ({ repo: path, base: ref }) => guarded(async () => {
46
+ const { run, graph } = await runGraph({ cwd: cwd(path), base: ref });
47
+ return json({ runId: run.id, diff: graph.diff, violations: graph.check.violations });
48
+ })
49
+ );
50
+ server.registerTool(
51
+ "check_contract",
52
+ {
53
+ description: "Evaluate plumbline.yml forbid and layer rules against the current tree. Never runs custom commands.",
54
+ inputSchema: { repo },
55
+ annotations: { readOnlyHint: false, openWorldHint: false }
56
+ },
57
+ ({ repo: path }) => guarded(async () => {
58
+ const { result, run, hasContract } = await runCheck({ cwd: cwd(path) });
59
+ return json({ runId: run.id, hasContract, ...result });
60
+ })
61
+ );
62
+ server.registerTool(
63
+ "list_lenses",
64
+ {
65
+ description: "List the review lenses, including any in the repo's .plumbline/lenses folder.",
66
+ inputSchema: { repo, includeBody: z.boolean().optional().describe("Include each lens's full brief.") },
67
+ annotations: { readOnlyHint: true, openWorldHint: false }
68
+ },
69
+ ({ repo: path, includeBody }) => guarded(
70
+ () => json(
71
+ listLenses(cwd(path)).map(({ body, file: _file, ...meta }) => includeBody ? { ...meta, body } : meta)
72
+ )
73
+ )
74
+ );
75
+ server.registerTool(
76
+ "render_report",
77
+ {
78
+ description: "Apply the proof gate to findings, compute the merge score and write report.md, report.json and report.sarif.",
79
+ inputSchema: {
80
+ repo,
81
+ base,
82
+ run: z.string().optional().describe("Run id. Defaults to the latest."),
83
+ findings: z.record(z.string(), z.unknown()).optional().describe("Findings file content. See references/findings.md.")
84
+ },
85
+ annotations: { readOnlyHint: false, openWorldHint: false }
86
+ },
87
+ ({ repo: path, base: ref, run, findings }) => guarded(async () => {
88
+ const out = await runReport({ cwd: cwd(path), base: ref, run, findingsValue: findings });
89
+ return {
90
+ content: [
91
+ { type: "text", text: renderMarkdown(out.report) },
92
+ { type: "text", text: JSON.stringify({ runId: out.run.id, score: out.report.score, gate: out.report.gate, lane: out.report.lane, paths: out.paths }, null, 2) }
93
+ ]
94
+ };
95
+ })
96
+ );
97
+ return server;
98
+ }
99
+ async function serveStdio() {
100
+ await createServer().connect(new StdioServerTransport());
101
+ }
102
+ export {
103
+ createServer,
104
+ serveStdio
105
+ };
106
+ //# sourceMappingURL=mcp-XABJTEWQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { NothingToReviewError, renderMarkdown } from \"@tanziro/plumbline-core\";\nimport { z } from \"zod\";\nimport { VERSION, listLenses, runCheck, runGraph, runReport, startScope } from \"./lib.js\";\n\nconst repo = z.string().optional().describe(\"Path inside the git repository. Defaults to the server's working directory.\");\nconst base = z.string().optional().describe(\"Base branch or ref. Defaults to dev, then main, then master.\");\n\ntype ToolResult = { content: { type: \"text\"; text: string }[]; isError?: boolean };\n\nconst json = (value: unknown): ToolResult => ({ content: [{ type: \"text\", text: JSON.stringify(value, null, 2) }] });\n\nasync function guarded(fn: () => Promise<ToolResult> | ToolResult): Promise<ToolResult> {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof NothingToReviewError) return json({ nothingToReview: true, message: error.message });\n return { isError: true, content: [{ type: \"text\", text: error instanceof Error ? error.message : String(error) }] };\n }\n}\n\nexport function createServer(defaultCwd: string = process.cwd()): McpServer {\n const server = new McpServer({ name: \"plumbline\", version: VERSION });\n const cwd = (path?: string) => path ?? defaultCwd;\n\n server.registerTool(\n \"scope\",\n {\n description: \"Pin the review scope: diff range, changed files, contract, ADRs and rule files. Starts a run.\",\n inputSchema: { repo, base, target: z.string().optional().describe(\"Branch, commit or PR number to review.\") },\n annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: false },\n },\n ({ repo: path, base: ref, target }) => guarded(() => json({ ...startScope({ cwd: cwd(path), base: ref, target }).scope })),\n );\n\n server.registerTool(\n \"graph_diff\",\n {\n description: \"Diff the JS/TS import graph between base and HEAD: added and removed edges, new cycles, layer crossings.\",\n inputSchema: { repo, base },\n annotations: { readOnlyHint: false, openWorldHint: false },\n },\n ({ repo: path, base: ref }) =>\n guarded(async () => {\n const { run, graph } = await runGraph({ cwd: cwd(path), base: ref });\n return json({ runId: run.id, diff: graph.diff, violations: graph.check.violations });\n }),\n );\n\n server.registerTool(\n \"check_contract\",\n {\n description: \"Evaluate plumbline.yml forbid and layer rules against the current tree. Never runs custom commands.\",\n inputSchema: { repo },\n annotations: { readOnlyHint: false, openWorldHint: false },\n },\n ({ repo: path }) =>\n guarded(async () => {\n const { result, run, hasContract } = await runCheck({ cwd: cwd(path) });\n return json({ runId: run.id, hasContract, ...result });\n }),\n );\n\n server.registerTool(\n \"list_lenses\",\n {\n description: \"List the review lenses, including any in the repo's .plumbline/lenses folder.\",\n inputSchema: { repo, includeBody: z.boolean().optional().describe(\"Include each lens's full brief.\") },\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n ({ repo: path, includeBody }) =>\n guarded(() =>\n json(\n listLenses(cwd(path)).map(({ body, file: _file, ...meta }) => (includeBody ? { ...meta, body } : meta)),\n ),\n ),\n );\n\n server.registerTool(\n \"render_report\",\n {\n description:\n \"Apply the proof gate to findings, compute the merge score and write report.md, report.json and report.sarif.\",\n inputSchema: {\n repo,\n base,\n run: z.string().optional().describe(\"Run id. Defaults to the latest.\"),\n findings: z.record(z.string(), z.unknown()).optional().describe(\"Findings file content. See references/findings.md.\"),\n },\n annotations: { readOnlyHint: false, openWorldHint: false },\n },\n ({ repo: path, base: ref, run, findings }) =>\n guarded(async () => {\n const out = await runReport({ cwd: cwd(path), base: ref, run, findingsValue: findings });\n return {\n content: [\n { type: \"text\", text: renderMarkdown(out.report) },\n { type: \"text\", text: JSON.stringify({ runId: out.run.id, score: out.report.score, gate: out.report.gate, lane: out.report.lane, paths: out.paths }, null, 2) },\n ],\n };\n }),\n );\n\n return server;\n}\n\nexport async function serveStdio(): Promise<void> {\n await createServer().connect(new StdioServerTransport());\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,sBAAsB,sBAAsB;AACrD,SAAS,SAAS;AAGlB,IAAM,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,6EAA6E;AACzH,IAAM,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,8DAA8D;AAI1G,IAAM,OAAO,CAAC,WAAgC,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,KAAK,UAAU,OAAO,MAAM,CAAC,EAAE,CAAC,EAAE;AAElH,eAAe,QAAQ,IAAiE;AACtF,MAAI;AACF,WAAO,MAAM,GAAG;AAAA,EAClB,SAAS,OAAO;AACd,QAAI,iBAAiB,qBAAsB,QAAO,KAAK,EAAE,iBAAiB,MAAM,SAAS,MAAM,QAAQ,CAAC;AACxG,WAAO,EAAE,SAAS,MAAM,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC,EAAE;AAAA,EACpH;AACF;AAEO,SAAS,aAAa,aAAqB,QAAQ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AAM,IAAI,OAAO,MAAM,MAAM,IAAI,OAAO,MAAM,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,EAAE;AAAA,QAChK;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACL;AAEA,SAAO;AACT;AAEA,eAAsB,aAA4B;AAChD,QAAM,aAAa,EAAE,QAAQ,IAAI,qBAAqB,CAAC;AACzD;","names":[]}
@@ -0,0 +1,33 @@
1
+ ---
2
+ id: L01
3
+ name: "Regressions"
4
+ default: "on"
5
+ proof: [failing_test]
6
+ catches: "Logic bugs, null paths and off-by-ones, traced with concrete values."
7
+ example: "total += item.qty // qty can be undefined"
8
+ ---
9
+
10
+ # L01 Regressions
11
+
12
+ Logic bugs, null paths and off-by-ones, traced with concrete values.
13
+
14
+ ## What to look for
15
+
16
+ - Inverted or widened conditions, off-by-one, wrong variable, unit, default or time zone.
17
+ - Null, empty and zero input reaching code that assumes a value.
18
+ - A missing `await`, swallowed errors, partial writes and fallbacks that hide a failure.
19
+ - One call site changed while its siblings were not.
20
+
21
+ ## How to prove it
22
+
23
+ Pick concrete values and trace them through the real code. Then write a test under `.plumbline/proofs/` that fails on HEAD and record it with `plumbline prove`.
24
+
25
+ ## False-positive traps
26
+
27
+ - A guard upstream, a type or a database constraint already rules the input out.
28
+ - The behaviour is unchanged by this diff.
29
+ - The caller never passes that value.
30
+
31
+ ## Examples
32
+
33
+ `total += item.qty` where an API payload may omit `qty` turns the invoice total into `NaN`.
@@ -0,0 +1,32 @@
1
+ ---
2
+ id: L02
3
+ name: "Boundaries & cycles"
4
+ default: "on"
5
+ proof: [graph_diff, broken_rule]
6
+ catches: "New edges in the import graph that cross a layer or close a loop."
7
+ example: "billing -> users/session -> billing"
8
+ ---
9
+
10
+ # L02 Boundaries & cycles
11
+
12
+ New edges in the import graph that cross a layer or close a loop.
13
+
14
+ ## What to look for
15
+
16
+ - New cycles and layer crossings in `graph.json`. These are already findings, so do not re-derive them.
17
+ - Coupling the graph cannot see: dynamic imports, string-keyed registries, shared globals, or reaching into another module's internals.
18
+ - Non-JS/TS code, where the graph checks do not run in v1.0. Read the imports by hand.
19
+
20
+ ## How to prove it
21
+
22
+ Cite the exact edge or cycle from the graph diff as `graph_diff`, or the contract rule id as `broken_rule` with the file and line.
23
+
24
+ ## False-positive traps
25
+
26
+ - Type-only imports do not create runtime cycles.
27
+ - An edge that already existed at base is not this PR's finding.
28
+ - A layer may skip downward: `api -> db` is allowed unless a rule forbids it.
29
+
30
+ ## Examples
31
+
32
+ `billing/invoice.ts` imports `users/session`, which already depends on billing for plan limits.
@@ -0,0 +1,32 @@
1
+ ---
2
+ id: L03
3
+ name: "Pattern deviations"
4
+ default: "on"
5
+ proof: [failing_test, broken_rule]
6
+ catches: "Code that breaks the codebase's own majority pattern."
7
+ example: "23/23 repo methods scope org_id"
8
+ ---
9
+
10
+ # L03 Pattern deviations
11
+
12
+ Code that breaks the codebase's own majority pattern.
13
+
14
+ ## What to look for
15
+
16
+ - For each new function, find its siblings and note what they all do: filters, validation, locking, registration, logging.
17
+ - A new method that skips what every sibling does, above all tenant scoping and authorization.
18
+ - `require` rules in the contract with `check: llm` that cover the changed paths.
19
+
20
+ ## How to prove it
21
+
22
+ Count the siblings and state the ratio. If the deviation causes wrong behaviour, write a failing test. If a contract rule covers it, cite the rule id with the file and line.
23
+
24
+ ## False-positive traps
25
+
26
+ - Being different is not a defect. The deviation must cause a problem.
27
+ - A small sample is not a pattern.
28
+ - The method may be deliberately global, such as an admin job, and say so in a stated decision.
29
+
30
+ ## Examples
31
+
32
+ `InvoiceRepo.listAll()` reads across tenants while every other repository method filters by `org_id`.
@@ -0,0 +1,33 @@
1
+ ---
2
+ id: L04
3
+ name: "Distributed systems"
4
+ default: "on"
5
+ proof: [failing_test]
6
+ catches: "Retries without idempotency, dual writes without an outbox, calls without timeouts."
7
+ example: "webhook handler · no dedupe key"
8
+ ---
9
+
10
+ # L04 Distributed systems
11
+
12
+ Retries without idempotency, dual writes without an outbox, calls without timeouts.
13
+
14
+ ## What to look for
15
+
16
+ - Handlers that can be delivered twice with no dedupe key.
17
+ - A database write and a queue publish with nothing tying them together.
18
+ - Network calls with no timeout, and retries of work that is not idempotent.
19
+ - Locks or transactions held across slow calls.
20
+
21
+ ## How to prove it
22
+
23
+ Write a test that replays the delivery or fails the second write, and show the wrong final state.
24
+
25
+ ## False-positive traps
26
+
27
+ - The framework may already dedupe or retry safely. Read its configuration.
28
+ - Single-process code has no delivery problem.
29
+ - A missing timeout on a local call is not a finding.
30
+
31
+ ## Examples
32
+
33
+ A payment webhook extends a subscription each time it is delivered, so a retry grants a second period.
@@ -0,0 +1,33 @@
1
+ ---
2
+ id: L05
3
+ name: "Migrations"
4
+ default: "on"
5
+ proof: [broken_rule, failing_test]
6
+ catches: "Schema changes that break rolling deploys or drop data without a backfill."
7
+ example: "DROP COLUMN while old pods read it"
8
+ ---
9
+
10
+ # L05 Migrations
11
+
12
+ Schema changes that break rolling deploys or drop data without a backfill.
13
+
14
+ ## What to look for
15
+
16
+ - Dropped or renamed columns and tables that the previous release still reads.
17
+ - `NOT NULL` added without a default or a backfill.
18
+ - Long locks on large tables.
19
+ - Code and schema changed in one deploy where order matters.
20
+
21
+ ## How to prove it
22
+
23
+ Grep for readers of the column at HEAD and at base, and cite them. Cite the contract rule if one covers migrations. If you can run the migration locally, write a failing test.
24
+
25
+ ## False-positive traps
26
+
27
+ - A table that was created in this same PR has no old readers.
28
+ - The project may deploy with downtime by design. Check the docs and ADRs.
29
+ - A column nothing reads is safe to drop.
30
+
31
+ ## Examples
32
+
33
+ `ALTER TABLE invoices DROP COLUMN legacy_total` ships while running pods still select it. Ship it as expand, migrate, contract.
@@ -0,0 +1,32 @@
1
+ ---
2
+ id: L06
3
+ name: "API contracts"
4
+ default: "on"
5
+ proof: [graph_diff, broken_rule]
6
+ catches: "Breaking changes to OpenAPI, proto or event schemas, with consumers in other repos."
7
+ example: "removed field · 3 consumers"
8
+ ---
9
+
10
+ # L06 API contracts
11
+
12
+ Breaking changes to OpenAPI, proto or event schemas, with consumers in other repos.
13
+
14
+ ## What to look for
15
+
16
+ - Removed or renamed fields, changed types, and new required fields in OpenAPI, proto, GraphQL or event schemas.
17
+ - Exports of a shared package changing shape while importers still use the old one.
18
+ - Stored payloads and queued messages written by the previous version that must still load.
19
+
20
+ ## How to prove it
21
+
22
+ Cite each consumer edge from the graph diff, or the rule or ADR that promises compatibility, with the file and line.
23
+
24
+ ## False-positive traps
25
+
26
+ - An internal type with no external consumers can change freely.
27
+ - A versioned endpoint may keep the old shape elsewhere.
28
+ - Adding an optional field is not a breaking change.
29
+
30
+ ## Examples
31
+
32
+ An event drops `customer_id` while a consumer in another package still reads it.
@@ -0,0 +1,33 @@
1
+ ---
2
+ id: L07
3
+ name: "Agent-PR hygiene"
4
+ default: "on"
5
+ proof: [broken_rule]
6
+ catches: "Reinvented helpers, needless abstraction, tests that assert mocks instead of behavior."
7
+ example: "formatMoney() exists in lib/fmt"
8
+ ---
9
+
10
+ # L07 Agent-PR hygiene
11
+
12
+ Reinvented helpers, needless abstraction, tests that assert mocks instead of behavior.
13
+
14
+ ## What to look for
15
+
16
+ - New helpers that duplicate one already in the repo.
17
+ - Abstractions with a single caller and no stated reason.
18
+ - Tests that assert on mocks, or would still pass if the change were reverted.
19
+ - Changes that contradict AGENTS.md or CLAUDE.md.
20
+
21
+ ## How to prove it
22
+
23
+ Cite the rule file line that the change breaks, or the existing helper by path. Without a broken rule this stays at P2 or below.
24
+
25
+ ## False-positive traps
26
+
27
+ - Style and naming preferences are not findings.
28
+ - Two similar functions may differ for a good reason.
29
+ - Do not ask for tests in general. Name the unprotected behaviour.
30
+
31
+ ## Examples
32
+
33
+ A PR adds `formatCurrency()` while `formatMoney()` in `lib/fmt` already handles the same cases.
@@ -0,0 +1,33 @@
1
+ ---
2
+ id: L08
3
+ name: "Operability & cost"
4
+ default: "on"
5
+ proof: [broken_rule]
6
+ catches: "Risky paths with no flag or metrics, model calls inside loops."
7
+ example: "llm.call() inside forEach"
8
+ ---
9
+
10
+ # L08 Operability & cost
11
+
12
+ Risky paths with no flag or metrics, model calls inside loops.
13
+
14
+ ## What to look for
15
+
16
+ - Paid API or model calls inside loops or per-request paths.
17
+ - Unbounded fetches, N+1 queries and missing pagination at realistic sizes.
18
+ - A risky rollout with no flag or kill switch where the repo's rules ask for one.
19
+ - Failures that nothing logs or measures.
20
+
21
+ ## How to prove it
22
+
23
+ Cite the rule that requires the flag, limit or metric, with the file and line. Without one this stays at P2 or below.
24
+
25
+ ## False-positive traps
26
+
27
+ - A loop over a small fixed list is fine.
28
+ - Do not ask for observability the rest of the codebase does not have.
29
+ - Admin scripts have different cost limits.
30
+
31
+ ## Examples
32
+
33
+ `llm.call()` inside `forEach` over every open ticket runs on each page load.
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@tanziro/plumbline",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Plumbline CLI and MCP server: scope, import graph diff, contract checks and reports.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/tanzir71/plumbline.git",
10
+ "directory": "packages/cli"
11
+ },
12
+ "homepage": "https://tanzir71.github.io/plumbline/",
13
+ "engines": {
14
+ "node": ">=20.12.0"
15
+ },
16
+ "bin": {
17
+ "plumbline": "./bin/plumbline.js"
18
+ },
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/lib.d.ts",
22
+ "import": "./dist/lib.js"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
26
+ "files": [
27
+ "bin",
28
+ "dist",
29
+ "lenses"
30
+ ],
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "dependencies": {
35
+ "@modelcontextprotocol/sdk": "^1.32.2",
36
+ "yaml": "^2.9.1",
37
+ "zod": "^4.6.7",
38
+ "@tanziro/plumbline-core": "^1.0.0"
39
+ },
40
+ "scripts": {
41
+ "build": "tsup && node ../../scripts/copy-lenses.mjs",
42
+ "test": "vitest run",
43
+ "typecheck": "tsc --noEmit"
44
+ }
6
45
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.