Skip to content

Six Checks Before You Trust Generated Code

Generated code often looks finished before it is correct. Run these six checks on every script, function or gizmo an assistant writes for KnowledgeLake, before you test it on a tenant.

Each check says what to look for and shows a bad and a good version. A short checklist for each surface follows.

At a glance

  1. Work item id: from the WorkItemId header, not the body.
  2. Secrets: in configuration, never in code.
  3. Failure fails: no caught exception followed by success.
  4. Exact names: buckets and keys match, values are strings.
  5. Real names: every endpoint is in your spec, every object is in the surface contract.
  6. Idempotent writes: set final values, never append or increment.

The six checks

1. Where does the work item id come from?

Call External API sends the work item id in the WorkItemId request header. It is not in the body unless you put it there. Code that reads it from the body gets nothing and fails late, or acts on the wrong work item.

Bad: id from the body
var body = await new StreamReader(req.Body).ReadToEndAsync();
var workItemId = JObject.Parse(body)["WorkItemId"];
Good: id from the header
if (!req.Headers.TryGetValue("WorkItemId", out var header) || !Guid.TryParse(header, out var workItemId))
{
    return new BadRequestObjectResult("Missing or invalid WorkItemId header");
}

In a Custom Step or Custom Event, the id is batch.BatchId. In routes and Liquid, it is WorkItemId.

2. Are secrets in configuration?

A token or key in source code leaks into every copy of the code. Look for any literal that looks like a token, password, function key or connection string.

Bad: token in code
config.AddApiKey("TempIdentityToken", "eyJhbGciOiJIUzI1NiIs...");
Good: token from configuration
var token = Environment.GetEnvironmentVariable("KnowledgeLakeApiToken");
if (string.IsNullOrEmpty(token)) throw new InvalidOperationException("KnowledgeLakeApiToken is not set");
config.AddApiKey("TempIdentityToken", token);

Put the value in app settings, environment variables or a key vault. Inside a workflow, read thresholds, URLs and keys with GlobalVariables.Get(name) instead of a literal, and mark a sensitive variable secret.

Important

Secret global variables are readable from workflow JavaScript. A script that copies a secret into metadata, an event property or an error message publishes it to everyone who can see that data. Use the value only where it is needed.

3. Does a failure fail?

A caught exception followed by success is a silent no-op. The workflow continues as if the work was done. Look at every catch block and every early exit.

Bad: the function reports success after an error
catch (Exception ex)
{
    log.LogError(ex.Message);
    return new OkObjectResult("done");
}
Good: the function fails the step
catch (Exception ex)
{
    log.LogError(ex, "FlagHighValueInvoices failed");
    return new BadRequestObjectResult(ex.Message);
}

Call External API fails the step on any non-2xx status. In a Custom Step, throw when the step must not continue. The step then fails and its queued changes are not applied.

Bad: the Custom Step swallows the error
try {
  var total = parseFloat(batch.Metadata['Index']['BatchTotal']);
} catch (e) { }
Good: the Custom Step stops with a clear message
var index = batch.Metadata['Index'] || {};
if (!index['BatchTotal']) {
  throw new Error('BatchTotal is missing on work item ' + batch.BatchId);
}
var total = parseFloat(String(index['BatchTotal']).replace(/[^0-9.\-]/g, '')) || 0;

If the work item must go to an exception queue instead, write a reason (for example General.ReviewReason) and let a route send it there.

4. Are bucket and key names exact?

Names are case-sensitive strings. Every metadata value is a string. An assistant often lowercases a name or writes a boolean.

Bad: wrong case, boolean value
builder.SetBatchMetadata('index', 'needsReview', true);
Good: exact names, string value
builder.SetBatchMetadata('Index', 'NeedsReview', 'Yes');

Compare every name in the code with the field list of your content type and your workflow. See The Work Item Model. The same rule applies to Custom Event properties: builder.SetEventProperty('invoiceTotal', String(total)), not a number.

5. Are the names real?

Plausible is not the same as present. Check every endpoint against your tenant's OpenAPI spec, and every script object against the surface's runtime contract.

Bad: neither fetch nor console exists in a Custom Step
var rate = fetch('https://api.example.com/rate');
console.log(rate);

A Custom Step cannot call the network. Fetch the value with a Call External API step first, then read it from ApiResults:

Good: read the API result from metadata
var raw = (batch.Metadata['ApiResults'] || {})['FxRate'] || '';
var rate = raw ? JSON.parse(raw).rates.USD : 0;

For API code, search the spec for each action name before you trust it:

Check that an action exists
grep -n '"/V1_KWorkItemAPI/UpsertWorkItemMetadata"' openapi.v2.json

No match means the action does not exist on your tenant. See Build with an AI Assistant for how to download the spec.

6. Are writes idempotent?

A step can run again: after a timeout, a retry, or a resubmit. Code that appends or increments gives a different result the second time.

