Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

chore: remove code comments

Raule824ed80cd2d
diff --git a/apps/erp/app/routes/api+/v1+/lib/args-envelope.test.ts b/apps/erp/app/routes/api+/v1+/lib/args-envelope.test.ts
index c8bcc68b23..209944f860 100644
--- a/apps/erp/app/routes/api+/v1+/lib/args-envelope.test.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/args-envelope.test.ts
@@ -1,17 +1,6 @@
import { describe, expect, it } from "vitest";
import { unwrapArgsEnvelope } from "./args-envelope";
-// The published MCP instructions taught `arguments: { args: {...} }`, which only
-// operations declaring an `args` object can take — for every other one the
-// envelope IS the payload, so each declared field arrived undefined and
-// validation rejected the call. The unwrap runs before validation, so it has to
-// be exact about which bodies it rewrites.
-//
-// Note the asymmetry (see .claude/rules/mcp-tools-reference.md): the opposite
-// compatibility path — a flat body sent to a WRAPPED schema — lives in
-// `jsonSchemaInput` and applies only when the wrapper is the sole required
-// property. Nothing here should widen that.
-
const flatSchema = {
type: "object",
properties: {
@@ -45,8 +34,6 @@ describe("unwrapArgsEnvelope", () => {
});
it("does not unwrap when args sits beside another key", () => {
- // Sibling keys mean the caller addressed real parameters; the dispatcher's
- // own `args` handling owns that shape.
const body = { args: { limit: 10 }, jobId: "job_1" };
expect(unwrapArgsEnvelope({ schema: flatSchema }, body)).toBe(body);
});
diff --git a/apps/erp/app/routes/api+/v1+/lib/args-envelope.ts b/apps/erp/app/routes/api+/v1+/lib/args-envelope.ts
index 6e0ad92571..51f0c6f274 100644
--- a/apps/erp/app/routes/api+/v1+/lib/args-envelope.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/args-envelope.ts
@@ -1,15 +1,3 @@
-// Kept out of call.server.ts so it can be tested without loading the service
-// registry (and with it the lingui-macro modules), the same split as
-// validation-issues.ts.
-
-/**
- * The published MCP instructions tell clients to send
- * `arguments: { args: { … } }`, and clients have copied that shape, but only the
- * operations that genuinely declare an `args` object want it — for every other
- * one the envelope IS the payload, so each declared field arrives undefined and
- * input validation rejects the call before the dispatcher ever unwraps it. Strip
- * a lone envelope here, where the operation's own schema says whether it is one.
- */
export function unwrapArgsEnvelope(
meta: { schema?: unknown },
args?: Record<string, unknown>
diff --git a/apps/erp/app/routes/api+/v1+/lib/call.server.ts b/apps/erp/app/routes/api+/v1+/lib/call.server.ts
index 8868be75f9..dcd26bd6c2 100644
--- a/apps/erp/app/routes/api+/v1+/lib/call.server.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/call.server.ts
@@ -32,11 +32,6 @@ export type CallResult =
| { success: true; data: unknown; count?: number }
| { success: false; error: string; errorKind: "database" | "execution" };
-/**
- * The edge function's own message, for a `functions.invoke()` failure only. Null
- * for every other Supabase error — a PostgREST error carries a `message` too, and
- * reading it here would rewrite error text the parity tests pin byte for byte.
- */
async function edgeFunctionMessage(error: unknown): Promise<string | null> {
const candidate = error as { name?: unknown; context?: unknown };
if (candidate?.name !== "FunctionsHttpError" || !candidate.context)
@@ -103,14 +98,6 @@ export async function callOperation(
? (err.data as { supabase?: unknown } | undefined)?.supabase
: undefined;
if (supabase) {
- // The caller gets a fixed message from the closed set in database-errors.ts
- // — never the serialized PostgREST body (which names columns, constraints
- // and values) and never an edge function's own text, both of which are
- // server-authored strings this surface should not echo (CWE-209). The full
- // detail goes to the server log instead, keyed by operation name, and an
- // edge function's message is read off its unread Response so the log has
- // the rule that actually fired ("The process is not batchable") rather than
- // an empty `{"name":"FunctionsHttpError","context":{}}`.
const edgeMessage = await edgeFunctionMessage(supabase);
logger.error("Operation failed", {
name,
diff --git a/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts b/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts
index 5c45306d7b..4a7252378e 100644
--- a/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts
@@ -5,10 +5,6 @@ import {
publicDatabaseError
} from "./database-errors";
-// The point of the closed set is that no server-authored text can reach an API
-// caller through it (CWE-209), so the tests that matter are the ones proving a
-// message with secrets in it cannot come back out.
-
describe("classifyDatabaseFailure", () => {
it.each([
["23505", "conflict"],
@@ -35,8 +31,6 @@ describe("classifyDatabaseFailure", () => {
});
it("classifies on structured fields, never on message text", () => {
- // A message that looks like a conflict must not be read as one — parsing text
- // is what makes a public string a function of a private one.
expect(
classifyDatabaseFailure({ message: "duplicate key value violates 23505" })
).toBe("unknown");
diff --git a/apps/erp/app/routes/api+/v1+/lib/database-errors.ts b/apps/erp/app/routes/api+/v1+/lib/database-errors.ts
index 9a01b120d8..fd21332a3f 100644
--- a/apps/erp/app/routes/api+/v1+/lib/database-errors.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/database-errors.ts
@@ -1,19 +1,3 @@
-// The PUBLIC face of a failed operation, for `callOperation`'s callers (MCP, the
-// in-app agent, the workflow dispatcher). Kept out of call.server.ts so it can be
-// tested without loading the service registry, the same split as
-// validation-issues.ts and args-envelope.ts.
-//
-// Nothing from the underlying error reaches the caller: neither a serialized
-// PostgREST body (whose code/details/hint name columns, constraints and values)
-// nor an edge function's own message text. The caller gets one of the fixed
-// strings below, chosen from the error's STRUCTURED fields only, and the full
-// detail is logged server-side where support can read it (CWE-209).
-//
-// The HTTP surface is a different path and is unchanged: an HTTP caller's 400
-// body is serialized from the ORPCError by the oRPC handler, never from
-// `CallResult`.
-
-/** What went wrong, at the granularity a caller can act on. */
export type DatabaseFailureKind =
| "conflict"
| "reference"
@@ -23,16 +7,8 @@ export type DatabaseFailureKind =
| "rule"
| "unknown";
-/**
- * The closed set. Every message is a fixed string — no interpolation, ever, or
- * this stops being a closed set.
- */
export const DATABASE_ERROR_MESSAGES: Record<DatabaseFailureKind, string> = {
conflict: "Database error: a record with these values already exists.",
- // Direction-neutral on purpose: 23503 fires both when a row references a
- // missing parent AND when a delete or update is blocked because dependent rows
- // still reference the target. Naming only the first sends the caller to the
- // wrong correction on the second.
reference:
"Database error: the operation would violate a reference between records.",
required: "Database error: a required field was missing.",
@@ -43,12 +19,6 @@ export const DATABASE_ERROR_MESSAGES: Record<DatabaseFailureKind, string> = {
unknown: "Database error: the operation could not be completed."
};
-/**
- * Classify from structured fields only — a Postgres SQLSTATE, or the error's own
- * constructor name for an edge-function failure. Message text is never parsed: it
- * is the thing being withheld, and matching on it would make the public message a
- * function of private text.
- */
export function classifyDatabaseFailure(error: unknown): DatabaseFailureKind {
const candidate = error as { code?: unknown; name?: unknown } | null;
if (candidate?.name === "FunctionsHttpError") return "rule";
@@ -70,7 +40,6 @@ export function classifyDatabaseFailure(error: unknown): DatabaseFailureKind {
}
}
-/** The public message for a failure. */
export function publicDatabaseError(error: unknown): string {
return DATABASE_ERROR_MESSAGES[classifyDatabaseFailure(error)];
}
diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
index 350f471522..2891f5b940 100644
--- a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
@@ -495,9 +495,6 @@ describe("dispatchOperation service-call contract (golden, ex-executeFunction pa
expect(r.dispatchError).toBeInstanceOf(ORPCError);
const orpcError = r.dispatchError as ORPCError<string, unknown>;
expect(orpcError.message).toBe("duplicate key value");
- // The raw error rides on the ORPCError: callOperation classifies it into a
- // public message and logs the detail, and the HTTP handler serializes it into
- // the 400 body.
expect(
(orpcError.data as { supabase?: unknown } | undefined)?.supabase
).toEqual(supabaseError);
@@ -509,9 +506,6 @@ describe("dispatchOperation service-call contract (golden, ex-executeFunction pa
spies.upsertNotificationPreference,
{ args: { channel: "email", enabled: true } }
);
- // userId rides along because the payload declares one: the field is stripped
- // from the published schema, so a caller cannot send it and the row used to be
- // written without it.
expect(r.calls).toEqual([
[
spies.FAKE_CLIENT,
@@ -687,10 +681,6 @@ describe("callOperation (the MCP/agent/workflow entry point)", () => {
});
it("maps a Supabase error to the errorKind:database envelope with a closed-set message", async () => {
- // The envelope shape is the parity contract; the TEXT deliberately is not.
- // It used to be `Database error: ${JSON.stringify(error)}`, which handed an
- // API caller the column, constraint and value out of the PostgREST body
- // (CWE-209). The detail now goes to the server log instead.
const supabaseError = { message: "boom", code: "XX000" };
spies.getAccountLedger.mockResolvedValue({
data: null,
diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts
index 49a44890f6..ac50e5dc2e 100644
--- a/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts
@@ -87,11 +87,6 @@ export function enrichWithAuthContext(
if (fields.includes("companyGroupId")) {
enriched.companyGroupId = context.companyGroupId;
}
- // Services that take the acting user as a FIELD of their args object (the
- // edge-function wrappers — batch-operations and friends) get it here; a
- // positional userId param is filled from context in the loop below instead.
- // Overwrite rather than fill, for the same reason as createdBy: the field is
- // stripped from the published schema, so a caller-supplied one is a forgery.
if (fields.includes("userId")) {
enriched.userId = context.userId;
}
@@ -366,9 +361,6 @@ export async function dispatchOperation(
if (result && typeof result === "object" && "data" in result) {
const r = result as { data: unknown; error?: unknown; count?: number };
if (r.error) {
- // The raw error rides along so callOperation can classify it into a public
- // message and log the detail, and so HTTP callers get the Postgres
- // code/details/hint the way Supabase REST does.
throw new ORPCError("BAD_REQUEST", {
message: supabaseErrorMessage(r.error),
data: { supabase: r.error }
diff --git a/apps/erp/test/mcp-tool-auth-injection.test.ts b/apps/erp/test/mcp-tool-auth-injection.test.ts
index dd73b9e7f5..e68ba6a8b7 100644
--- a/apps/erp/test/mcp-tool-auth-injection.test.ts
+++ b/apps/erp/test/mcp-tool-auth-injection.test.ts
@@ -4,19 +4,6 @@ import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import toolMetadataJson from "../app/routes/api+/mcp+/lib/tool-metadata.json";
-// Guard for the gap that broke every batch write over MCP (#1550 shipped the
-// batch tools; nothing exercised them through this surface). A service takes the
-// acting user either as a POSITIONAL `userId` param — which the dispatcher fills
-// straight from context — or as a FIELD of its payload object, the shape every
-// edge-function wrapper uses. `CONTEXT_PARAMS` strips that field from the
-// published schema on the assumption something supplies it, so unless the
-// manifest also marks the tool for injection the service is invoked with no
-// userId at all. In-app callers pass it explicitly, so the failure is invisible
-// until an API-key or MCP caller hits it.
-//
-// The contract this pins is already written down: .claude/rules/mcp-tools-reference.md
-// says companyId/userId come from the auth context and are injected server-side,
-// never trusted from tool arguments.
const MODULES_DIR = join(dirname(fileURLToPath(import.meta.url)), "../app/modules");
@@ -47,7 +34,6 @@ function serviceSources(module: string): string {
return joined;
}
-/** The text between the parens of `export async function <fn>(…)`, or null. */
function signatureOf(source: string, fn: string): string | null {
const match = new RegExp(
`export\\s+(?:async\\s+)?function\\s+${fn}\\s*\\(`
@@ -66,7 +52,6 @@ function signatureOf(source: string, fn: string): string | null {
return null;
}
-/** Split a parameter list on its top-level commas. */
function splitParams(signature: string): string[] {
const params: string[] = [];
let depth = 0;
@@ -87,13 +72,12 @@ function splitParams(signature: string): string[] {
const PAYLOAD_USER_ID = /(^|[{;,\s])userId\s*\??\s*:/;
-/** Does any non-positional param of this signature declare a `userId` field? */
function payloadDeclaresUserId(signature: string): boolean {
return splitParams(signature).some((param) => {
const colon = param.indexOf(":");
if (colon < 0) return false;
const name = param.slice(0, colon).trim().replace(/\?$/, "");
- if (name === "userId") return false; // positional — filled from context
+ if (name === "userId") return false;
return PAYLOAD_USER_ID.test(param.slice(colon + 1));
});
}
diff --git a/packages/api/src/manifest-types.ts b/packages/api/src/manifest-types.ts
index 02e639348b..14028d5918 100644
--- a/packages/api/src/manifest-types.ts
+++ b/packages/api/src/manifest-types.ts
@@ -12,9 +12,6 @@ export type AuthField =
| "companyGroupId"
| "createdBy"
| "updatedBy"
- /** The acting user, for services that take it as a field of their args object
- * rather than as a positional param. A positional `userId` is filled straight
- * from context by the dispatcher and never appears here. */
| "userId";
export type PermissionAction = "view" | "create" | "update" | "delete";
diff --git a/scripts/lib/service-metadata.ts b/scripts/lib/service-metadata.ts
index ab588d1cd0..09a31f4f07 100644
--- a/scripts/lib/service-metadata.ts
+++ b/scripts/lib/service-metadata.ts
@@ -1191,20 +1191,6 @@ function computeInjectAuth(
return ["companyId"];
}
-/**
- * A service takes the acting user one of two ways: as a positional `userId`
- * param, which the dispatcher fills straight from context, or as a FIELD of its
- * args object — the shape every edge-function wrapper uses
- * (`createJobOperationBatch`, `pickPickingListLine`, …). `CONTEXT_PARAMS` strips
- * that field from the published schema on the assumption something supplies it,
- * so without this the service is invoked with no userId at all and the edge
- * function rejects the payload. Deriving the flag from the signature keeps the
- * strip and the injection in step.
- *
- * A textual test of the param type is exact here: every userId-bearing payload
- * in the service layer is an inline object literal, and no type alias declares
- * one. Should that change, the manifest guard test fails rather than the tool.
- */
export function withPayloadUserId(
fields: AuthField[],
func: ParsedFunction