@viberaven/mcp 1.6.12 → 1.7.1

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.
@@ -30,6 +30,598 @@ __export(tools_exports, {
30
30
  });
31
31
  module.exports = __toCommonJS(tools_exports);
32
32
 
33
+ // ../../shared/rlsTool.ts
34
+ var RLS_TOOL_NAME = "viberaven_rls_test";
35
+ var RLS_RUN_TIMEOUT_MS = 3e5;
36
+ var RLS_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
37
+ var NON_AUTHORITATIVE_LABEL = "PGlite imitation of Supabase, non-authoritative. Scenario passed locally does not prove production.";
38
+ var MAX_PATH_LENGTH = 4096;
39
+ var RLS_TOOL = {
40
+ name: RLS_TOOL_NAME,
41
+ description: "After reviewing a Supabase migration or ownership policy, optionally execute already reviewed local permissions scenarios for owner, other_user and anon. Returns Pass, Fail or Unknown per cell with the original scoped evidence. This is an experimental PGlite imitation, not live Supabase proof. The optional PGlite dependency must already be installed next to the matching CLI used by this local MCP host; missing setup returns the CLI setup guidance as a tool error. No SQL, credentials, provider calls or dependency installation are accepted.",
42
+ inputSchema: {
43
+ type: "object",
44
+ properties: {
45
+ matrix: { type: "string", minLength: 1, maxLength: MAX_PATH_LENGTH, description: "Path to an already reviewed permissions JSON file, relative to cwd or absolute. Expectations must describe intended access." },
46
+ migrations: { type: "string", minLength: 1, maxLength: MAX_PATH_LENGTH, description: "Local migrations directory. Defaults to supabase/migrations under cwd." },
47
+ cwd: { type: "string", minLength: 1, maxLength: MAX_PATH_LENGTH, description: "Project root. Defaults to the MCP server working directory." }
48
+ },
49
+ required: ["matrix"],
50
+ additionalProperties: false
51
+ }
52
+ };
53
+ function record(value) {
54
+ return value !== null && typeof value === "object" && !Array.isArray(value);
55
+ }
56
+ function nonempty(value) {
57
+ return typeof value === "string" && Boolean(value.trim());
58
+ }
59
+ function pathArg(value, name, commandLine = true) {
60
+ if (!nonempty(value) || value.length > MAX_PATH_LENGTH || /[\x00-\x1f\x7f]/.test(value)) throw Error(`Invalid RLS ${name}: expected a non-empty local path up to ${MAX_PATH_LENGTH} characters`);
61
+ if (commandLine && (value.trimStart().startsWith("-") || /[&|<>^%!"'`$();]/.test(value))) throw Error(`Unsafe RLS ${name} path`);
62
+ return value;
63
+ }
64
+ function buildRlsToolArgs(input) {
65
+ if (!record(input) || Object.keys(input).some((key) => !["matrix", "migrations", "cwd"].includes(key))) throw Error("Invalid RLS tool arguments: only matrix, migrations and cwd are accepted");
66
+ const args = ["rls-test", "--json", "--matrix", pathArg(input.matrix, "matrix")];
67
+ if ("migrations" in input) args.push("--migrations", pathArg(input.migrations, "migrations"));
68
+ if ("cwd" in input) pathArg(input.cwd, "cwd", false);
69
+ return args;
70
+ }
71
+ var hash = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
72
+ var strings = (value) => Array.isArray(value) && value.every(nonempty);
73
+ var actions = ["select", "insert", "update", "delete"];
74
+ var actors = ["owner", "other_user", "anon"];
75
+ function completedReceipt(receipt, processExit) {
76
+ if ("error" in receipt || receipt.tool !== "viberaven rls-test" || receipt.experimental !== true || receipt.label !== NON_AUTHORITATIVE_LABEL || !nonempty(receipt.project)) return false;
77
+ if (![0, 1, 2].includes(processExit) || receipt.exitCode !== processExit) return false;
78
+ const { engine, migrations, matrix, summary, tables, roleChecks } = receipt;
79
+ if (!record(engine) || engine.name !== "PGlite" || engine.available !== true || "error" in engine) return false;
80
+ if (!record(migrations) || migrations.applied !== true || "failure" in migrations || !nonempty(migrations.dir) || !hash(migrations.hash) || !Array.isArray(migrations.files) || migrations.files.length === 0 || !migrations.files.every((file) => record(file) && nonempty(file.name) && hash(file.sha256))) return false;
81
+ if (!record(matrix) || !nonempty(matrix.path) || !hash(matrix.hash) || !["none", "supabase-legacy"].includes(matrix.defaultGrants)) return false;
82
+ if (receipt.commit !== null && (!record(receipt.commit) || typeof receipt.commit.sha !== "string" || !/^[a-f0-9]{40}$/.test(receipt.commit.sha) || ![true, false, null].includes(receipt.commit.dirty))) return false;
83
+ if (!strings(receipt.filesRead) || !strings(receipt.assumptions) || !strings(receipt.exclusions)) return false;
84
+ if (!Array.isArray(roleChecks) || !roleChecks.every((check) => record(check) && nonempty(check.role) && check.ok === true && nonempty(check.detail))) return false;
85
+ const checkedRoles = new Set(roleChecks.map((check) => check.role));
86
+ if (checkedRoles.size !== roleChecks.length || !checkedRoles.has("anon") || !checkedRoles.has("authenticated")) return false;
87
+ if (!record(summary) || !Array.isArray(tables) || tables.length === 0) return false;
88
+ const counts = { pass: 0, fail: 0, unknown: 0, notApplicable: 0, tested: 0, total: 0 };
89
+ const tableNames = /* @__PURE__ */ new Set();
90
+ for (const table of tables) {
91
+ if (!record(table) || !nonempty(table.name) || tableNames.has(table.name) || !Array.isArray(table.cells) || table.cells.length === 0) return false;
92
+ tableNames.add(table.name);
93
+ const cells = /* @__PURE__ */ new Set();
94
+ let observed = false;
95
+ for (const cell of table.cells) {
96
+ if (!record(cell) || cell.table !== table.name || ![...actors, "service_role"].includes(cell.actor) || ![...actions, "reassign"].includes(cell.action)) return false;
97
+ const key = `${cell.actor}:${cell.action}`;
98
+ if (cells.has(key) || !record(cell.observed) || !nonempty(cell.observed.summary) || !nonempty(cell.reason)) return false;
99
+ cells.add(key);
100
+ if (cell.actor === "service_role") {
101
+ if (!actions.includes(cell.action) || cell.expected !== "excluded" || cell.outcome !== "N/A") return false;
102
+ } else if (cell.expected === "skip") {
103
+ if (cell.outcome !== "N/A") return false;
104
+ } else if (!["allow", "deny"].includes(cell.expected) || !["Pass", "Fail", "Unknown"].includes(cell.outcome)) return false;
105
+ if (cell.outcome === "Pass") {
106
+ counts.pass += 1;
107
+ observed = true;
108
+ } else if (cell.outcome === "Fail") {
109
+ counts.fail += 1;
110
+ observed = true;
111
+ } else if (cell.outcome === "Unknown") counts.unknown += 1;
112
+ else if (cell.outcome === "N/A") counts.notApplicable += 1;
113
+ else return false;
114
+ counts.total += 1;
115
+ }
116
+ if (actors.some((actor) => actions.some((action) => !cells.has(`${actor}:${action}`)))) return false;
117
+ if (actions.some((action) => cells.has(`service_role:${action}`)) && actions.some((action) => !cells.has(`service_role:${action}`))) return false;
118
+ if (observed || table.rls !== void 0) {
119
+ if (!record(table.rls) || typeof table.rls.enabled !== "boolean" || typeof table.rls.forced !== "boolean" || !nonempty(table.rls.owner)) return false;
120
+ if (!checkedRoles.has(`anon on ${table.name}`) || !checkedRoles.has(`authenticated on ${table.name}`)) return false;
121
+ }
122
+ }
123
+ counts.tested = counts.total - counts.notApplicable;
124
+ if (Object.entries(counts).some(([key, value]) => !Number.isSafeInteger(summary[key]) || summary[key] !== value)) return false;
125
+ const exitCode = counts.fail > 0 ? 1 : counts.pass === 0 || counts.unknown > 0 ? 2 : 0;
126
+ if (processExit !== exitCode) return false;
127
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
128
+ const verdict = counts.fail > 0 ? `Not ready within tested scope: ${plural(counts.fail, "cell does", "cells do")} not match the matrix; ${plural(counts.unknown, "unknown")}.` : counts.pass === 0 ? `Nothing was observed: ${plural(counts.unknown, "unknown")}, ${counts.notApplicable} N/A.` : counts.unknown > 0 ? `No blockers found within tested scope; ${plural(counts.unknown, "unknown")}.` : "No blockers found within tested scope; 0 unknowns. Scenario passed locally.";
129
+ return receipt.verdict === verdict;
130
+ }
131
+ function classifyRlsToolResult(stdout, exitCode, transportError = false) {
132
+ let receipt;
133
+ try {
134
+ receipt = JSON.parse(stdout);
135
+ } catch {
136
+ return { isError: true };
137
+ }
138
+ if (!record(receipt)) return { isError: true };
139
+ return { isError: transportError || !completedReceipt(receipt, exitCode), structuredContent: receipt };
140
+ }
141
+ function buildRlsToolResponse(run) {
142
+ const classified = classifyRlsToolResult(run.stdout, run.exitCode, run.transportError);
143
+ const text = !classified.isError && classified.structuredContent ? `exit ${run.exitCode}
144
+ ${JSON.stringify(classified.structuredContent)}${run.stderr ? `
145
+ ${run.stderr}` : ""}`.trim() : run.text;
146
+ return { content: [{ type: "text", text }], ...classified };
147
+ }
148
+
149
+ // ../../shared/liveTools.ts
150
+ var cwd = { type: "string", description: "Local project directory. Defaults to the MCP working directory." };
151
+ var stepId = { type: "string", format: "uuid", description: "The stepId returned by live_start; preserve it through sign-in, payment and retries." };
152
+ var supabaseProjectPattern = "^[a-z]{20}$";
153
+ var vercelProjectPattern = "^prj_[a-zA-Z0-9]{8,80}$";
154
+ var vercelTeamPattern = "^team_[a-zA-Z0-9]{8,80}$";
155
+ var schemaPattern = "^(?!pg_)(?!(?:auth|storage|vault|information_schema)$)[a-z][a-z0-9_]{0,62}$";
156
+ var LIVE_TOOLS = [
157
+ {
158
+ name: "viberaven_live_start",
159
+ description: "Local candidate feature: save a scoped metadata-verification request without provider reads or payment. Supabase catalog reads require a VibeRaven account and explicit human consent on resume. Vercel is deliberately blocked before network access. Local repository checks stay free without an account. Never pass credentials as tool arguments.",
160
+ inputSchema: {
161
+ type: "object",
162
+ properties: {
163
+ cwd,
164
+ provider: { type: "string", enum: ["supabase", "vercel"] },
165
+ projectRef: { type: "string", description: "Exact provider project ID: 20 lowercase letters for Supabase, or prj_ followed by 8\u201380 alphanumeric characters for Vercel." },
166
+ schemas: { type: "array", items: { type: "string", pattern: schemaPattern }, minItems: 1, maxItems: 8, uniqueItems: true, description: "1\u20138 lowercase application schemas; defaults to public. Excludes pg_, auth, storage, vault and information_schema. No application-row reads." },
167
+ teamId: { type: "string", pattern: vercelTeamPattern, description: "Optional Vercel team_ ID with 8\u201380 alphanumeric characters. Vercel transport is currently blocked." }
168
+ },
169
+ required: ["provider", "projectRef"],
170
+ additionalProperties: false,
171
+ allOf: [
172
+ { if: { properties: { provider: { const: "supabase" } } }, then: { properties: { projectRef: { pattern: supabaseProjectPattern } }, not: { required: ["teamId"] } } },
173
+ { if: { properties: { provider: { const: "vercel" } } }, then: { properties: { projectRef: { pattern: vercelProjectPattern } }, not: { required: ["schemas"] } } }
174
+ ]
175
+ }
176
+ },
177
+ {
178
+ name: "viberaven_live_resume",
179
+ description: "Local candidate feature: resume the SAME saved live step through account connection, allowance and metadata verification. Set approvedRead=true only after the person explicitly approves the named Supabase project/schema catalog read. Show any returned action URL and wait for the person; never approve sign-in or payment for them. Credentials stay local and are never tool arguments. Vercel stays blocked; local checks stay free.",
180
+ inputSchema: { type: "object", properties: { cwd, stepId, approvedRead: { type: "boolean", description: "True only after explicit human approval of this saved provider/project/schema read." } }, required: ["stepId"], additionalProperties: false }
181
+ },
182
+ {
183
+ name: "viberaven_live_status",
184
+ description: "Local candidate feature: read the saved live-step receipt without provider reads, payment or another live-step charge. Evidence is historical and scoped, not proof of application security. Local checks stay free.",
185
+ inputSchema: { type: "object", properties: { cwd, stepId }, required: ["stepId"], additionalProperties: false }
186
+ },
187
+ {
188
+ name: "viberaven_live_disconnect",
189
+ description: "Local candidate feature: disconnect the saved live step and remove its locally retained provider credential and evidence. Does not alter provider settings or unrelated MCP credentials. Unfinished account reservations expire. Local checks stay free.",
190
+ inputSchema: { type: "object", properties: { cwd, stepId }, required: ["stepId"], additionalProperties: false }
191
+ }
192
+ ];
193
+ function isLiveTool(name) {
194
+ return LIVE_TOOLS.some((tool) => tool.name === name);
195
+ }
196
+ function isLiveToolFailure(exitCode, receipt) {
197
+ if (exitCode !== 0) return true;
198
+ if (!receipt || typeof receipt !== "object") return false;
199
+ const value = receipt;
200
+ return Boolean(value.error) || ["blocked", "failed", "unsupported", "requires_retry"].includes(String(value.state));
201
+ }
202
+ var uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
203
+ function invalid() {
204
+ throw new Error("Invalid live-tool arguments. Use only the documented scope or saved stepId; never pass credentials.");
205
+ }
206
+ function buildLiveToolArgs(name, raw) {
207
+ if (!isLiveTool(name) || !raw || typeof raw !== "object" || Array.isArray(raw)) return invalid();
208
+ const args = raw;
209
+ const allowed = name === "viberaven_live_start" ? ["cwd", "provider", "projectRef", "schemas", "teamId"] : name === "viberaven_live_resume" ? ["cwd", "stepId", "approvedRead"] : ["cwd", "stepId"];
210
+ if (Object.keys(args).some((key) => !allowed.includes(key))) return invalid();
211
+ if (args.cwd !== void 0 && (typeof args.cwd !== "string" || !args.cwd.trim() || args.cwd.length > 4096 || /[\0\r\n]/.test(args.cwd))) return invalid();
212
+ if (name === "viberaven_live_start") {
213
+ if (!["supabase", "vercel"].includes(args.provider) || typeof args.projectRef !== "string" || !new RegExp(args.provider === "supabase" ? supabaseProjectPattern : vercelProjectPattern).test(args.projectRef)) return invalid();
214
+ const out = ["live", "start", "--provider", args.provider, "--project", args.projectRef];
215
+ if (args.schemas !== void 0) {
216
+ if (args.provider !== "supabase" || !Array.isArray(args.schemas) || args.schemas.length < 1 || args.schemas.length > 8 || args.schemas.some((s) => typeof s !== "string" || !new RegExp(schemaPattern).test(s)) || new Set(args.schemas).size !== args.schemas.length) return invalid();
217
+ out.push("--schemas", args.schemas.join(","));
218
+ }
219
+ if (args.teamId !== void 0) {
220
+ if (args.provider !== "vercel" || typeof args.teamId !== "string" || !new RegExp(vercelTeamPattern).test(args.teamId)) return invalid();
221
+ out.push("--team", args.teamId);
222
+ }
223
+ return [...out, "--json"];
224
+ }
225
+ if (typeof args.stepId !== "string" || !uuid.test(args.stepId) || args.approvedRead !== void 0 && typeof args.approvedRead !== "boolean") return invalid();
226
+ return ["live", name.slice("viberaven_live_".length), "--id", args.stepId.toLowerCase(), ...args.approvedRead === true ? ["--approve-read"] : [], "--json"];
227
+ }
228
+
229
+ // ../providers/registry.generated.mjs
230
+ var registry_generated_default = {
231
+ "supabase": {
232
+ "hash": "e03ec354e648f89c22202df2e908e48e1ee88b733af8fe8becd70c8089001e45",
233
+ "pack": {
234
+ "schemaVersion": 1,
235
+ "provider": "supabase",
236
+ "displayName": "Supabase",
237
+ "packVersion": "1.0.0",
238
+ "reviewedAt": "2026-10-27",
239
+ "summary": "Plan Supabase-backed features with explicit identity, permissions, keys and provider seams. Repo rules are available; live catalog checks are planned and have not run.",
240
+ "applicability": [
241
+ "Supabase Data API, Auth, Postgres, Storage and Edge Functions.",
242
+ "Works with any hosting provider; Vercel is an optional seam, not a requirement."
243
+ ],
244
+ "limits": [
245
+ "This pack is knowledge, not a scan, live connection or approval to change a provider.",
246
+ "Catalog metadata cannot prove row isolation or application behavior. Test the feature in an authorized test environment.",
247
+ "Local guidance and repository checks remain free without an account. Future live steps need an account; their free monthly quota is undecided.",
248
+ "No feature-building advantage over plain Claude is claimed before P3 comparison."
249
+ ],
250
+ "sources": [
251
+ {
252
+ "id": "keys",
253
+ "title": "API keys",
254
+ "url": "https://supabase.com/docs/guides/api/api-keys"
255
+ },
256
+ {
257
+ "id": "rls",
258
+ "title": "Row Level Security",
259
+ "url": "https://supabase.com/docs/guides/database/postgres/row-level-security"
260
+ },
261
+ {
262
+ "id": "grants",
263
+ "title": "New table Data API exposure",
264
+ "url": "https://supabase.com/changelog/45329-breaking-change-tables-not-exposed-to-data-and-graphql-api-automatically"
265
+ },
266
+ {
267
+ "id": "functions",
268
+ "title": "Database functions",
269
+ "url": "https://supabase.com/docs/guides/database/functions"
270
+ },
271
+ {
272
+ "id": "connections",
273
+ "title": "Connecting to Postgres",
274
+ "url": "https://supabase.com/docs/guides/database/connecting-to-postgres"
275
+ },
276
+ {
277
+ "id": "clerk",
278
+ "title": "Third-party auth with Clerk",
279
+ "url": "https://supabase.com/docs/guides/auth/third-party/clerk"
280
+ },
281
+ {
282
+ "id": "vercel",
283
+ "title": "Vercel Marketplace integration",
284
+ "url": "https://supabase.com/docs/guides/integrations/vercel-marketplace"
285
+ },
286
+ {
287
+ "id": "edge-auth",
288
+ "title": "Securing Edge Functions",
289
+ "url": "https://supabase.com/docs/guides/functions/auth"
290
+ },
291
+ {
292
+ "id": "storage",
293
+ "title": "Storage access control",
294
+ "url": "https://supabase.com/docs/guides/storage/security/access-control"
295
+ },
296
+ {
297
+ "id": "email",
298
+ "title": "Sending emails from an Edge Function",
299
+ "url": "https://supabase.com/docs/guides/functions/examples/send-emails"
300
+ },
301
+ {
302
+ "id": "mcp",
303
+ "title": "Supabase MCP",
304
+ "url": "https://supabase.com/docs/guides/ai-tools/mcp"
305
+ }
306
+ ],
307
+ "setup": [
308
+ {
309
+ "id": "choose-data-path",
310
+ "title": "Choose Data API or direct Postgres",
311
+ "appliesTo": "Supabase projects using the named feature.",
312
+ "text": "Record the target project and whether calls use supabase-js/Data API or a direct Postgres driver. Connection and permission checks differ.",
313
+ "evidence": "Inspect the relevant configuration and test the requested behavior; guidance is not observed evidence.",
314
+ "sources": [
315
+ "connections"
316
+ ]
317
+ },
318
+ {
319
+ "id": "split-client-server-keys",
320
+ "title": "Separate public and server clients",
321
+ "appliesTo": "Supabase projects using the named feature.",
322
+ "text": "Use a publishable key for public clients. Keep sb_secret_ and legacy service_role credentials server-side; they bypass RLS. End-user identity comes from a user token, not the project key.",
323
+ "evidence": "Inspect the relevant configuration and test the requested behavior; guidance is not observed evidence.",
324
+ "sources": [
325
+ "keys"
326
+ ]
327
+ },
328
+ {
329
+ "id": "define-ownership",
330
+ "title": "Define ownership before tables",
331
+ "appliesTo": "Supabase projects using the named feature.",
332
+ "text": "Enable RLS where appropriate and define role/owner predicates for the feature. Review grants separately.",
333
+ "evidence": "Review migrations, then test allowed and denied actors in an authorized fixture.",
334
+ "sources": [
335
+ "rls",
336
+ "grants"
337
+ ]
338
+ },
339
+ {
340
+ "id": "function-auth-boundary",
341
+ "title": "Choose Edge Function authentication",
342
+ "appliesTo": "Supabase projects using the named feature.",
343
+ "text": "Decide whether a function accepts user JWTs, service calls or signed webhooks. New API keys are not JWTs. Disabling verify_jwt requires explicit handler authorization; it is not an authentication fix by itself.",
344
+ "evidence": "Inspect the relevant configuration and test the requested behavior; guidance is not observed evidence.",
345
+ "sources": [
346
+ "keys",
347
+ "edge-auth"
348
+ ]
349
+ },
350
+ {
351
+ "id": "feature-evidence",
352
+ "title": "Define the evidence before implementation",
353
+ "appliesTo": "Supabase projects using the named feature.",
354
+ "text": "List repo assertions, provider metadata assertions and application tests separately. Planned live capabilities below currently return no observations.",
355
+ "evidence": "A task-specific test plan with each unchecked boundary visible.",
356
+ "sources": [
357
+ "mcp"
358
+ ]
359
+ }
360
+ ],
361
+ "gotchas": [
362
+ {
363
+ "id": "grants-not-policies",
364
+ "title": "42501 is not automatically an RLS bug",
365
+ "appliesTo": "Supabase projects using the named feature.",
366
+ "text": "New Data API tables may lack grants. Grant only intended operations/roles; an RLS policy does not supply table privileges. Do not disable RLS to fix permission denied.",
367
+ "evidence": "Inspect the relevant configuration and test the requested behavior; guidance is not observed evidence.",
368
+ "sources": [
369
+ "grants"
370
+ ]
371
+ },
372
+ {
373
+ "id": "update-select",
374
+ "title": "UPDATE needs a SELECT policy",
375
+ "appliesTo": "Supabase projects using the named feature.",
376
+ "text": "Review the SELECT policy as well as UPDATE predicates. USING applies to existing rows; WITH CHECK constrains the new row. Test owner changes explicitly.",
377
+ "evidence": "Inspect the relevant configuration and test the requested behavior; guidance is not observed evidence.",
378
+ "sources": [
379
+ "rls"
380
+ ]
381
+ },
382
+ {
383
+ "id": "invoker-views",
384
+ "title": "Views need their own access review",
385
+ "appliesTo": "Supabase projects using the named feature.",
386
+ "text": "On supported PostgreSQL versions, security_invoker views use the caller permissions. A view can otherwise bypass intended RLS restrictions depending on its owner.",
387
+ "evidence": "Inspect the relevant configuration and test the requested behavior; guidance is not observed evidence.",
388
+ "sources": [
389
+ "rls"
390
+ ]
391
+ },
392
+ {
393
+ "id": "definer-execute",
394
+ "title": "Function ownership and EXECUTE matter",
395
+ "appliesTo": "Supabase projects using the named feature.",
396
+ "text": "Prefer invoker functions. For a necessary SECURITY DEFINER, constrain search_path and review EXECUTE privileges, including PUBLIC. Do not use elevated functions as a blanket permission workaround.",
397
+ "evidence": "Inspect the relevant configuration and test the requested behavior; guidance is not observed evidence.",
398
+ "sources": [
399
+ "functions"
400
+ ]
401
+ },
402
+ {
403
+ "id": "pooler-mode",
404
+ "title": "Pooler ports have different semantics",
405
+ "appliesTo": "Supabase projects using the named feature.",
406
+ "text": "Session and transaction pooling serve different connection lifetimes. Transaction pooling does not support prepared statements; match the driver configuration to the documented mode instead of changing ports blindly.",
407
+ "evidence": "Inspect the relevant configuration and test the requested behavior; guidance is not observed evidence.",
408
+ "sources": [
409
+ "connections"
410
+ ]
411
+ },
412
+ {
413
+ "id": "storage-upsert",
414
+ "title": "Storage replacement is more than INSERT",
415
+ "appliesTo": "Supabase projects using the named feature.",
416
+ "text": "Storage upsert needs SELECT and UPDATE privileges in addition to INSERT. Test replacement separately from a first upload.",
417
+ "evidence": "Inspect the relevant configuration and test the requested behavior; guidance is not observed evidence.",
418
+ "sources": [
419
+ "storage"
420
+ ]
421
+ }
422
+ ],
423
+ "changes": [
424
+ {
425
+ "id": "data-api-default-grants",
426
+ "title": "New tables require explicit Data API grants",
427
+ "appliesTo": "New public tables reached via Data API or GraphQL; inspect the project setting and grants.",
428
+ "text": "The announcement schedules existing-project rollout for 2026-10-30; new projects started receiving the default on 2026-05-30. Existing table grants remain. Direct Postgres callers are outside this specific change.",
429
+ "evidence": "Review live project metadata after authorized connection; a date alone does not prove rollout.",
430
+ "sources": [
431
+ "grants"
432
+ ],
433
+ "effectiveOn": "2026-10-30",
434
+ "status": "announced"
435
+ },
436
+ {
437
+ "id": "publishable-secret-migration",
438
+ "title": "Use current API-key families",
439
+ "appliesTo": "Supabase projects using the named feature.",
440
+ "text": "Prefer sb_publishable_ and sb_secret_ over the legacy JWT-based project keys. Audit key consumers and Edge Function authorization during migration; do not invent a universal removal date.",
441
+ "evidence": "Inspect the relevant configuration and test the requested behavior; guidance is not observed evidence.",
442
+ "sources": [
443
+ "keys"
444
+ ],
445
+ "effectiveOn": "unknown",
446
+ "status": "undated"
447
+ }
448
+ ],
449
+ "seams": [
450
+ {
451
+ "id": "supabase-vercel",
452
+ "title": "Vercel environment names and targets",
453
+ "appliesTo": "Supabase projects using the named feature.",
454
+ "text": "Check the integration-provided names against code. NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY belong to the public client; SUPABASE_SECRET_KEY stays server-side. Verify the target environment separately.",
455
+ "evidence": "Inspect the relevant configuration and test the requested behavior; guidance is not observed evidence.",
456
+ "sources": [
457
+ "vercel"
458
+ ],
459
+ "providers": [
460
+ "supabase",
461
+ "vercel"
462
+ ]
463
+ },
464
+ {
465
+ "id": "supabase-clerk",
466
+ "title": "Clerk user identity and Supabase authorization",
467
+ "appliesTo": "Supabase projects using the named feature.",
468
+ "text": "Configure the Clerk third-party integration in Supabase. Pass the Clerk session token through the client accessToken callback. Review the authenticated role claim and ownership predicates; successful sign-in alone does not authorize every row.",
469
+ "evidence": "Inspect the relevant configuration and test the requested behavior; guidance is not observed evidence.",
470
+ "sources": [
471
+ "clerk"
472
+ ],
473
+ "providers": [
474
+ "supabase",
475
+ "clerk"
476
+ ]
477
+ },
478
+ {
479
+ "id": "supabase-resend",
480
+ "title": "Resend from an Edge Function",
481
+ "appliesTo": "Supabase projects using the named feature.",
482
+ "text": "Keep RESEND_API_KEY in the function environment and authorize the function caller. Check the sending-domain setup and test email delivery separately from a successful function invocation.",
483
+ "evidence": "Inspect the relevant configuration and test the requested behavior; guidance is not observed evidence.",
484
+ "sources": [
485
+ "email",
486
+ "edge-auth"
487
+ ],
488
+ "providers": [
489
+ "supabase",
490
+ "resend"
491
+ ]
492
+ }
493
+ ],
494
+ "repo-checks": [
495
+ {
496
+ "id": "repo-rls",
497
+ "title": "Migration RLS checks",
498
+ "appliesTo": "Supabase projects using the named feature.",
499
+ "text": "Reference the existing local checks for missing RLS and policies. Their findings describe repository SQL, not applied provider state.",
500
+ "evidence": "Run viberaven check --json in the project and retain the actual finding IDs.",
501
+ "sources": [
502
+ "rls"
503
+ ],
504
+ "ruleIds": [
505
+ "rls_disabled",
506
+ "rls_no_policies"
507
+ ],
508
+ "status": "implemented"
509
+ },
510
+ {
511
+ "id": "repo-keys",
512
+ "title": "Client credential boundary",
513
+ "appliesTo": "Supabase projects using the named feature.",
514
+ "text": "Existing local rules detect service-role credentials in client env or code; an absent finding is not proof that no secret was ever exposed.",
515
+ "evidence": "Run the local check and inspect relevant source files.",
516
+ "sources": [
517
+ "keys"
518
+ ],
519
+ "ruleIds": [
520
+ "service_role_key_in_client_env",
521
+ "service_role_key_in_client_code"
522
+ ],
523
+ "status": "implemented"
524
+ },
525
+ {
526
+ "id": "repo-grant-review",
527
+ "title": "Grants and function privileges",
528
+ "appliesTo": "Supabase projects using the named feature.",
529
+ "text": "The audit has checks for Data API grants and SECURITY DEFINER functions. Review the emitted evidence and unsupported cases.",
530
+ "evidence": "Run viberaven audit --vercel-supabase --json; report only checks that actually ran.",
531
+ "sources": [
532
+ "grants",
533
+ "functions"
534
+ ],
535
+ "ruleIds": [
536
+ "supabase-data-api-grants",
537
+ "supabase-security-definer-functions"
538
+ ],
539
+ "status": "implemented"
540
+ }
541
+ ],
542
+ "live-checks": [
543
+ {
544
+ "id": "live-relation-policy",
545
+ "title": "Selected relation and policy metadata",
546
+ "appliesTo": "Supabase projects using the named feature.",
547
+ "text": "Planned adapter: selected schemas, relation RLS flags and bounded policy metadata. No application rows, query logs, samples or function execution.",
548
+ "evidence": "Future timestamped, project-bound metadata receipt; not implemented in P1.",
549
+ "sources": [
550
+ "rls",
551
+ "mcp"
552
+ ],
553
+ "capability": "supabase-catalog-rls",
554
+ "status": "planned",
555
+ "scope": "catalog-metadata"
556
+ },
557
+ {
558
+ "id": "live-grants",
559
+ "title": "Table and function grant metadata",
560
+ "appliesTo": "Supabase projects using the named feature.",
561
+ "text": "Planned adapter: selected relation grants and function identity/EXECUTE/security-mode metadata. Exclude function bodies and customer data.",
562
+ "evidence": "Future allowlisted catalog receipt; missing permissions must remain not_checked.",
563
+ "sources": [
564
+ "grants",
565
+ "functions"
566
+ ],
567
+ "capability": "supabase-catalog-grants",
568
+ "status": "planned",
569
+ "scope": "catalog-metadata"
570
+ }
571
+ ]
572
+ }
573
+ }
574
+ };
575
+
576
+ // ../providers/index.mjs
577
+ var PROVIDER_TOOL = {
578
+ name: "provider_playbook",
579
+ title: "Get a provider playbook",
580
+ description: `Plan setup and integration before implementing a feature that touches a provider. Returns versioned setup guidance, gotchas, dated changes, integration seams, existing repo checks and planned live checks with official sources. Available packs: ${Object.keys(registry_generated_default).sort().join(", ")}.
581
+ Limits: guidance only; does not connect to providers, read your project, run checks or verify that a feature works.`,
582
+ inputSchema: { type: "object", properties: { provider: { type: "string", minLength: 1, maxLength: 40, pattern: "^[a-z][a-z0-9-]*$", description: "Provider id, for example supabase. Unsupported ids return the available packs." } }, required: ["provider"], additionalProperties: false },
583
+ outputSchema: { type: "object", properties: { provider: { type: "string" }, packVersion: { type: "string" }, packHash: { type: "string" }, pack: { type: "object" }, verification: { type: "object" }, nextStep: { type: "object" } }, required: ["provider", "packVersion", "packHash", "pack", "verification", "nextStep"] },
584
+ annotations: { title: "Get a provider playbook", readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true }
585
+ };
586
+ var listProviders = () => Object.keys(registry_generated_default).sort();
587
+ function renderPlaybook(result) {
588
+ const { pack } = result;
589
+ const lines = [`${pack.displayName} provider playbook ${pack.packVersion} (reviewed ${pack.reviewedAt})`, pack.summary, "Guidance only. Repository and live checks: not checked.", ""];
590
+ for (const section of ["setup", "gotchas", "changes", "seams", "repo-checks", "live-checks"]) {
591
+ lines.push(section.toUpperCase());
592
+ for (const item of pack[section]) {
593
+ lines.push(`- ${item.title}: ${item.text}`, ` Applies: ${item.appliesTo}`, ` Evidence needed: ${item.evidence}`);
594
+ if (item.effectiveOn) lines.push(` Date: ${item.effectiveOn} (${item.status})`);
595
+ if (item.ruleIds) lines.push(` Repo rule IDs: ${item.ruleIds.join(", ")}`);
596
+ if (item.capability) lines.push(` Live capability: ${item.capability} (${item.status})`);
597
+ lines.push(` Sources: ${item.sources.map((id2) => pack.sources.find((source) => source.id === id2).url).join(" ")}`);
598
+ }
599
+ lines.push("");
600
+ }
601
+ lines.push("Limits:", ...pack.limits.map((limit) => `- ${limit}`), result.nextStep.message);
602
+ return lines.join("\n");
603
+ }
604
+ function providerPlaybook(args) {
605
+ if (!args || typeof args !== "object" || Array.isArray(args) || Object.keys(args).some((k) => k !== "provider") || typeof args.provider !== "string" || !/^[a-z][a-z0-9-]{0,39}$/.test(args.provider) || !Object.hasOwn(registry_generated_default, args.provider)) {
606
+ const field = args && typeof args === "object" && !Array.isArray(args) && Object.keys(args).some((k) => k !== "provider") ? "arguments" : "provider";
607
+ return { isError: true, content: [{ type: "text", text: `invalid_input: Choose a supported provider.
608
+ Field: ${field}
609
+ Next step: Select an available pack: ${listProviders().join(", ")}. No connection or check was attempted.
610
+ Example arguments: {"provider":"supabase"}` }] };
611
+ }
612
+ const entry = registry_generated_default[args.provider];
613
+ const pack = JSON.parse(JSON.stringify(entry.pack));
614
+ const structuredContent = {
615
+ provider: pack.provider,
616
+ packVersion: pack.packVersion,
617
+ packHash: entry.hash,
618
+ pack,
619
+ verification: { repo: "not_checked", live: "not_checked" },
620
+ nextStep: { phase: "P2-planned", accountRequiredForLive: true, message: "Use this guidance to plan the requested feature and run relevant local checks. Live connections are not implemented in this candidate; do not claim provider verification. Local guidance and checks need no account." }
621
+ };
622
+ return { isError: false, structuredContent, content: [{ type: "text", text: renderPlaybook(structuredContent) }] };
623
+ }
624
+
33
625
  // src/tools/readiness.ts
34
626
  var cwdSchema = {
35
627
  type: "object",
@@ -158,6 +750,292 @@ var actionTools = [
158
750
  }
159
751
  ];
160
752
 
753
+ // ../../shared/taskContract.ts
754
+ var TASK_CONTRACT_MAX_BYTES = 4800;
755
+ var condition = { type: "object", properties: {
756
+ id: { type: "string", pattern: "^[a-z][a-z0-9_-]{0,39}$" },
757
+ description: { type: "string", minLength: 1, maxLength: 240, pattern: "\\S" }
758
+ }, required: ["id", "description"], additionalProperties: false };
759
+ var TASK_CONTRACT_SCHEMA = {
760
+ $schema: "http://json-schema.org/draft-07/schema#",
761
+ title: "VibeRaven Task contract v1",
762
+ type: "object",
763
+ description: "Declarative task definition, not executable commands or evidence. Runtime also enforces a 4800-byte UTF-8 limit and condition IDs unique across both lists.",
764
+ properties: {
765
+ schemaVersion: { const: 1 },
766
+ status: { type: "string", enum: ["draft", "ready"] },
767
+ request: { type: "string", minLength: 1, maxLength: 1200, pattern: "^\\S(?:[\\s\\S]*\\S)?(?![\\s\\S])" },
768
+ acceptance: { type: "array", items: condition, maxItems: 16, uniqueItems: true },
769
+ mustNotBreak: { type: "array", items: condition, maxItems: 16, uniqueItems: true },
770
+ scope: { type: "object", properties: {
771
+ environment: { type: "string", enum: ["local", "preview", "test-mode"] },
772
+ paths: { type: "array", minItems: 0, maxItems: 16, uniqueItems: true, items: {
773
+ type: "string",
774
+ minLength: 1,
775
+ maxLength: 200,
776
+ pattern: '^(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\\\:*?"<>|\\u0000-\\u001f])(?!/)(?!.*//)(?!.*[. ](?:/|$))[^/]+(?:/[^/]+)*$'
777
+ } },
778
+ providers: { type: "array", maxItems: 8, uniqueItems: true, items: { type: "string", pattern: "^[a-z][a-z0-9-]{0,39}$" } }
779
+ }, required: ["environment", "paths", "providers"], additionalProperties: false }
780
+ },
781
+ required: ["schemaVersion", "status", "request", "acceptance", "mustNotBreak", "scope"],
782
+ additionalProperties: false,
783
+ allOf: [{ if: { properties: { status: { const: "ready" } } }, then: { properties: {
784
+ acceptance: { minItems: 1 },
785
+ scope: { properties: { paths: { minItems: 1 } } }
786
+ } } }]
787
+ };
788
+ function validate(value, schema, path2) {
789
+ const fail = () => {
790
+ throw new Error(`Invalid Task contract at ${path2}.`);
791
+ };
792
+ if ("const" in schema && value !== schema.const) fail();
793
+ if (schema.enum && !schema.enum.includes(value)) fail();
794
+ if (schema.type === "object" && (!value || typeof value !== "object" || Array.isArray(value))) fail();
795
+ if (schema.type === "string" && typeof value !== "string") fail();
796
+ if (schema.type === "array" && !Array.isArray(value)) fail();
797
+ if (typeof value === "string" && (schema.minLength !== void 0 && [...value].length < schema.minLength || schema.maxLength !== void 0 && [...value].length > schema.maxLength || schema.pattern && !new RegExp(schema.pattern, "u").test(value))) fail();
798
+ if (Array.isArray(value)) {
799
+ if (schema.minItems !== void 0 && value.length < schema.minItems || schema.maxItems !== void 0 && value.length > schema.maxItems || schema.uniqueItems && new Set(value.map((v) => JSON.stringify(v))).size !== value.length) fail();
800
+ value.forEach((item, i) => {
801
+ if (schema.items) validate(item, schema.items, `${path2}[${i}]`);
802
+ });
803
+ } else if (value && typeof value === "object") {
804
+ const object = value;
805
+ for (const key of schema.required ?? []) if (!Object.hasOwn(object, key)) fail();
806
+ for (const key of Object.keys(object)) {
807
+ if (schema.additionalProperties === false && !Object.hasOwn(schema.properties ?? {}, key)) fail();
808
+ if (Object.hasOwn(schema.properties ?? {}, key)) validate(object[key], schema.properties[key], `${path2}.${key}`);
809
+ }
810
+ }
811
+ for (const clause of schema.allOf ?? []) {
812
+ let matches = true;
813
+ try {
814
+ validate(value, clause.if, path2);
815
+ } catch {
816
+ matches = false;
817
+ }
818
+ if (matches) validate(value, clause.then, path2);
819
+ }
820
+ }
821
+ function parseTaskContract(raw) {
822
+ const serialized = JSON.stringify(raw);
823
+ if (!serialized || Buffer.byteLength(serialized, "utf8") > TASK_CONTRACT_MAX_BYTES) throw new Error("Task contract exceeds 4800 UTF-8 bytes.");
824
+ validate(raw, TASK_CONTRACT_SCHEMA, "$");
825
+ const contract = JSON.parse(serialized);
826
+ const ids = [...contract.acceptance, ...contract.mustNotBreak].map((c) => c.id);
827
+ if (new Set(ids).size !== ids.length) throw new Error("Task condition IDs must be unique across acceptance and mustNotBreak.");
828
+ if (contract.request.length > 1200) throw new Error("Task request exceeds the account API limit of 1200 characters.");
829
+ return contract;
830
+ }
831
+ function draftTaskContract(request) {
832
+ return parseTaskContract({ schemaVersion: 1, status: "draft", request, acceptance: [], mustNotBreak: [], scope: { environment: "local", paths: [], providers: [] } });
833
+ }
834
+
835
+ // ../../shared/verificationPlan.ts
836
+ var VERIFICATION_PLAN_MAX_BYTES = 65536;
837
+ var HTTP_LIMITS = { bodyBytes: 8192, responseBytes: 8192, requestTimeoutMs: 2e3, totalResponseBytes: 32768 };
838
+ var httpMethods = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
839
+ var httpPathPattern = "^/(?!/)(?!.*%(?:0[0-9a-fA-F]|1[0-9a-fA-F]|20|7[fF]|5[cC]))[!-~]*$(?![\\s\\S])";
840
+ var httpHeaderPattern = "^(?:accept|content-type|stripe-signature|x-(?:fixture|test)-[a-z0-9-]{1,40})$(?![\\s\\S])";
841
+ var httpExpected = {
842
+ type: "object",
843
+ properties: { status: { type: "integer", minimum: 200, maximum: 599 }, json: {}, text: { type: "string", maxLength: HTTP_LIMITS.responseBytes } },
844
+ required: ["status"],
845
+ additionalProperties: false,
846
+ oneOf: [{ required: ["json"], not: { required: ["text"] } }, { required: ["text"], not: { required: ["json"] } }],
847
+ allOf: [{ if: { properties: { status: { enum: [204, 205, 304] } } }, then: { required: ["text"], properties: { text: { const: "" } }, not: { required: ["json"] } } }]
848
+ };
849
+ var httpCase = {
850
+ type: "object",
851
+ properties: { request: {
852
+ type: "object",
853
+ properties: {
854
+ method: { enum: httpMethods },
855
+ path: { type: "string", minLength: 1, maxLength: 2048, allOf: [{ pattern: httpPathPattern }, { not: { pattern: "[\\\\#]" } }] },
856
+ headers: { type: "object", maxProperties: 8, propertyNames: { pattern: httpHeaderPattern }, additionalProperties: { type: "string", maxLength: 512, pattern: "^[ -~]*$(?![\\s\\S])" } },
857
+ body: { type: "string", maxLength: HTTP_LIMITS.bodyBytes }
858
+ },
859
+ required: ["method", "path"],
860
+ additionalProperties: false,
861
+ allOf: [{ if: { properties: { method: { enum: ["GET", "HEAD"] } } }, then: { not: { required: ["body"] } } }]
862
+ }, expected: httpExpected },
863
+ required: ["request", "expected"],
864
+ additionalProperties: false,
865
+ allOf: [{ if: { properties: { request: { properties: { method: { const: "HEAD" } } } } }, then: { properties: { expected: { required: ["text"], properties: { text: { const: "" } }, not: { required: ["json"] } } } } }]
866
+ };
867
+ var id = { type: "string", pattern: "^[a-z][a-z0-9_-]{0,39}$" };
868
+ var verificationPathPattern = '^(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\\\:*?"<>|\\u0000-\\u001f])(?!/)(?!.*//)(?!.*[. ](?:/|$))[^/]+(?:/[^/]+)*$';
869
+ var path = { type: "string", minLength: 1, maxLength: 200, pattern: verificationPathPattern };
870
+ var common = { id, conditionId: id };
871
+ var VERIFICATION_PLAN_SCHEMA = {
872
+ $schema: "http://json-schema.org/draft-07/schema#",
873
+ title: "VibeRaven local verification plan v1",
874
+ type: "object",
875
+ properties: { schemaVersion: { const: 1 }, checks: { type: "array", minItems: 1, maxItems: 32, items: { oneOf: [
876
+ { type: "object", properties: {
877
+ ...common,
878
+ adapter: { const: "module" },
879
+ module: path,
880
+ export: { type: "string", pattern: "^[A-Za-z_$][A-Za-z0-9_$]{0,79}$" },
881
+ cases: { type: "array", minItems: 1, maxItems: 32, items: { type: "object", properties: { args: { type: "array", maxItems: 16 }, expected: {} }, required: ["args", "expected"], additionalProperties: false } }
882
+ }, required: ["id", "conditionId", "adapter", "module", "export", "cases"], additionalProperties: false },
883
+ { type: "object", properties: { ...common, adapter: { const: "node-test" }, entry: path, frozenPaths: { type: "array", minItems: 0, maxItems: 16, uniqueItems: true, items: path } }, required: ["id", "conditionId", "adapter", "entry", "frozenPaths"], additionalProperties: false },
884
+ { type: "object", properties: { ...common, adapter: { const: "http" }, module: path, export: { type: "string", pattern: "^[A-Za-z_$][A-Za-z0-9_$]{0,79}$" }, cases: { type: "array", minItems: 1, maxItems: 32, items: httpCase } }, required: ["id", "conditionId", "adapter", "module", "export", "cases"], additionalProperties: false }
885
+ ] } } },
886
+ required: ["schemaVersion", "checks"],
887
+ additionalProperties: false,
888
+ description: "Reviewed local observations, not commands or imported proof. Runtime also bounds JSON depth/UTF-8 bytes, including HTTP request/expected bodies to 8192 bytes, rejects unknown condition IDs, and restricts node-test to preservation conditions and frozen test-owned paths. HTTP factories return unlistened Node servers; sequential requests observe volatile state only. Runtime package/config files remain candidate inputs. Expected values remain in the host comparator. Coverage completeness is a human judgment."
889
+ };
890
+ function validVerificationPath(value) {
891
+ return typeof value === "string" && value.length <= 200 && new RegExp(verificationPathPattern, "u").test(value) && !value.split("/").some((p) => /^(?:con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(p));
892
+ }
893
+ function frozenVerificationPath(path2) {
894
+ return /^(?:tests?|__tests__)(?:\/|$)|(?:^|\/)[^/]+\.(?:test|spec)\.[^/]+$/i.test(path2);
895
+ }
896
+ function keys(value, required) {
897
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join(",") !== [...required].sort().join(",")) throw new Error("Invalid verification plan fields. Commands and evidence are not accepted.");
898
+ }
899
+ function boundedJson(value, depth = 0) {
900
+ if (depth > 12) throw new Error("Verification JSON exceeds depth 12.");
901
+ if (value === null || typeof value === "boolean" || typeof value === "string") return;
902
+ if (typeof value === "number" && Number.isFinite(value)) return;
903
+ if (Array.isArray(value)) {
904
+ if (value.length > 256) throw new Error("Verification JSON array exceeds 256 items.");
905
+ value.forEach((v) => boundedJson(v, depth + 1));
906
+ return;
907
+ }
908
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
909
+ if (Object.keys(value).length > 256) throw new Error("Verification JSON object exceeds 256 keys.");
910
+ for (const [k, v] of Object.entries(value)) {
911
+ if (["__proto__", "prototype", "constructor"].includes(k)) throw new Error("Unsafe verification JSON key.");
912
+ boundedJson(v, depth + 1);
913
+ }
914
+ return;
915
+ }
916
+ throw new Error("Verification values must be finite JSON data.");
917
+ }
918
+ function parseVerificationPlan(raw, contract) {
919
+ boundedJson(raw);
920
+ if (Buffer.byteLength(JSON.stringify(raw), "utf8") > VERIFICATION_PLAN_MAX_BYTES) throw new Error("Verification plan exceeds 65536 UTF-8 bytes.");
921
+ keys(raw, ["schemaVersion", "checks"]);
922
+ if (raw.schemaVersion !== 1 || !Array.isArray(raw.checks) || !raw.checks.length || raw.checks.length > 32) throw new Error("Invalid verification plan checks.");
923
+ const seen = /* @__PURE__ */ new Set();
924
+ for (const c of raw.checks) {
925
+ if (!c || typeof c !== "object") throw new Error("Invalid verification check.");
926
+ if (c.adapter === "module" || c.adapter === "http") {
927
+ keys(c, ["id", "conditionId", "adapter", "module", "export", "cases"]);
928
+ if (!validVerificationPath(c.module) || typeof c.export !== "string" || !/^[A-Za-z_$][A-Za-z0-9_$]{0,79}$/.test(c.export) || !Array.isArray(c.cases) || !c.cases.length || c.cases.length > 32) throw new Error("Invalid module verification check.");
929
+ for (const test of c.cases) {
930
+ if (c.adapter === "module") {
931
+ keys(test, ["args", "expected"]);
932
+ if (!Array.isArray(test.args) || test.args.length > 16) throw new Error("Invalid module arguments.");
933
+ } else validateHttpCase(test);
934
+ }
935
+ } else if (c.adapter === "node-test") {
936
+ keys(c, ["id", "conditionId", "adapter", "entry", "frozenPaths"]);
937
+ if (!validVerificationPath(c.entry) || !frozenVerificationPath(c.entry) || !Array.isArray(c.frozenPaths) || c.frozenPaths.length > 16 || new Set(c.frozenPaths).size !== c.frozenPaths.length || c.frozenPaths.some((p) => !validVerificationPath(p) || !frozenVerificationPath(p))) throw new Error("Node-test entries/helpers must be frozen test-owned paths; runtime package/config files stay candidate inputs.");
938
+ if (contract && !contract.mustNotBreak.some((condition2) => condition2.id === c.conditionId)) throw new Error("Node-test checks support mustNotBreak only; use independent module observations for acceptance.");
939
+ } else throw new Error("Unsupported verification adapter. No shell commands are accepted.");
940
+ if (typeof c.id !== "string" || !/^[a-z][a-z0-9_-]{0,39}$/.test(c.id) || seen.has(c.id) || typeof c.conditionId !== "string" || !/^[a-z][a-z0-9_-]{0,39}$/.test(c.conditionId)) throw new Error("Invalid or duplicate verification ID.");
941
+ seen.add(c.id);
942
+ if (contract && ![...contract.acceptance, ...contract.mustNotBreak].some((condition2) => condition2.id === c.conditionId)) throw new Error("Unknown verification condition ID.");
943
+ }
944
+ return JSON.parse(JSON.stringify(raw));
945
+ }
946
+ function validateHttpCase(test) {
947
+ keys(test, ["request", "expected"]);
948
+ const request = test.request, expected = test.expected;
949
+ if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("Invalid HTTP request.");
950
+ keys(request, ["method", "path", ..."headers" in request ? ["headers"] : [], ..."body" in request ? ["body"] : []]);
951
+ if (!httpMethods.includes(request.method) || typeof request.path !== "string" || request.path.length > 2048 || !new RegExp(httpPathPattern).test(request.path) || /[\\#]/.test(request.path)) throw new Error("Invalid HTTP method or origin-relative path.");
952
+ if ("body" in request && (typeof request.body !== "string" || Buffer.byteLength(request.body, "utf8") > HTTP_LIMITS.bodyBytes || ["GET", "HEAD"].includes(request.method))) throw new Error("Invalid HTTP request body.");
953
+ if ("headers" in request) {
954
+ const headers = request.headers;
955
+ if (!headers || typeof headers !== "object" || Array.isArray(headers) || Object.keys(headers).length > 8 || Object.entries(headers).some(([name, value]) => !new RegExp(httpHeaderPattern).test(name) || typeof value !== "string" || value.length > 512 || /[^ -~]/.test(value))) throw new Error("Invalid synthetic HTTP headers.");
956
+ }
957
+ if (!expected || typeof expected !== "object" || Array.isArray(expected)) throw new Error("Missing HTTP expectation.");
958
+ const hasJson = Object.hasOwn(expected, "json");
959
+ keys(expected, ["status", hasJson ? "json" : "text"]);
960
+ if (!Number.isInteger(expected.status) || expected.status < 200 || expected.status > 599 || !hasJson && typeof expected.text !== "string") throw new Error("Invalid HTTP expectation.");
961
+ if (Buffer.byteLength(hasJson ? JSON.stringify(expected.json) : expected.text, "utf8") > HTTP_LIMITS.responseBytes) throw new Error("HTTP expected body exceeds byte limit.");
962
+ if ((request.method === "HEAD" || [204, 205, 304].includes(expected.status)) && (hasJson || expected.text !== "")) throw new Error("HTTP response must have an empty text body.");
963
+ }
964
+
965
+ // ../../shared/workTools.ts
966
+ var cwd2 = { type: "string", minLength: 1, maxLength: 4096 };
967
+ var taskId = { type: "string", pattern: "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$" };
968
+ var WORK_TOOLS = [
969
+ {
970
+ name: "viberaven_work_start",
971
+ description: "Save a versioned Task contract and run a free local check without login, network, edits or payment. Prefer contract; request alone saves a draft with unknown acceptance. No credentials or shell command fields. Review the returned contract before approving resume. Resume shares its short request and redacted results with the account; the full definition stays local. Provider and non-local contracts are planning only.",
972
+ inputSchema: { type: "object", properties: { cwd: cwd2, contract: TASK_CONTRACT_SCHEMA, request: { type: "string", minLength: 1, maxLength: 1200 }, cli: { type: "string", enum: ["claude", "codex", "gemini"] }, access: { type: "string", enum: ["ask", "approve"] } }, required: ["cli", "access"], oneOf: [{ required: ["contract"], not: { required: ["request"] } }, { required: ["request"], not: { required: ["contract"] } }], additionalProperties: false }
973
+ },
974
+ {
975
+ name: "viberaven_work_resume",
976
+ description: "Resume the SAME saved task through account sign-in, quota or payment. Set approvedContract=true only after explicit human approval of its exact acceptance, must-not-break conditions and declared scope. A draft can be upgraded with contract before any job exists; its request must stay identical. Never authorize sign-in or payment for the person. Execution state is separate from independent verification observations; agent success is not condition proof. Scope declarations are not an enforced sandbox.",
977
+ inputSchema: { type: "object", properties: { cwd: cwd2, taskId, contract: TASK_CONTRACT_SCHEMA, approvedContract: { type: "boolean" } }, required: ["taskId"], additionalProperties: false }
978
+ },
979
+ {
980
+ name: "viberaven_work_status",
981
+ description: "Read the saved Task contract, execution state and independent verification receipts locally without account, network, edits or payment. Current worktree changes invalidate checked proof; missing observations stay not_checked. Checked conditions separately report passed/failed outcomes. Historical agent results do not verify conditions.",
982
+ inputSchema: { type: "object", properties: { cwd: cwd2, taskId }, required: ["taskId"], additionalProperties: false }
983
+ },
984
+ {
985
+ name: "viberaven_work_prepare",
986
+ description: "Before implementing a local Node feature, freeze reviewed expected behavior and actual dirty/untracked baseline. Supports module comparisons, sequential HTTP requests to an isolated local server factory, and frozen Node preservation tests. No login or network; no commands or imported proof. MCP plans are limited to 4800 UTF-8 bytes; larger plans use the CLI JSON file (65536 bytes). No browser, database or live provider proof. Changed plans require a new task.",
987
+ inputSchema: { type: "object", properties: { cwd: cwd2, taskId, verification: VERIFICATION_PLAN_SCHEMA }, required: ["taskId", "verification"], additionalProperties: false }
988
+ },
989
+ {
990
+ name: "viberaven_work_verify",
991
+ description: "Run or resume the SAME frozen plan using the locally available pinned Docker image only. Set approvedVerification=true only after human review/approval. Network is disabled and no dependencies are installed. No login or billing. Missing conditions, dependencies or Docker remain not_checked; completed receipts are reused for the identical candidate. Coding-agent success is not proof.",
992
+ inputSchema: { type: "object", properties: { cwd: cwd2, taskId, approvedVerification: { type: "boolean" } }, required: ["taskId", "approvedVerification"], additionalProperties: false }
993
+ },
994
+ {
995
+ name: "viberaven_work_report",
996
+ description: "Export a bounded local draft proof report with Markdown from current integrity-checked verification receipts. Read-only: no login, network, Docker, agent or GitHub execution. Failed and unknown evidence remain explicit; agent success is not proof. Not authoritative CI or a completed live PR pilot. Review redacted text before sharing; redaction is not a complete secret scanner.",
997
+ inputSchema: { type: "object", properties: { cwd: cwd2, taskId }, required: ["taskId"], additionalProperties: false }
998
+ }
999
+ ];
1000
+ var isWorkTool = (name) => WORK_TOOLS.some((tool) => tool.name === name);
1001
+ function buildWorkToolArgs(name, raw) {
1002
+ const invalid2 = () => {
1003
+ throw new Error("Invalid work-tool arguments. Use only the documented Task contract or taskId; no credentials or commands.");
1004
+ };
1005
+ if (!isWorkTool(name) || !raw || typeof raw !== "object" || Array.isArray(raw)) return invalid2();
1006
+ const args = raw;
1007
+ const action = name.slice("viberaven_work_".length);
1008
+ const allowed = action === "start" ? ["cwd", "request", "contract", "cli", "access"] : action === "resume" ? ["cwd", "taskId", "contract", "approvedContract"] : action === "prepare" ? ["cwd", "taskId", "verification"] : action === "verify" ? ["cwd", "taskId", "approvedVerification"] : ["cwd", "taskId"];
1009
+ if (Object.keys(args).some((key) => !allowed.includes(key))) return invalid2();
1010
+ if (args.cwd !== void 0 && (typeof args.cwd !== "string" || !args.cwd.trim() || args.cwd.length > 4096 || /[\0\r\n]/.test(args.cwd))) return invalid2();
1011
+ const out = ["work", action];
1012
+ if (action === "start") {
1013
+ if (args.contract === void 0 === (args.request === void 0) || !["claude", "codex", "gemini"].includes(args.cli) || !["ask", "approve"].includes(args.access)) return invalid2();
1014
+ if (args.request !== void 0) {
1015
+ if (typeof args.request !== "string") return invalid2();
1016
+ draftTaskContract(args.request);
1017
+ out.push("--request-base64", Buffer.from(args.request, "utf8").toString("base64url"));
1018
+ }
1019
+ out.push("--source", "mcp", "--cli", args.cli, "--access", args.access);
1020
+ } else {
1021
+ if (typeof args.taskId !== "string" || !new RegExp(taskId.pattern).test(args.taskId)) return invalid2();
1022
+ if (args.approvedContract !== void 0 && typeof args.approvedContract !== "boolean") return invalid2();
1023
+ out.push("--id", args.taskId);
1024
+ if (args.approvedContract === true) out.push("--approve-contract");
1025
+ if (action === "prepare") {
1026
+ const plan = JSON.stringify(parseVerificationPlan(args.verification));
1027
+ if (Buffer.byteLength(plan, "utf8") > 4800) throw new Error("MCP verification transport exceeds 4800 bytes. Use work prepare --verification <file.json>.");
1028
+ out.push("--verification-base64", Buffer.from(plan, "utf8").toString("base64url"));
1029
+ }
1030
+ if (action === "verify") {
1031
+ if (typeof args.approvedVerification !== "boolean") return invalid2();
1032
+ if (args.approvedVerification) out.push("--approve-verification");
1033
+ }
1034
+ }
1035
+ if (args.contract !== void 0) out.push("--contract-base64", Buffer.from(JSON.stringify(parseTaskContract(args.contract)), "utf8").toString("base64url"));
1036
+ return [...out, "--json"];
1037
+ }
1038
+
161
1039
  // src/tools/npm.ts
162
1040
  var npmTools = [
163
1041
  {
@@ -176,8 +1054,123 @@ var npmTools = [
176
1054
 
177
1055
  // src/lib/cli-runner.ts
178
1056
  var import_node_child_process = require("node:child_process");
179
- var import_node_fs = require("node:fs");
1057
+ var import_node_fs3 = require("node:fs");
1058
+ var import_node_path2 = require("node:path");
1059
+
1060
+ // src/lib/work-report-runner.ts
1061
+ var import_node_fs2 = require("node:fs");
1062
+ var import_node_module = require("node:module");
180
1063
  var import_node_path = require("node:path");
1064
+
1065
+ // ../../shared/workReportRunner.ts
1066
+ var import_node_fs = require("node:fs");
1067
+ var MAX_OUTPUT_BYTES = 65536;
1068
+ var REPORT_TIMEOUT_MS = 3e4;
1069
+ var workReportFailure = () => {
1070
+ const stdout = JSON.stringify({ error: "Local proof report unavailable. Check the matching installed CLI, task ID, saved state integrity and current source readability.", code: "work_report_unavailable" });
1071
+ return { stdout, stderr: "", exitCode: 1, text: `exit 1
1072
+ ${stdout}` };
1073
+ };
1074
+ function runWorkReportProcess(entry, args, cwd3, spawnFn2) {
1075
+ let canonicalCwd;
1076
+ try {
1077
+ if (cwd3 !== void 0 && (typeof cwd3 !== "string" || !cwd3.trim())) return Promise.resolve(workReportFailure());
1078
+ canonicalCwd = (0, import_node_fs.realpathSync)(cwd3 === void 0 ? process.cwd() : cwd3);
1079
+ } catch {
1080
+ return Promise.resolve(workReportFailure());
1081
+ }
1082
+ return new Promise((resolve2) => {
1083
+ let settled = false, stdoutBytes = 0, stderrBytes = 0;
1084
+ const chunks = [];
1085
+ let child;
1086
+ const finish = (result) => {
1087
+ if (!settled) {
1088
+ settled = true;
1089
+ clearTimeout(timer);
1090
+ resolve2(result);
1091
+ }
1092
+ };
1093
+ const fail = () => {
1094
+ if (settled) return;
1095
+ finish(workReportFailure());
1096
+ child?.kill();
1097
+ };
1098
+ const timer = setTimeout(fail, REPORT_TIMEOUT_MS);
1099
+ timer.unref();
1100
+ try {
1101
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(?:node_|npm_)/i.test(key) && key.toLowerCase() !== "viberaven_cli_path"));
1102
+ child = spawnFn2(process.execPath, [entry, ...args], { cwd: canonicalCwd, env, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
1103
+ child.stdout?.on("data", (chunk) => {
1104
+ if (settled) return;
1105
+ stdoutBytes += chunk.length;
1106
+ if (stdoutBytes > MAX_OUTPUT_BYTES - 8) return fail();
1107
+ chunks.push(Buffer.from(chunk));
1108
+ });
1109
+ child.stderr?.on("data", (chunk) => {
1110
+ if (settled) return;
1111
+ stderrBytes += chunk.length;
1112
+ if (stderrBytes > MAX_OUTPUT_BYTES) fail();
1113
+ });
1114
+ child.on("error", fail);
1115
+ child.on("close", (code) => {
1116
+ if (settled) return;
1117
+ try {
1118
+ const stdout = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks));
1119
+ const report = JSON.parse(stdout);
1120
+ const requestedId = args[args.indexOf("--id") + 1];
1121
+ if (code !== 0 || !report || Array.isArray(report) || report.reportVersion !== 1 || report.taskId !== requestedId || !["passed", "failed", "not_checked"].includes(report.outcome) || typeof report.markdown !== "string" || "error" in report) return finish(workReportFailure());
1122
+ finish({ stdout, stderr: "", exitCode: 0, text: `exit 0
1123
+ ${stdout.trim()}` });
1124
+ } catch {
1125
+ finish(workReportFailure());
1126
+ }
1127
+ });
1128
+ } catch {
1129
+ fail();
1130
+ }
1131
+ });
1132
+ }
1133
+
1134
+ // src/lib/work-report-runner.ts
1135
+ var within = (root, target) => {
1136
+ const rel = (0, import_node_path.relative)(root, target);
1137
+ return !rel || !(0, import_node_path.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(`..${import_node_path.sep}`);
1138
+ };
1139
+ function resolveInstalledCli(version, cwd3) {
1140
+ const override = process.env.VIBERAVEN_CLI_PATH;
1141
+ try {
1142
+ if (override !== void 0 && !(0, import_node_path.isAbsolute)(override)) throw new Error("Unavailable installed CLI");
1143
+ const selected = override ?? (0, import_node_path.join)((0, import_node_path.dirname)((0, import_node_module.createRequire)(__filename).resolve("@viberaven/cli/package.json")), "dist", "cli.js");
1144
+ const info = (0, import_node_fs2.lstatSync)(selected);
1145
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error("Unavailable installed CLI");
1146
+ const entry = (0, import_node_fs2.realpathSync)(selected);
1147
+ const root = (0, import_node_fs2.realpathSync)((0, import_node_path.join)((0, import_node_path.dirname)(entry), ".."));
1148
+ if (entry !== (0, import_node_path.resolve)(selected) || entry !== (0, import_node_path.join)(root, "dist", "cli.js") || within((0, import_node_fs2.realpathSync)(cwd3), entry)) throw new Error("Unavailable installed CLI");
1149
+ const manifestPath = (0, import_node_path.join)(root, "package.json"), manifestInfo = (0, import_node_fs2.lstatSync)(manifestPath);
1150
+ if (!manifestInfo.isFile() || manifestInfo.isSymbolicLink() || manifestInfo.size > 65536 || (0, import_node_fs2.realpathSync)(manifestPath) !== manifestPath) throw new Error("Unavailable installed CLI");
1151
+ const manifest = JSON.parse((0, import_node_fs2.readFileSync)(manifestPath, "utf8"));
1152
+ if (manifest.name !== "@viberaven/cli" || manifest.version !== version) throw new Error("Unavailable installed CLI");
1153
+ return entry;
1154
+ } catch {
1155
+ if (override !== void 0) throw new Error("Matching installed CLI unavailable. Check VIBERAVEN_CLI_PATH, its exact version and installation outside the task repository.");
1156
+ return void 0;
1157
+ }
1158
+ }
1159
+ function runInstalledWorkReport(args, cwd3, version, spawnFn2) {
1160
+ let entry, canonicalCwd;
1161
+ try {
1162
+ if (cwd3 !== void 0 && (typeof cwd3 !== "string" || !cwd3.trim())) return Promise.resolve(workReportFailure());
1163
+ canonicalCwd = (0, import_node_fs2.realpathSync)(cwd3 === void 0 ? process.cwd() : cwd3);
1164
+ const installed = resolveInstalledCli(version, canonicalCwd);
1165
+ if (!installed) return Promise.resolve(workReportFailure());
1166
+ entry = installed;
1167
+ } catch {
1168
+ return Promise.resolve(workReportFailure());
1169
+ }
1170
+ return runWorkReportProcess(entry, args, canonicalCwd, spawnFn2);
1171
+ }
1172
+
1173
+ // src/lib/cli-runner.ts
181
1174
  var CLI_PACKAGE = "@viberaven/cli";
182
1175
  var MCP_PACKAGE = "@viberaven/mcp";
183
1176
  var PLAIN_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
@@ -185,14 +1178,14 @@ var cachedVersion;
185
1178
  function mcpVersion() {
186
1179
  if (cachedVersion) return cachedVersion;
187
1180
  let found;
188
- for (let dir = __dirname, depth = 0; depth < 4 && !found; depth += 1, dir = (0, import_node_path.dirname)(dir)) {
1181
+ for (let dir = __dirname, depth = 0; depth < 4 && !found; depth += 1, dir = (0, import_node_path2.dirname)(dir)) {
189
1182
  try {
190
- const manifest = JSON.parse((0, import_node_fs.readFileSync)((0, import_node_path.join)(dir, "package.json"), "utf8"));
1183
+ const manifest = JSON.parse((0, import_node_fs3.readFileSync)((0, import_node_path2.join)(dir, "package.json"), "utf8"));
191
1184
  if (manifest.name === MCP_PACKAGE && typeof manifest.version === "string") found = manifest.version;
192
1185
  } catch {
193
1186
  }
194
1187
  }
195
- found ??= true ? "1.6.12" : void 0;
1188
+ found ??= true ? "1.7.1" : void 0;
196
1189
  if (!found || !PLAIN_VERSION.test(found)) {
197
1190
  throw new Error(`Could not read a valid ${MCP_PACKAGE} version (got ${JSON.stringify(found)}), so the matching ${CLI_PACKAGE} cannot be pinned.`);
198
1191
  }
@@ -230,11 +1223,11 @@ function safeStringArg(value, label) {
230
1223
  if (/[&|<>^%!"\r\n]/.test(value)) throw new Error(`Unsafe characters in ${label}`);
231
1224
  return value;
232
1225
  }
233
- function resolveCwd(cwd) {
234
- if (cwd === void 0 || cwd === null) return process.cwd();
235
- if (typeof cwd !== "string") throw new Error("Invalid cwd: expected string");
236
- if (!cwd.trim()) throw new Error("Invalid cwd: expected non-empty string");
237
- return cwd;
1226
+ function resolveCwd(cwd3) {
1227
+ if (cwd3 === void 0 || cwd3 === null) return process.cwd();
1228
+ if (typeof cwd3 !== "string") throw new Error("Invalid cwd: expected string");
1229
+ if (!cwd3.trim()) throw new Error("Invalid cwd: expected non-empty string");
1230
+ return cwd3;
238
1231
  }
239
1232
  function buildNpxCommand(args) {
240
1233
  if (process.platform === "win32") {
@@ -249,6 +1242,9 @@ function buildHealArgs(prefix, args) {
249
1242
  return cliArgs;
250
1243
  }
251
1244
  function buildToolArgs(name, args) {
1245
+ if (name === RLS_TOOL_NAME) return buildRlsToolArgs(args);
1246
+ if (isLiveTool(name)) return buildLiveToolArgs(name, args);
1247
+ if (isWorkTool(name)) return buildWorkToolArgs(name, args);
252
1248
  switch (name) {
253
1249
  case "viberaven_check_readiness":
254
1250
  return ["check", "--json"];
@@ -296,42 +1292,112 @@ function buildToolArgs(name, args) {
296
1292
  throw new Error(`Unknown VibeRaven tool: ${name}`);
297
1293
  }
298
1294
  }
299
- function runVibeRaven(args, cwd) {
300
- let npxArgs;
1295
+ function transportFailure(error, stderr = "") {
1296
+ return { stdout: "", stderr, exitCode: 1, transportError: true, text: `ERROR: ${error instanceof Error ? error.message : String(error)}` };
1297
+ }
1298
+ async function runVibeRaven(args, cwd3) {
1299
+ return (await runVibeRavenDetailed(args, cwd3)).text;
1300
+ }
1301
+ function runVibeRavenDetailed(args, cwd3) {
1302
+ if (args[0] === "work" && args[1] === "report") {
1303
+ try {
1304
+ return runInstalledWorkReport(args, cwd3, mcpVersion(), spawnFn);
1305
+ } catch {
1306
+ return Promise.resolve(workReportFailure());
1307
+ }
1308
+ }
1309
+ let built;
1310
+ let childCwd, env;
301
1311
  try {
302
- npxArgs = cliNpxArgs(args);
1312
+ childCwd = resolveCwd(cwd3);
1313
+ const installed = resolveInstalledCli(mcpVersion(), childCwd);
1314
+ if (args[0] === "rls-test" && !installed) return Promise.resolve(transportFailure(new Error("RLS testing requires a matching installed CLI outside the task repository, with optional PGlite installed next to it. Configure the local MCP host installation or VIBERAVEN_CLI_PATH; this tool does not download or install dependencies.")));
1315
+ built = installed ? { command: process.execPath, args: [installed, ...args], shell: false } : buildNpxCommand(cliNpxArgs(args));
1316
+ env = installed ? Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(?:node_|npm_)/i.test(key) && key.toLowerCase() !== "viberaven_cli_path")) : cliChildEnv();
303
1317
  } catch (error) {
304
- return Promise.resolve(`ERROR: ${error instanceof Error ? error.message : String(error)}`);
305
- }
306
- return new Promise((resolve) => {
307
- const built = buildNpxCommand(npxArgs);
308
- const child = spawnFn(built.command, built.args, {
309
- cwd: resolveCwd(cwd),
310
- env: cliChildEnv(),
311
- shell: built.shell,
312
- stdio: ["ignore", "pipe", "pipe"]
313
- });
1318
+ return Promise.resolve(transportFailure(error));
1319
+ }
1320
+ return new Promise((resolve2) => {
1321
+ let child;
1322
+ try {
1323
+ child = spawnFn(built.command, built.args, {
1324
+ cwd: childCwd,
1325
+ env,
1326
+ shell: built.shell,
1327
+ windowsHide: true,
1328
+ stdio: ["ignore", "pipe", "pipe"]
1329
+ });
1330
+ } catch (error) {
1331
+ resolve2(transportFailure(error));
1332
+ return;
1333
+ }
314
1334
  let stdout = "";
315
1335
  let stderr = "";
316
- child.stdout?.on("data", (chunk) => {
317
- stdout += chunk.toString();
318
- });
319
- child.stderr?.on("data", (chunk) => {
320
- stderr += chunk.toString();
321
- });
322
- child.on("error", (error) => resolve(`ERROR: ${error.message}`));
1336
+ const boundedRls = args[0] === "rls-test";
1337
+ const rlsChunks = { stdout: [], stderr: [] };
1338
+ let outputBytes = 0;
1339
+ let settled = false;
1340
+ let timer;
1341
+ const finish = (result) => {
1342
+ if (settled) return;
1343
+ settled = true;
1344
+ if (timer) clearTimeout(timer);
1345
+ resolve2(result);
1346
+ };
1347
+ const stopRls = (reason) => {
1348
+ finish(transportFailure(new Error(reason)));
1349
+ try {
1350
+ child.kill("SIGKILL");
1351
+ } catch {
1352
+ }
1353
+ };
1354
+ if (boundedRls) timer = setTimeout(() => stopRls("RLS test exceeded its 300-second aggregate time limit and was stopped; no partial result is reported as passed."), RLS_RUN_TIMEOUT_MS);
1355
+ const collect = (chunk, stream) => {
1356
+ if (settled) return;
1357
+ outputBytes += Buffer.byteLength(chunk);
1358
+ if (boundedRls && outputBytes > RLS_MAX_OUTPUT_BYTES) {
1359
+ stopRls("RLS test exceeded its combined output limit and was stopped; no partial result is reported as passed.");
1360
+ return;
1361
+ }
1362
+ if (boundedRls) {
1363
+ rlsChunks[stream].push(Buffer.from(chunk));
1364
+ return;
1365
+ }
1366
+ if (stream === "stdout") stdout += chunk.toString();
1367
+ else stderr += chunk.toString();
1368
+ };
1369
+ child.stdout?.on("data", (chunk) => collect(chunk, "stdout"));
1370
+ child.stderr?.on("data", (chunk) => collect(chunk, "stderr"));
1371
+ child.on("error", (error) => finish(transportFailure(error, boundedRls ? "" : stderr)));
323
1372
  child.on("close", (code) => {
1373
+ if (settled) return;
1374
+ if (code === null) {
1375
+ finish(transportFailure(new Error("CLI process ended without an exit code"), boundedRls ? "" : stderr));
1376
+ return;
1377
+ }
1378
+ if (boundedRls) {
1379
+ try {
1380
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
1381
+ stdout = decoder.decode(Buffer.concat(rlsChunks.stdout));
1382
+ stderr = decoder.decode(Buffer.concat(rlsChunks.stderr));
1383
+ } catch {
1384
+ finish(transportFailure(new Error("RLS test returned invalid UTF-8; no partial result is reported as passed.")));
1385
+ return;
1386
+ }
1387
+ }
324
1388
  const combined = `${stdout}${stderr}`.trim();
325
- resolve(`exit ${code ?? 1}${combined ? `
326
- ${combined}` : ""}`);
1389
+ finish({ stdout, stderr, exitCode: code ?? 1, text: `exit ${code ?? 1}${combined ? `
1390
+ ${combined}` : ""}` });
327
1391
  });
328
1392
  });
329
1393
  }
330
1394
 
331
1395
  // src/tools/index.ts
332
1396
  var [checkReadiness, verify, strictGate, gateResult, contextMap] = readinessTools;
1397
+ var SEMANTIC_FINDING_TOOLS = /* @__PURE__ */ new Set(["viberaven_check_readiness", "viberaven_verify", "viberaven_audit", "viberaven_strict_gate", "viberaven_gate_result"]);
333
1398
  var ALL_TOOLS = [
334
1399
  checkReadiness,
1400
+ RLS_TOOL,
335
1401
  verify,
336
1402
  ...auditTools,
337
1403
  ...rulesTools,
@@ -340,7 +1406,10 @@ var ALL_TOOLS = [
340
1406
  contextMap,
341
1407
  ...actionTools,
342
1408
  ...healTools,
343
- ...npmTools
1409
+ ...npmTools,
1410
+ ...WORK_TOOLS,
1411
+ PROVIDER_TOOL,
1412
+ ...LIVE_TOOLS
344
1413
  ];
345
1414
  function parseJsonObjectFromToolText(text) {
346
1415
  const start = text.indexOf("{");
@@ -351,16 +1420,41 @@ function parseJsonObjectFromToolText(text) {
351
1420
  return void 0;
352
1421
  }
353
1422
  }
1423
+ function isCompletedNegativeNpmVerdict(receipt) {
1424
+ if (!receipt || "error" in receipt) return false;
1425
+ const results = "results" in receipt ? receipt.results : [receipt];
1426
+ try {
1427
+ return Array.isArray(results) && results.length > 0 && results.every((item) => {
1428
+ if (!item || typeof item !== "object" || Array.isArray(item) || "error" in item) return false;
1429
+ return typeof item.name === "string" && Boolean(item.name.trim()) && ["ok", "not_found", "suspicious"].includes(item.verdict) && Array.isArray(item.reasons) && item.reasons.length > 0 && item.reasons.every((reason) => typeof reason === "string" && Boolean(reason.trim())) && item.registryUrl === `https://registry.npmjs.org/${encodeURIComponent(item.name)}` && typeof item.followUpCommand === "string" && Boolean(item.followUpCommand.trim());
1430
+ }) && results.some((item) => item.verdict !== "ok");
1431
+ } catch {
1432
+ return false;
1433
+ }
1434
+ }
354
1435
  async function callTool(name, args) {
1436
+ if (name === "provider_playbook") return providerPlaybook(args).content[0].text;
355
1437
  return runVibeRaven(buildToolArgs(name, args || {}), args?.cwd);
356
1438
  }
357
1439
  async function handleRequest(method, params) {
358
1440
  if (method === "tools/list") return { tools: ALL_TOOLS };
359
1441
  if (method === "tools/call") {
360
- const text = await callTool(params.name, params.arguments || {});
361
- const parsed = parseJsonObjectFromToolText(text);
1442
+ if (params.name === "provider_playbook") return providerPlaybook(params.arguments);
1443
+ const args = params.arguments || {};
1444
+ const cliArgs = buildToolArgs(params.name, args);
1445
+ const run = await runVibeRavenDetailed(cliArgs, args.cwd);
1446
+ if (params.name === RLS_TOOL_NAME) return buildRlsToolResponse(run);
1447
+ const { text, stdout, exitCode, transportError } = run;
1448
+ const parsed = parseJsonObjectFromToolText(stdout);
1449
+ const receipt = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
1450
+ const approvalRefusal = params.name === "viberaven_heal_apply" && receipt?.status === "refused_dangerous";
1451
+ const textAuditFinding = params.name === "viberaven_audit" && !cliArgs.includes("--json") && !transportError && /^VibeRaven Vercel\/Supabase audit\r?\nStatus: needs_work\r?\n/.test(stdout) && /^NEEDS_WORK [a-z][a-z0-9-]*\r?$/m.test(stdout);
1452
+ const semanticFinding = exitCode === 1 && (textAuditFinding || receipt && !receipt.error && (SEMANTIC_FINDING_TOOLS.has(params.name) || approvalRefusal));
1453
+ const npmFinding = params.name === "viberaven_validate_npm_package" && exitCode === 2 && !transportError && isCompletedNegativeNpmVerdict(receipt);
1454
+ const isError = transportError || cliArgs.includes("--json") && !receipt || Boolean(receipt?.error) || exitCode !== 0 && !semanticFinding && !npmFinding || isLiveTool(params.name) && isLiveToolFailure(exitCode, parsed);
362
1455
  return {
363
1456
  content: [{ type: "text", text }],
1457
+ ...isError ? { isError: true } : {},
364
1458
  ...parsed ? { structuredContent: parsed } : {}
365
1459
  };
366
1460
  }