Bad: increments on every run
var count = parseInt((batch.Metadata['General'] || {})['ReviewCount'] || '0', 10);
builder.SetBatchMetadata('General', 'ReviewCount', String(count + flagged));
Good: sets the value computed from the source
builder.SetBatchMetadata('General', 'ReviewCount', String(flagged));

Compute each value from its source on every run, and set it. In API code, use the Upsert...Metadata actions with the final value.

Custom Event steps repeat too

A Custom Event step that runs twice writes two events. Give your report a key that tolerates a repeat, such as the work item id plus the scopes.

Per-surface checklist

Custom Behavior

  • context is lowercase: context.username, context.usergroups, context.app. A capitalized Context object does not exist.
  • RuntimeValue is a string. A check box reads "true" or "false". Compare strings, not booleans.
  • Field names are the content type's field keys, exact and case-sensitive.
  • To reset another field, pass true as the third argument of SetFieldRuntimeValue so its behaviors do not fire.
  • Use SetFieldChoices(field, choices). Do not use the SetChoices shorthand.
  • The script also runs on the server (Index Your Documents, Run Indexing Behaviors, Start QC Task, Search bulk edit) with context.app set to "worker" and no user. Guard user-only logic.
  • No network, no console, no top-level return.

Search filter behavior

  • Only context.username exists. There is no usergroups or app here.
  • Use the SetFilter* methods.
  • Finish well inside 1.5 seconds.

Workflow route

  • The route is one expression, or a function you call at once: (function () { ... return true; })().
  • Read workItem, not batch. The id is WorkItemId and the name is Name.
  • A value set only per document does not appear in workItem.Metadata.

Custom Step

  • No network, no fetch, no require, no console, no top-level return.
  • Read from batch, write through builder. Writes apply when the script ends, unless the script calls builder.ApplyChanges().
  • Set routing values on the work item with builder.SetBatchMetadata, not only on documents.
  • When you delete or move documents, iterate a copy of batch.Documents or walk it backwards.
  • Guard each metadata level. A missing bucket is undefined.
  • GlobalVariables.Get(name) throws Global variable {name} was not found. if the variable does not exist. A || 'default' fallback covers an empty value only.

Custom Event

  • The only write is builder.SetEventProperty(key, value). The step cannot change the work item.
  • Every value is a string. Use String(x) for numbers and JSON.stringify(x) for objects.
  • Scopes come from the step's Scopes setting, not from the script. Avoid the words error, start and stop in scopes unless you mean them.
  • The script has 10 seconds and no PapaParse.

Your own function

  • The work item id comes from the WorkItemId header.
  • The token and URL come from configuration.
  • Every failure returns a non-2xx status.
  • Every action exists in your tenant's spec. Check Success on every response, and read Messages[].MessageKey on HTTP 412.

Custom Gizmo

  • Every external host the gizmo calls is in whitelist.txt.
  • Every external host allows the request in CORS. The gizmo runs in a sandbox, so requests are sent with Origin: null.
  • No inline <script> blocks and no inline event handlers such as onclick=. Put all code in main.js.
  • Read gizmo.Config only after gizmo.OnReceiveConfig fires.
  • Declare every API permission the gizmo uses with gizmo.DeclarePermissions.

Intuitive AI script

  • Return a graded confidence with result.SetResult(score). Do not return 1 for any match.
  • Match whole words, not substrings. A bare indexOf match on a vendor name picks the wrong subclass when one vendor name is part of another.
  • Score more than one signal (name, address, account number) when subclasses look alike.
  • Metadata is read-only (state.BatchProjection). Write only with result.SetDocumentMetadata. No network.

Custom Insight widget endpoint

  • The endpoint answers GET {base}/validate with HTTP 200 when the bearer token is right.
  • It checks the bearer token on every request.
  • It returns JSON in the published schema for the widget type, inside the connection's timeout.

Copy this into your assistant

Paste the block below after the assistant writes code. It asks the assistant to review its own work against the six checks before you do.

Review prompt for AI assistants
Review the code you wrote against these six checks. For each check, answer
PASS or FAIL, quote the line that decides it, and fix every FAIL.

1. Work item id: an endpoint called by Call External API reads it from the
   `WorkItemId` header, never the body. A Custom Step or Custom Event uses
   `batch.BatchId`. Routes and Liquid use `WorkItemId`.
2. Secrets: no token, password, key or connection string in code. Values come
   from app settings, environment variables, a key vault or a global variable.
   No secret is copied into metadata, an event property or an error message.
3. Failure fails: no catch block that ends in success. Endpoints return non-2xx
   on failure. Custom Step throws `new Error('clear message')`.
4. Exact names: every bucket, key, field and variable name matches the names I
   gave you, with the same case. Every value written is a string.
5. Real names: every API action is one I gave you from the spec. Every script
   object is in the surface contract. No `console`, `logger`, `http`, `fetch`,
   `require` or capitalized `Context` in behaviors, Custom Step, Custom Event,
   routes or Intuitive AI scripts.
6. Idempotent: values are set or upserted, never appended or incremented. Say
   what happens if the step runs twice.

Then list every name you assumed that I did not give you.