@topline-build/harness-mcp 0.9.13 → 0.9.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  All notable customer-visible Build MCP changes are recorded here. A source change is not a published package or customer release.
4
4
 
5
+ ## 0.9.15 - 2026-11-11
6
+
7
+ - `platform_inspect_artifact_app` runs `node --check` on each `.js`, `.mjs` and `.cjs` source file, so a syntax error makes `packageReady` false with a `javascript_syntax_error` problem naming the file and line, instead of failing the build after deploy.
8
+ - Inspect also returns `warnings` for static page text that Topline's render smoke would refuse as sample or mock data (`rendered_text_rule:sample_or_mock_data_text`), with the file and the phrase.
9
+ - A source conflict error carries `currentSourceHash`, and a pending-operation error carries this session's `pendingOperationId` and `pendingKind`, when Topline sends them. `artifact_operation_pending` is marked retryable once the operation settles.
10
+
11
+ ## 0.9.14 - 2026-11-11
12
+
13
+ - `platform_wait_artifact_deploy` names the build's failure code (`artifact_deploy_failed:<code>`) instead of only `failed`, and its recovery says to read `platform_deploy_operation` for the build's own error instead of retrying the wait.
14
+ - `platform_inspect_artifact_app` runs the manifest and data-binding checks Topline's build would fail: every `datasets[]` entry needs a `name` and `route`, every `routes[]` entry a `path`, and each `./_artifact/data/<name>` the source fetches needs a matching dataset. `packageReady` is false and `problems` names each field or file until they are fixed.
15
+ - Descriptions match the server: with company tables on, workspace SQL without a scope runs against company tables; an approved review completes the build session (asking again returns `validation_already_completed`); `needs_fix` keeps it active; rendered smoke can report `passed_with_warnings`; and omitted `buildOk` / `typecheckOk` are read as not reported.
16
+
5
17
  ## 0.9.13 - 2026-11-10
6
18
 
7
19
  - New `platform_read_logs`, for Topline staff only: bounded, redacted reads of the platform API and worker logs and of one-off task logs (connector syncs, one-off scripts, route optimization, link migrations, a coding task's runtime lines). It forwards to the hosted Build MCP, which checks operator access and audits every read.
@@ -19,7 +19,7 @@ export function externalBuildHelperTools(annotate) {
19
19
  }, ["idempotencyKey", "budgetCents", "brief"]),
20
20
  tool("platform_read_build_session", "Read the owned build session and original pending operations. Does not start another coder or deployment.", session, ["sessionId"], true),
21
21
  tool("platform_close_build_session", "Stop new authoring and request pending-operation cancellation. Unknown effects retain their reservation; cancellation does not undo committed writes.", session, ["sessionId"]),
