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
- Work item id: from the
WorkItemIdheader, not the body. - Secrets: in configuration, never in code.
- Failure fails: no caught exception followed by success.
- Exact names: buckets and keys match, values are strings.
- Real names: every endpoint is in your spec, every object is in the surface contract.
- 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.
var body = await new StreamReader(req.Body).ReadToEndAsync();
var workItemId = JObject.Parse(body)["WorkItemId"];
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.
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.
catch (Exception ex)
{
log.LogError(ex.Message);
return new OkObjectResult("done");
}
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.
try {
var total = parseFloat(batch.Metadata['Index']['BatchTotal']);
} catch (e) { }
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.
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.
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:
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:
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.
var count = parseInt((batch.Metadata['General'] || {})['ReviewCount'] || '0', 10);
builder.SetBatchMetadata('General', 'ReviewCount', String(count + flagged));
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¶
contextis lowercase:context.username,context.usergroups,context.app. A capitalizedContextobject does not exist.RuntimeValueis 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
trueas the third argument ofSetFieldRuntimeValueso its behaviors do not fire. - Use
SetFieldChoices(field, choices). Do not use theSetChoicesshorthand. - The script also runs on the server (Index Your Documents, Run Indexing Behaviors, Start QC Task, Search bulk edit) with
context.appset to"worker"and no user. Guard user-only logic. - No network, no
console, no top-levelreturn.
Search filter behavior¶
- Only
context.usernameexists. There is nousergroupsorapphere. - 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, notbatch. The id isWorkItemIdand the name isName. - A value set only per document does not appear in
workItem.Metadata.
Custom Step¶
- No network, no
fetch, norequire, noconsole, no top-levelreturn. - Read from
batch, write throughbuilder. Writes apply when the script ends, unless the script callsbuilder.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.Documentsor walk it backwards. - Guard each metadata level. A missing bucket is undefined.
GlobalVariables.Get(name)throwsGlobal 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 andJSON.stringify(x)for objects. - Scopes come from the step's Scopes setting, not from the script. Avoid the words
error,startandstopin scopes unless you mean them. - The script has 10 seconds and no PapaParse.
Your own function¶
- The work item id comes from the
WorkItemIdheader. - The token and URL come from configuration.
- Every failure returns a non-2xx status.
- Every action exists in your tenant's spec. Check
Successon every response, and readMessages[].MessageKeyon 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 asonclick=. Put all code inmain.js. - Read
gizmo.Configonly aftergizmo.OnReceiveConfigfires. - 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
indexOfmatch 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 withresult.SetDocumentMetadata. No network.
Custom Insight widget endpoint¶
- The endpoint answers
GET {base}/validatewith 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 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.