22
- tool("platform_run_artifact_workspace_sql", "Run guarded SQL using the exact session, version and retry key. Without scope, or scope \"artifact\", it reads and writes this app's own build-checkpoint and cache tables. With scope \"company\", it creates, changes or drops a company table in company_data, or changes its rows, at once with no confirmation step; check the catalog before creating one, and declare tables an app uses in manifest tables[]. The company scope needs the harness:company:tables:write permission on your sign-in and the build session. CREATE TABLE/ADD COLUMN require documentation (company tables: a description and sensitivity for every column). Enforced non-admin writes remain denied; unknown writes are never replayed.", {
22
+ tool("platform_run_artifact_workspace_sql", "Run guarded SQL using the exact session, version and retry key. Without scope, or scope \"artifact\", it reads and writes this app's own build-checkpoint and cache tables; when the build session's workspace.routing is company_tables there are no private tables and every statement runs against company tables, as with scope \"company\". A statement the database rejects returns sql_statement_failed:<SQLSTATE> (company tables: company_table_sql_failed:<SQLSTATE>) with a fixed hint. With scope \"company\", it creates, changes or drops a company table in company_data, or changes its rows, at once with no confirmation step; check the catalog before creating one, and declare tables an app uses in manifest tables[]. The company scope needs the harness:company:tables:write permission on your sign-in and the build session. CREATE TABLE/ADD COLUMN require documentation (company tables: a description and sensitivity for every column). Enforced non-admin writes remain denied; unknown writes are never replayed.", {
23
23
  ...mutation, scope: { type: "string", enum: ["artifact", "company"] },
24
24
  sql: { type: "string", minLength: 1, maxLength: 20000 }, purpose: { type: "string", minLength: 3, maxLength: 500 },
25
25
  params: { type: "object", additionalProperties: true }, maxRows: { type: "integer", minimum: 1, maximum: 5000 }, documentation: { type: "object" }, columnDocumentation: { type: "object" }
@@ -38,14 +38,14 @@ export function externalBuildHelperTools(annotate) {
38
38
  tool("platform_add_acceptance_check", "Add a required acceptance check bound to this build session and deployed revision. A semantic control query requires separate Build data-verification consent.", {
39
39
  ...mutation, description: { type: "string", minLength: 3, maxLength: 1000 }
40
40
  }, [...Object.keys(mutation), "description"]),
41
- tool("platform_run_acceptance_checks", "Run required acceptance checks for the exact current draft revision through the shared service. Pass counts cover acceptance checks only; renderedSmoke reports the latest rendered smoke for this version, which also gates validation.", mutation, Object.keys(mutation)),
41
+ tool("platform_run_acceptance_checks", "Run required acceptance checks for the exact current draft revision through the shared service. Pass counts cover acceptance checks only; renderedSmoke reports the latest rendered smoke for this version (passed, passed_with_warnings with qualityWarnings codes, failed with failingChecks, or not_run), which also gates validation.", mutation, Object.keys(mutation)),
42
42
  tool("platform_record_acceptance_review", "Record the builder's review of a reviewer-only acceptance check. A passed result is accepted only for a check whose latest result platform_run_acceptance_checks recorded as a skipped reviewer check for this version, so run the checks first. Does not impersonate the independent validator or remove required checks.", {
43
43
  ...mutation, checkId: id, status: { type: "string", enum: ["passed", "failed"] }, summary: { type: "string", minLength: 3, maxLength: 2000 }
44
44
  }, [...Object.keys(mutation), "checkId", "status", "summary"]),
45
45
  tool("platform_prepare_artifact_validation", "Prepare validation evidence for the exact private draft revision; missing required checks block readiness.", { ...session, artifactVersionId: id, deploymentRecordId: id, idempotencyKey: requestKey }, ["sessionId", "artifactVersionId", "deploymentRecordId"], true),
46
- tool("platform_request_artifact_validation", "Request the independent reviewer for the exact deployment and bounded evidence. Returns durable operation status; unavailable infrastructure leaves operator review required, never approval. waitMs is 0 to 1000 (milliseconds to wait before returning); poll platform_artifact_validation_status for longer reviews. An approved review marks the private draft ready for an operator to publish.", {
46
+ tool("platform_request_artifact_validation", "Request the independent reviewer for the exact deployment and bounded evidence. Returns durable operation status; unavailable infrastructure leaves operator review required, never approval. waitMs is 0 to 1000 (milliseconds to wait before returning); poll platform_artifact_validation_status for longer reviews. An approved review marks the private draft ready for an operator to publish and completes this build session; asking again returns validation_already_completed. A needs_fix review keeps the session active: fix, deploy a new version, smoke, then request a review of that version. If the draft isn't ready, the refusal names the blocker platform_prepare_artifact_validation reports.", {
47
47
  ...deployed, summary: { type: "string", minLength: 3, maxLength: 4000 }, waitMs: { type: "integer", minimum: 0, maximum: 1000, description: "Milliseconds to wait for the review before returning, 0 to 1000." },
48
- buildOk: { type: "boolean" }, typecheckOk: { type: "boolean" }, docImpact: { type: "string", enum: ["material", "none"] },
48
+ buildOk: { type: "boolean", description: "Your own local build result. Omit if you did not run one; the reviewer is told separately that Topline's trusted build deployed this version." }, typecheckOk: { type: "boolean", description: "Your own local typecheck result. Omit if you did not run one." }, docImpact: { type: "string", enum: ["material", "none"] },
49
49
  docImpactNotes: { type: "string", minLength: 12, maxLength: 2000 }, visualReview: { type: "object", additionalProperties: true }, dataValidation: { type: "object", additionalProperties: true }
50
50
  }, [...Object.keys(deployed), "summary", "docImpact", "docImpactNotes", "visualReview"]),
51
51
  tool("platform_artifact_validation_status", "Read the original validation result and pending prompts without starting another reviewer or deploy. operationId selects the review; the result names the artifactVersionId it reviewed, and a supplied artifactVersionId that differs is refused (validation_operation_version_mismatch). Use the operationId this build session's request returned; another session's operation is refused (validation_operation_not_found). Current authorization is rechecked before evidence delivery.", {
package/dist/index.d.ts CHANGED
@@ -42,7 +42,7 @@ type ToolProgressReporter = (progress: number, message: string) => void | Promis
42
42
  export type McpSurface = "build" | "topline" | "harness";
43
43
  export declare const DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
44
44
  export declare const BUILD_MCP_SERVER_NAME = "topline-build-stdio";
45
- export declare const HARNESS_MCP_VERSION = "0.9.13";
45
+ export declare const HARNESS_MCP_VERSION = "0.9.15";
46
46
  export declare const DEFAULT_OAUTH_SCOPES: readonly string[];
47
47
  /** The Topline server's scopes: Build and Workspace. Consent shows what the seat allows. */
48
48
  export declare const TOPLINE_OAUTH_SCOPES: readonly string[];
@@ -131,6 +131,17 @@ export declare function materializeBuildAssets(opts: HarnessMcpStdioOptions, inp
131
131
  export declare function inspectArtifactApp(opts: HarnessMcpStdioOptions, input: Record<string, unknown>): Promise<{
132
132
  ok: boolean;
133
133
  packageReady: boolean;
134
+ problems: {
135
+ code: string;
136
+ path: string;
137
+ detail: string;
138
+ }[];
139
+ warnings: {
140
+ code: string;
141
+ path: string;
142
+ phrase: string;
143
+ detail: string;
144
+ }[];
134
145
  serverManifestValidationRequired: boolean;
135
146
  appDir: string;
136
147
  platformAppDir: string;
@@ -153,6 +164,31 @@ export declare function inspectArtifactApp(opts: HarnessMcpStdioOptions, input:
153
164
  };
154
165
  nextAction: string;
155
166
  }>;
167
+ /**
168
+ * Round 11 P4: the checks Topline's server and trusted build run that a local inspect can repeat
169
+ * cheaply, so packageReady isn't true for a package the deploy will refuse: dataset and route
170
+ * fields the manifest needs, and ./_artifact/data/<name> references with no matching dataset.
171
+ */
172
+ export declare function localPreflightProblems(appDir: string, manifest: Record<string, unknown>): Promise<Array<{
173
+ code: string;
174
+ path: string;
175
+ detail: string;
176
+ }>>;
177
+ /**
178
+ * Round 12: a JavaScript syntax error passed inspect (packageReady true) and then failed the
179
+ * build. Check each source file the way the build's Node would, and name the file and line.
180
+ */
181
+ export declare function javascriptSyntaxProblems(appDir: string): Promise<Array<{
182
+ code: string;
183
+ path: string;
184
+ detail: string;
185
+ }>>;
186
+ export declare function renderedTextRuleWarnings(appDir: string): Promise<Array<{
187
+ code: string;
188
+ path: string;
189
+ phrase: string;
190
+ detail: string;
191
+ }>>;
156
192
  export declare function waitForArtifactDeploy(opts: HarnessMcpStdioOptions, input: Record<string, unknown>, onProgress?: ToolProgressReporter): Promise<Record<string, unknown>>;
157
193
  export declare function initArtifactApp(opts: HarnessMcpStdioOptions, input: Record<string, unknown>): Promise<{
158
194
  ok: boolean;
package/dist/index.js CHANGED
@@ -19,7 +19,7 @@ const MCP_SURFACES = ["build", "topline", "harness"];
19
19
  export const DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
20
20
  const DEFAULT_TIMEOUT_MS = 120_000;
21
21
  export const BUILD_MCP_SERVER_NAME = "topline-build-stdio";
22
- export const HARNESS_MCP_VERSION = "0.9.13";
22
+ export const HARNESS_MCP_VERSION = "0.9.15";
23
23
  export const DEFAULT_OAUTH_SCOPES = Object.freeze(["harness:artifact:read", "harness:artifact:write", "harness:artifact:deploy", "harness:artifact:delete"]);
24
24
  /** The Topline server's scopes: Build and Workspace. Consent shows what the seat allows. */
25
25
  export const TOPLINE_OAUTH_SCOPES = Object.freeze([
@@ -1153,9 +1153,14 @@ export async function inspectArtifactApp(opts, input) {
1153
1153
  const suppliedPlatformAppDir = optionalString(input, "platformAppDir");
1154
1154
  const platformAppDir = suppliedPlatformAppDir ? (suppliedPlatformAppDir === "." ? "." : validateArchivePrefix(suppliedPlatformAppDir)) : logicalArtifactAppDir(workspaceAppDir, manifest);
1155
1155
  const bundle = await packArtifactAppDirectory(absoluteAppDir, platformAppDir === "." ? "" : platformAppDir);
1156
+ const problems = await localPreflightProblems(absoluteAppDir, manifest);
1157
+ problems.push(...await javascriptSyntaxProblems(absoluteAppDir));
1158
+ const warnings = await renderedTextRuleWarnings(absoluteAppDir);
1156
1159
  return {
1157
1160
  ok: true,
1158
- packageReady: true,
1161
+ packageReady: problems.length === 0,
1162
+ problems,
1163
+ warnings,
1159
1164
  serverManifestValidationRequired: true,
1160
1165
  appDir: workspaceAppDir,
1161
1166
  platformAppDir,
@@ -1178,9 +1183,150 @@ export async function inspectArtifactApp(opts, input) {
1178
1183
  sha256: bundle.sha256,
1179
1184
  excluded: bundle.excluded
1180
1185
  },
1181
- nextAction: "Call platform_deploy_artifact_app with the same appDir and expectedBundleSha256 set to bundle.sha256 when this local package is ready to deploy."
1186
+ nextAction: problems.length
1187
+ ? `Fix the ${problems.length === 1 ? "problem" : "problems"} listed in problems (each names its field or file), then inspect again. Topline's build would refuse this package as it is.`
1188
+ : "Call platform_deploy_artifact_app with the same appDir and expectedBundleSha256 set to bundle.sha256 when this local package is ready to deploy."
1182
1189
  };
1183
1190
  }
1191
+ const PREFLIGHT_SCAN_EXTENSIONS = new Set([".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".html", ".json", ".py", ".txt"]);
1192
+ const PREFLIGHT_SKIP_DIRS = new Set(["node_modules", ".git", ".next", ".vite", ".turbo", ".cache"]);
1193
+ /**
1194
+ * Round 11 P4: the checks Topline's server and trusted build run that a local inspect can repeat
1195
+ * cheaply, so packageReady isn't true for a package the deploy will refuse: dataset and route
1196
+ * fields the manifest needs, and ./_artifact/data/<name> references with no matching dataset.
1197
+ */
1198
+ export async function localPreflightProblems(appDir, manifest) {
1199
+ const problems = [];
1200
+ const nonEmpty = (value) => typeof value === "string" && value.trim() !== "";
1201
+ const datasets = Array.isArray(manifest.datasets) ? manifest.datasets : [];
1202
+ datasets.forEach((dataset, index) => {
1203
+ const record = isRecord(dataset) ? dataset : {};
1204
+ for (const key of ["name", "route"]) {
1205
+ if (!nonEmpty(record[key]))
1206
+ problems.push({ code: "invalid_artifact_app_manifest", path: `datasets[${index}].${key}`, detail: `datasets[${index}].${key} must be a non-empty string${key === "route" ? " (the page's path, for example /_artifact/data/<name>)" : ""}` });
1207
+ }
1208
+ });
1209
+ const routes = Array.isArray(manifest.routes) ? manifest.routes : [];
1210
+ routes.forEach((route, index) => {
1211
+ if (!isRecord(route) || !nonEmpty(route.path))
1212
+ problems.push({ code: "invalid_artifact_app_manifest", path: `routes[${index}].path`, detail: `routes[${index}].path must be a non-empty string` });
1213
+ });
1214
+ const declared = new Set([
1215
+ ...datasets.filter(isRecord).map((dataset) => dataset.name),
1216
+ ...(Array.isArray(manifest.sourceBindings) ? manifest.sourceBindings : []).filter(isRecord).map((binding) => binding.name)
1217
+ ].filter((name) => typeof name === "string"));
1218
+ const reported = new Set();
1219
+ let scanned = 0;
1220
+ const visit = async (dir) => {
1221
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
1222
+ if (scanned > 5_000)
1223
+ return;
1224
+ const full = path.join(dir, entry.name);
1225
+ if (entry.isDirectory()) {
1226
+ if (!PREFLIGHT_SKIP_DIRS.has(entry.name))
1227
+ await visit(full);
1228
+ continue;
1229
+ }
1230
+ if (!entry.isFile() || !PREFLIGHT_SCAN_EXTENSIONS.has(path.extname(entry.name)))
1231
+ continue;
1232
+ scanned += 1;
1233
+ const content = await readFile(full, "utf8").catch(() => "");
1234
+ if (content.length > 2_000_000)
1235
+ continue;
1236
+ for (const match of content.matchAll(/\.\/_artifact\/data\/([A-Za-z0-9_-]+)/g)) {
1237
+ const rel = path.relative(appDir, full).replaceAll("\\", "/");
1238
+ const key = `${rel}:${match[1]}`;
1239
+ if (declared.has(match[1]) || reported.has(key))
1240
+ continue;
1241
+ reported.add(key);
1242
+ problems.push({ code: "undeclared_artifact_data_binding", path: rel, detail: `${rel} fetches ./_artifact/data/${match[1]}, but no datasets[] entry is named ${match[1]}. Declare it (with its route) or remove the reference.` });
1243
+ }
1244
+ }
1245
+ };
1246
+ await visit(appDir);
1247
+ return problems.slice(0, 25);
1248
+ }
1249
+ const SYNTAX_CHECK_EXTENSIONS = new Set([".js", ".mjs", ".cjs"]);
1250
+ const SYNTAX_CHECK_SKIP_DIRS = new Set([...PREFLIGHT_SKIP_DIRS, "dist", "build", "out", "vendor"]);
1251
+ async function listAppFiles(appDir, extensions, skipDirs, limit) {
1252
+ const out = [];
1253
+ const visit = async (dir) => {
1254
+ for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
1255
+ if (out.length >= limit)
1256
+ return;
1257
+ const full = path.join(dir, entry.name);
1258
+ if (entry.isDirectory()) {
1259
+ if (!skipDirs.has(entry.name))
1260
+ await visit(full);
1261
+ continue;
1262
+ }
1263
+ if (entry.isFile() && extensions.has(path.extname(entry.name)))
1264
+ out.push(full);
1265
+ }
1266
+ };
1267
+ await visit(appDir);
1268
+ return out;
1269
+ }
1270
+ function nodeCheck(file) {
1271
+ return new Promise((resolve) => {
1272
+ const child = spawn(process.execPath, ["--check", file], { stdio: ["ignore", "ignore", "pipe"] });
1273
+ let stderr = "";
1274
+ child.stderr?.on("data", (chunk) => { if (stderr.length < 4_000)
1275
+ stderr += String(chunk); });
1276
+ const timer = setTimeout(() => { child.kill(); resolve(null); }, 10_000);
1277
+ child.on("error", () => { clearTimeout(timer); resolve(null); });
1278
+ child.on("close", (code) => { clearTimeout(timer); resolve(code === 0 ? null : stderr); });
1279
+ });
1280
+ }
1281
+ /**
1282
+ * Round 12: a JavaScript syntax error passed inspect (packageReady true) and then failed the
1283
+ * build. Check each source file the way the build's Node would, and name the file and line.
1284
+ */
1285
+ export async function javascriptSyntaxProblems(appDir) {
1286
+ const problems = [];
1287
+ for (const file of await listAppFiles(appDir, SYNTAX_CHECK_EXTENSIONS, SYNTAX_CHECK_SKIP_DIRS, 200)) {
1288
+ const stderr = await nodeCheck(file);
1289
+ if (!stderr || !/SyntaxError/.test(stderr))
1290
+ continue;
1291
+ const rel = path.relative(appDir, file).replaceAll("\\", "/");
1292
+ const line = new RegExp(`${file.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}:(\\d+)`).exec(stderr)?.[1] ?? null;
1293
+ const message = /SyntaxError:[^\n]*/.exec(stderr)?.[0]?.slice(0, 200) ?? "SyntaxError";
1294
+ problems.push({ code: "javascript_syntax_error", path: line ? `${rel}:${line}` : rel, detail: `${rel}${line ? ` line ${line}` : ""}: ${message}` });
1295
+ if (problems.length >= 10)
1296
+ break;
1297
+ }
1298
+ return problems;
1299
+ }
1300
+ // The page-text rule the build's render smoke applies (sample_or_mock_data_text). Inspect can only
1301
+ // see static text, so a match is a warning: the build fails only if the rendered page shows it.
1302
+ const SAMPLE_DATA_TEXT_PATTERNS = [
1303
+ /\b(showing|using|displaying|rendering|loaded|fallback|placeholder)\s+(sample|demo|mock|placeholder|example)?\s*(data|dataset|rows|metrics|values)\b/i,
1304
+ /\b(sample|demo|mock|placeholder|example)\s+(data|dataset|rows|metrics|values)\b/i,
1305
+ /\b(template[-\s]?local|local[-\s]?(summary|tasks|events|rows|metrics|dataset))\b/i
1306
+ ];
1307
+ export async function renderedTextRuleWarnings(appDir) {
1308
+ const warnings = [];
1309
+ for (const file of await listAppFiles(appDir, new Set([".html", ".js", ".jsx", ".ts", ".tsx", ".mjs"]), SYNTAX_CHECK_SKIP_DIRS, 500)) {
1310
+ const content = await readFile(file, "utf8").catch(() => "");
1311
+ if (content.length > 2_000_000)
1312
+ continue;
1313
+ // Visible text only: HTML text between tags and quoted string literals, not identifiers or comments.
1314
+ const texts = [...content.matchAll(/>([^<>]{3,400})</g), ...content.matchAll(/(["'`])((?:(?!\1)[^\\\n]|\\.){3,400})\1/g)].map((m) => m[m.length - 1] ?? "");
1315
+ for (const text of texts) {
1316
+ const match = SAMPLE_DATA_TEXT_PATTERNS.map((pattern) => pattern.exec(text)).find(Boolean);
1317
+ if (!match)
1318
+ continue;
1319
+ const rel = path.relative(appDir, file).replaceAll("\\", "/");
1320
+ const phrase = match[0].slice(0, 80);
1321
+ warnings.push({ code: "rendered_text_rule:sample_or_mock_data_text", path: rel, phrase,
1322
+ detail: `${rel} contains "${phrase}". If the page shows this text, Topline's build refuses it as sample or mock data. Reword it (for example "synthetic figures") or show the real data.` });
1323
+ break;
1324
+ }
1325
+ if (warnings.length >= 10)
1326
+ break;
1327
+ }
1328
+ return warnings;
1329
+ }
1184
1330
  async function callHostedBuildTool(opts, name, input) {
1185
1331
  if (!servesBuild(opts))
1186
1332
  throw new Error(`${name}_requires_build_surface`);
@@ -1351,8 +1497,12 @@ export async function waitForArtifactDeploy(opts, input, onProgress) {
1351
1497
  if (typeof latest.nextSeq === "number")
1352
1498
  afterSeq = latest.nextSeq;
1353
1499
  if (latest.terminal === true) {
1354
- if (latest.successful !== true)
1355
- throw new Error(`artifact_deploy_failed:${String(latest.taskStatus ?? "failed")}`);
1500
+ if (latest.successful !== true) {
1501
+ // Round 11 P3: name the build's failure code, not just the task status.
1502
+ const failure = isRecord(latest.failure) ? latest.failure : {};
1503
+ const code = typeof failure.code === "string" && /^[a-z][a-z0-9_]{2,80}$/.test(failure.code) ? failure.code : String(latest.taskStatus ?? "failed");
1504
+ throw new Error(`artifact_deploy_failed:${code}`);
1505
+ }
1356
1506
  return latest;
1357
1507
  }
1358
1508
  const waitMs = typeof latest.nextPollAfterMs === "number" ? Math.min(Math.max(latest.nextPollAfterMs, 250), 10_000) : 2_000;
@@ -1959,7 +2109,7 @@ const BUILD_MCP_TOOLS = [
1959
2109
  },
1960
2110
  {
1961
2111
  name: "platform_inspect_artifact_app",
1962
- description: "Inspect local artifact paths and package boundaries without authenticating, uploading, or creating a remote draft.",
2112
+ description: "Inspect local artifact paths and package boundaries without authenticating, uploading, or creating a remote draft. Also runs the manifest and data-binding checks Topline's build would fail (datasets[].name and route, routes[].path, ./_artifact/data/<name> references with no matching dataset) and a node --check of each .js/.mjs/.cjs file (javascript_syntax_error with file and line); packageReady is false and problems lists each one until they are fixed. warnings lists static text the build's page-text rules would refuse if the page shows it.",
1963
2113
  annotations: mcpToolAnnotations("platform_inspect_artifact_app", { readOnly: true }),
1964
2114
  inputSchema: {
1965
2115
  type: "object",
@@ -1972,6 +2122,8 @@ const BUILD_MCP_TOOLS = [
1972
2122
  properties: {
1973
2123
  ok: { type: "boolean" },
1974
2124
  packageReady: { type: "boolean" },
2125
+ problems: { type: "array", items: { type: "object" }, description: "Checks Topline's build would fail: each has code, path (manifest field or file, with :line for javascript_syntax_error) and detail. packageReady is false while any remain." },
2126
+ warnings: { type: "array", items: { type: "object" }, description: "Static text that matches a rule Topline's render smoke applies to the page (rendered_text_rule:sample_or_mock_data_text), with the file and phrase. The build fails only if the rendered page shows it." },
1975
2127
  serverManifestValidationRequired: { type: "boolean" },
1976
2128
  appDir: { type: "string" },
1977
2129
  platformAppDir: { type: "string" },
@@ -2005,7 +2157,7 @@ const BUILD_MCP_TOOLS = [
2005
2157
  },
2006
2158
  {
2007
2159
  name: "platform_wait_artifact_deploy",
2008
- description: "Wait for a durable deployment operation and stream server-derived progress.",
2160
+ description: "Wait for a durable deployment operation and stream server-derived progress. A failed deploy returns artifact_deploy_failed:<failure code>; read platform_deploy_operation for the build's own error (failure.detail) and next step. A successful deploy returns the session's next sourceHash for the following deploy.",
2009
2161
  annotations: mcpToolAnnotations("platform_wait_artifact_deploy", { readOnly: true, openWorld: true }),
2010
2162
  inputSchema: { type: "object", properties: { artifactId: { type: "string", format: "uuid" }, operationId: { type: "string", format: "uuid" }, timeoutSeconds: { type: "integer", minimum: 1, maximum: 900 } }, required: ["artifactId", "operationId"], additionalProperties: false },
2011
2163
  outputSchema: { type: "object", properties: { ok: { type: "boolean" }, phase: { type: "string" }, artifactId: { type: "string" }, operationId: { type: "string" }, taskStatus: { type: "string" }, progress: { type: "number" }, terminal: { type: "boolean" }, successful: { type: "boolean" }, events: { type: "array", items: { type: "object" } } }, required: ["ok", "phase", "artifactId", "operationId", "taskStatus", "progress", "terminal", "successful", "events"] }
@@ -2340,6 +2492,9 @@ function withRecoveryOutputSchema(value) {
2340
2492
  retryable: { type: "boolean" },
2341
2493
  recoveryAction: { type: "string" },
2342
2494
  signInUrl: { type: "string" },
2495
+ currentSourceHash: { type: "string" },
2496
+ pendingOperationId: { type: "string" },
2497
+ pendingKind: { type: "string" },
2343
2498
  ...(DOMAIN_FORWARD_TOOLS.has(tool.name) ? { recovery: { type: "object", additionalProperties: true } } : {})
2344
2499
  },
2345
2500
  required: ["code", "message", "retryable", "recoveryAction"],
@@ -2402,6 +2557,9 @@ const BUILD_MCP_RECOVERY_ERROR_VALUES = {
2402
2557
  build_session_id_required: { retryable: false, recoveryAction: "The fields named after the code only work inside a build session. Remove them for a plain deploy of an app you created over MCP, or start a session and pass its sessionId." },
2403
2558
  artifact_external_session_active: { retryable: false, recoveryAction: "An open build session holds this app. If it is yours, pass its sessionId; otherwise close it with platform_close_build_session or wait for it to end." },
2404
2559
  artifact_deploy_wait_timeout: { retryable: true, recoveryAction: "Call platform_wait_artifact_deploy again with the same artifactId and operationId." },
2560
+ // Round 11 P3: the wait names the failure code; the detail (the build's own error) is on the operation.
2561
+ artifact_deploy_failed: { retryable: false, recoveryAction: "The deploy finished and failed; the code after artifact_deploy_failed names why. Call platform_deploy_operation with the same artifactId and operationId for failure.detail (the build's own error) and failure.nextAction. Fix the source, run platform_inspect_artifact_app, then deploy again. Retrying the wait or redeploying the same source fails the same way." },
2562
+ validation_already_completed: { retryable: false, recoveryAction: "A review already approved this version and completed the build session. Don't request another review or start a new session to repeat it; read the verdict with platform_artifact_validation_status. Publishing is the person's step in Topline." },
2405
2563
  artifact_delete_plan_stale: { retryable: true, recoveryAction: "Call platform_plan_artifact_draft_delete again, review the new effects, and use its planToken." },
2406
2564
  artifact_app_bundle_changed_after_inspection: { retryable: true, recoveryAction: "Call platform_inspect_artifact_app again, review the new bundle hash, then retry deployment with that hash." },
2407
2565
  artifact_app_bundle_hardlink_forbidden: { retryable: false, recoveryAction: "Replace the hard link with a regular file copied into appDir, then inspect again." },
@@ -2416,8 +2574,8 @@ const BUILD_MCP_RECOVERY_ERROR_VALUES = {
2416
2574
  // Stale preconditions: the same input can never succeed, whatever HTTP status an older Topline sends.
2417
2575
  artifact_version_conflict: { retryable: false, recoveryAction: "The session moved to a newer version. Read the session (platform_read_build_session). A build session always starts from the app's current version; Build MCP can't check out an older saved version, so to go back, deploy source you saved before (or ask the coding agent in Topline to go back to version N). For a refused deploy: keep your local edits, run platform_inspect_artifact_app again, then deploy with the current artifactVersionId and the new inspectedSourceHash. For a refused validation request: don't deploy again. Wait for the current version's deploy to settle (platform_deploy_operation), run its checks and smoke, prepare it with platform_prepare_artifact_validation, then call platform_request_artifact_validation with that prepared evidence." },
2418
2576
  build_session_deployment_arguments_required: { retryable: false, recoveryAction: "Inside a build session a deploy needs artifactVersionId, idempotencyKey, and the inspectedSourceHash and expectedBundleSha256 that platform_inspect_artifact_app returned. The fields named after the code are missing; add them and call again." },
2419
- artifact_source_conflict: { retryable: false, recoveryAction: "inspectedSourceHash no longer matches the session's source fence. Read the session for its current sourceHash (or check out again into a new directory), keep your local edits, inspect again, then deploy with the fresh hash." },
2420
- artifact_operation_pending: { retryable: false, recoveryAction: "Another operation on this app has not settled. Read it with platform_deploy_operation (a deploy that already landed settles on that read), or platform_read_build_session, then call this tool again once it is terminal." },
2577
+ artifact_source_conflict: { retryable: false, recoveryAction: "inspectedSourceHash no longer matches the session's source fence. Use currentSourceHash from this error when present, or read the session for its current sourceHash (or check out again into a new directory). Keep your local edits, inspect again, then deploy with the fresh hash." },
2578
+ artifact_operation_pending: { retryable: true, recoveryAction: "Another operation on this app has not settled. Read it with platform_deploy_operation, using pendingOperationId from this error when present (a deploy that already landed settles on that read), or platform_read_build_session, then call this tool again once it is terminal." },
2421
2579
  artifact_deploy_in_flight: { retryable: true, recoveryAction: "A deploy for this app is still running. Wait until platform_deploy_operation says it is terminal, then retry the call that was refused (checkout, delete or deploy)." },
2422
2580
  artifact_logs_deployment_not_found: { retryable: false, recoveryAction: "There is no deployment to read runtime logs from yet. For a failed build, read platform_deploy_operation: its failure field carries the build error." }
2423
2581
  };
@@ -2429,13 +2587,35 @@ export function structuredToolError(message) {
2429
2587
  const selected = BUILD_MCP_RECOVERY_ERRORS[code] ?? { retryable, recoveryAction: !retryable && /^platform_harness_http_error:4|^platform_mcp_tool_error:/.test(message)
2430
2588
  ? "Topline refused this request as sent. Read the code, correct the input or state it names, then call the tool again; the same input fails the same way."
2431
2589
  : "Inspect the code and message, correct the input if needed, then retry the same tool." };
2432
- const structuredContent = { ok: false, error: { code, message, ...selected } };
2590
+ const structuredContent = { ok: false, error: { code, message, ...selected, ...conflictFieldsFromMessage(message) } };
2433
2591
  return {
2434
2592
  content: [{ type: "text", text: JSON.stringify(structuredContent, null, 2) }],
2435
2593
  structuredContent,
2436
2594
  isError: true
2437
2595
  };
2438
2596
  }
2597
+ /** Round 12 Q5: Topline names the value a conflict needs (value-free hashes and ids); lift them onto the error. */
2598
+ function conflictFieldsFromMessage(message) {
2599
+ const http = /^platform_harness_http_error:\d{3}:(.*)$/s.exec(message);
2600
+ if (!http)
2601
+ return {};
2602
+ let body;
2603
+ try {
2604
+ body = JSON.parse(http[1]);
2605
+ }
2606
+ catch {
2607
+ return {};
2608
+ }
2609
+ if (!isRecord(body))
2610
+ return {};
2611
+ const out = {};
2612
+ for (const key of ["currentSourceHash", "pendingOperationId", "pendingKind"]) {
2613
+ const value = body[key];
2614
+ if (typeof value === "string" && /^[A-Za-z0-9_:.-]{1,128}$/.test(value))
2615
+ out[key] = value;
2616
+ }
2617
+ return out;
2618
+ }
2439
2619
  /** The code Topline put inside a wrapped tool error: JSON `{ error: { code } }`, `{ error: "code" }`, or a leading code token. */
2440
2620
  function hostedToolErrorCode(inner) {
2441
2621
  try {