@zalosai/zalos-cli 0.2.34 → 0.2.35

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/dist/client.js CHANGED
@@ -83,6 +83,8 @@ export const client = {
83
83
  post: (path, body, options) => request({ method: 'POST', path, body, ...options }),
84
84
  postForm: (path, body, options) => request({ method: 'POST', path, body, ...options }),
85
85
  postBinary: (path, body, options) => request({ method: 'POST', path, body, ...options }),
86
+ /** POST a binary body and return the raw response, e.g. a streamed NDJSON result. */
87
+ postBinaryRaw: (path, body, options) => request({ method: 'POST', path, body, binaryResponse: true, ...options }),
86
88
  putBinary: (path, body, options) => request({ method: 'PUT', path, body, ...options }),
87
89
  getBinary: (path, options) => request({ method: 'GET', path, binaryResponse: true, ...options }),
88
90
  put: (path, body) => request({ method: 'PUT', path, body }),
@@ -185,6 +185,21 @@ export function registerCloseCommand(program) {
185
185
  else
186
186
  process.stdout.write(yaml);
187
187
  }));
188
+ registry
189
+ .command('retire-dataset')
190
+ .description('Retire one Data Hub report and retain its history; previews unless --confirm')
191
+ .requiredOption('--team-id <ref>', 'Team public ID or UUID (select it before confirming)')
192
+ .requiredOption('--dataset-key <key>', 'Report dataset key, e.g. bank.transactions')
193
+ .requiredOption('--expected-version <number>', 'Active registry version')
194
+ .option('--confirm <digest>', 'Publish the previewed retirement with its confirmation digest')
195
+ .action(async (o) => action(async () => {
196
+ printJson(dataRow(await client.post('/developer/finance/registry/retire-dataset', {
197
+ teamId: resourceId(o.teamId),
198
+ datasetKey: o.datasetKey,
199
+ expectedVersion: positiveVersion(o.expectedVersion),
200
+ ...(o.confirm !== undefined ? { confirm: confirmDigest(o.confirm) } : {}),
201
+ }, { timeoutMs: APPLY_TIMEOUT_MS })));
202
+ }));
188
203
  registerOnboardInput(registry);
189
204
  registerAddAgent(registry);
190
205
  }
@@ -1,12 +1,19 @@
1
1
  import { client } from '../client.js';
2
2
  import { packCodepack, packCodepackSource, unpackCodepack, } from '../utils/codepack.js';
3
3
  import { scaffoldCodepack } from '../utils/codepack-scaffold.js';
4
+ import { CASES_ROOT, isCasePath, loadCodepackCases, runLocalCodepackTests, selectCases, } from '../utils/codepack-cases.js';
4
5
  import { ApiError, ValidationError } from '../utils/errors.js';
5
6
  import { printJson } from '../utils/output.js';
6
7
  import { action, dataRow, isRow, resourceId } from '../utils/product-api.js';
7
8
  import { parseWorkflowFile } from '../workflow-file.js';
8
9
  import { publicationStatus, putWorkflowDraft } from './workflow.js';
9
10
  const PUBLISH_TIMEOUT_MS = 120_000;
11
+ /** Time a remote run may take beyond its own limit: sandbox start, upload and download. */
12
+ const REMOTE_TEST_OVERHEAD_SECONDS = 600;
13
+ /** The server's default for a test run (MAX_CODEPACK_RUN_TIMEOUT_SECONDS). */
14
+ const DEFAULT_REMOTE_TEST_SECONDS = 900;
15
+ const MAX_REMOTE_TEST_SECONDS = 900;
16
+ const MAX_LOCAL_CASE_SECONDS = 1800;
10
17
  const CODEPACK_REF_PATTERN = /^codepack:sha256:[0-9a-f]{64}$/;
11
18
  const CODEPACK_NODE_TYPE = 'mesh-nodes-base.codepack';
12
19
  const MAX_CHECKPOINT_NAME_LENGTH = 200;
@@ -159,6 +166,103 @@ async function uploadCodepack(packed, options) {
159
166
  });
160
167
  return published;
161
168
  }
169
+ function parseTimeout(raw, maximum) {
170
+ if (raw === undefined)
171
+ return undefined;
172
+ const value = Number(raw);
173
+ if (!/^\d+$/.test(raw) || value < 10 || value > maximum) {
174
+ throw new ValidationError('timeout', `Expected whole seconds from 10 to ${maximum}`);
175
+ }
176
+ return value;
177
+ }
178
+ /** The streamed result of POST /codepacks/test: heartbeat lines, then one result or error. */
179
+ function remoteTestResult(body) {
180
+ const lines = body
181
+ .toString('utf8')
182
+ .split('\n')
183
+ .filter((line) => line.trim())
184
+ .map((line) => {
185
+ try {
186
+ return JSON.parse(line);
187
+ }
188
+ catch {
189
+ return null;
190
+ }
191
+ })
192
+ .filter(isRow);
193
+ const last = lines.filter((line) => line.type !== 'heartbeat').at(-1);
194
+ if (last?.type === 'result' && isRow(last.data))
195
+ return last.data;
196
+ if (last?.type === 'error' && isRow(last.error)) {
197
+ throw new ApiError(last.error.code === 'INVALID_CODEPACK' ? 400 : 502, String(last.error.message ?? 'The codepack test run failed'));
198
+ }
199
+ throw new ApiError(502, 'The test run ended without a result; try again');
200
+ }
201
+ async function remoteTestReport(directory, options) {
202
+ const timeoutSeconds = parseTimeout(options.timeout, MAX_REMOTE_TEST_SECONDS);
203
+ // Same checks a publish makes, then the cases, before anything is sent.
204
+ const codepack = await packCodepack(directory);
205
+ const { cases } = await loadCodepackCases(directory);
206
+ const selected = new Set(selectCases(cases, options.case).map((testCase) => testCase.name));
207
+ const source = await packCodepackSource(directory, {
208
+ // With --case, send only those cases; unit tests are skipped as they are locally.
209
+ exclude: options.case
210
+ ? (path) => isCasePath(path)
211
+ ? !selected.has(path.slice(CASES_ROOT.length + 1).split('/')[0])
212
+ : path.startsWith('tests/')
213
+ : undefined,
214
+ });
215
+ const { body } = await client.postBinaryRaw('/codepacks/test', source.archive, {
216
+ contentType: 'application/gzip',
217
+ timeoutMs: ((timeoutSeconds ?? DEFAULT_REMOTE_TEST_SECONDS) + REMOTE_TEST_OVERHEAD_SECONDS) * 1000,
218
+ ...(timeoutSeconds !== undefined ? { query: { timeoutSeconds: String(timeoutSeconds) } } : {}),
219
+ });
220
+ const result = remoteTestResult(body);
221
+ const reported = Array.isArray(result.cases) ? result.cases.length : 0;
222
+ return {
223
+ where: 'remote',
224
+ templateKey: codepack.templateKey,
225
+ agentRef: codepack.agentRef,
226
+ runtimeSnapshot: result.runtimeSnapshot,
227
+ status: result.status,
228
+ unitTests: result.unitTests,
229
+ cases: Array.isArray(result.cases) ? result.cases : [],
230
+ // Every case that was sent must report; a missing result is a failure.
231
+ casesMissing: reported < selected.size,
232
+ ...(reported < selected.size
233
+ ? { notice: `Only ${reported} of ${selected.size} cases reported a result; see log.` }
234
+ : {}),
235
+ log: result.log,
236
+ };
237
+ }
238
+ /** Runs a codepack's unit tests and cases, locally or on the production runtime. */
239
+ export async function testCodepackAction(directory, options = {}) {
240
+ if (options.remote && options.python !== undefined) {
241
+ throw new ValidationError('python', '--python applies to local runs; --remote uses the runtime');
242
+ }
243
+ const report = options.remote
244
+ ? await remoteTestReport(directory, options)
245
+ : {
246
+ where: 'local',
247
+ ...(await runLocalCodepackTests(directory, {
248
+ ...(options.python !== undefined ? { python: options.python } : {}),
249
+ ...(options.case ? { cases: options.case } : {}),
250
+ ...(options.timeout !== undefined
251
+ ? { timeoutSeconds: parseTimeout(options.timeout, MAX_LOCAL_CASE_SECONDS) }
252
+ : {}),
253
+ })),
254
+ };
255
+ const cases = report.cases;
256
+ const failed = cases.filter((testCase) => testCase.status === 'failed').length;
257
+ const unitTests = isRow(report.unitTests) ? report.unitTests : {};
258
+ const ok = unitTests.status !== 'failed' &&
259
+ failed === 0 &&
260
+ !('casesMissing' in report && report.casesMissing) &&
261
+ (report.where === 'local' || report.status === 'succeeded');
262
+ printJson({ data: { ok, passed: cases.length - failed, failed, ...report } });
263
+ if (!ok)
264
+ process.exitCode = 1;
265
+ }
162
266
  export async function validateCodepackAction(directory) {
163
267
  printJson({ data: summary(await packCodepack(directory)) });
164
268
  }
@@ -171,7 +275,8 @@ export async function initCodepackAction(name, options) {
171
275
  next: [
172
276
  `cd ${JSON.stringify(dir)}`,
173
277
  'python process.py inputs/sample.csv --period_end 2026-10-31',
174
- 'python -m pytest tests',
278
+ `zl codepack test ${JSON.stringify(dir)}`,
279
+ `zl --environment <env> codepack test ${JSON.stringify(dir)} --remote`,
175
280
  `zl codepack validate ${JSON.stringify(dir)}`,
176
281
  `zl codepack publish ${JSON.stringify(dir)}`,
177
282
  ],
@@ -273,7 +378,7 @@ export async function fetchCodepackSourceAction(agentRef, options) {
273
378
  files,
274
379
  next: [
275
380
  `cd ${JSON.stringify(directory)}`,
276
- 'python -m pytest tests',
381
+ 'zl codepack test .',
277
382
  `zl codepack publish ${JSON.stringify(directory)} --parent ${agentRef} --label "<what changed>"`,
278
383
  ],
279
384
  },
@@ -292,6 +397,14 @@ export function registerCodepackCommand(program) {
292
397
  .command('validate <directory>')
293
398
  .description('Check a codepack folder and print the codepack ref it would publish as')
294
399
  .action(async (directory) => action(() => validateCodepackAction(directory)));
400
+ cmd
401
+ .command('test <directory>')
402
+ .description('Run the unit tests (tests/test_*.py) and cases (tests/cases/<case>/) with local Python, or with --remote on the production codepack runtime')
403
+ .option('--remote', 'Run on the production codepack runtime in the selected region')
404
+ .option('--case <name...>', 'Run only these cases (skips unit tests)')
405
+ .option('--python <path>', 'Local Python (default: ./.venv/bin/python, else python3)')
406
+ .option('--timeout <seconds>', 'Local: limit per case. Remote: limit for the whole run (max 900)')
407
+ .action(async (directory, o) => action(() => testCodepackAction(directory, o)));
295
408
  cmd
296
409
  .command('publish <directory>')
297
410
  .description('Publish a codepack folder to the selected team; with --workflow, repin its Codepack node and save a named checkpoint')
package/dist/main.js CHANGED
@@ -54,6 +54,10 @@ program
54
54
  (actionCommand.name() === 'validate' && actionCommand.parent?.name() === 'data-table') ||
55
55
  ((actionCommand.name() === 'validate' || actionCommand.name() === 'init') &&
56
56
  actionCommand.parent?.name() === 'codepack') ||
57
+ // A local test run needs no region; --remote does.
58
+ (actionCommand.name() === 'test' &&
59
+ actionCommand.parent?.name() === 'codepack' &&
60
+ !actionCommand.opts().remote) ||
57
61
  ((actionCommand.name() === 'validate' || actionCommand.name() === 'starter') &&
58
62
  actionCommand.parent?.name() === 'custom-page') ||
59
63
  actionCommand.parent?.name() === 'schema' ||
@@ -0,0 +1,655 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { access, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join, relative, resolve, sep } from 'node:path';
5
+ import { parse as parseYaml } from 'yaml';
6
+ import { ValidationError } from './errors.js';
7
+ import { validateCodepackConfig } from './codepack.js';
8
+ /**
9
+ * Codepack test cases, run locally by `zl codepack test`.
10
+ *
11
+ * A case is a folder under `tests/cases/<name>/`:
12
+ *
13
+ * case.json optional: {"description", "parameters", "expectError"}
14
+ * inputs/<fileInput>/<file> one file per declared file input
15
+ * expected/<output>.<ext> expected content of a declared output
16
+ *
17
+ * Locally, process.py runs with the author's Python exactly as the executor
18
+ * calls it (required inputs positional, optional ones and parameters as
19
+ * --<fieldName>, OUTPUT_DIR set), and the harness compares each registered
20
+ * output with its expected file: CSV and workbook cells, JSON values, other
21
+ * files byte for byte. `--remote` sends the folder to Mesh, which runs the same
22
+ * cases through financial-executor on the production runtime.
23
+ *
24
+ * Mirrors `packages/cli/src/services/codepacks/codepack-cases.ts`. Keep the
25
+ * layout rules and CODEPACK_CASES_HARNESS identical in both.
26
+ */
27
+ export const CASES_ROOT = 'tests/cases';
28
+ const CASE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
29
+ const SAFE_FILE_NAME = /^(?!\.)[A-Za-z0-9 ._()-]{1,180}$/;
30
+ const EXPECTED_FILE_PATTERN = /^([A-Za-z_][A-Za-z0-9_]{0,63})(\.[A-Za-z0-9]{1,10})$/;
31
+ const CASE_KEYS = new Set(['description', 'parameters', 'expectError']);
32
+ const UNIT_TEST_PATTERN = /^tests\/(.+\/)?test_[^/]*\.py$/;
33
+ const DEFAULT_TIMEOUT_SECONDS = 600;
34
+ const LOG_TAIL = 4000;
35
+ export function readCodepackContract(configYaml) {
36
+ const templateKey = validateCodepackConfig(configYaml);
37
+ const config = parseYaml(configYaml)[templateKey];
38
+ const list = (value) => Array.isArray(value) ? value.filter(isRecord) : [];
39
+ const outputContract = isRecord(config.output_contract) ? config.output_contract : {};
40
+ const resources = isRecord(config.resources) ? config.resources : {};
41
+ return {
42
+ fileInputs: list(config.file_inputs).map((field) => ({
43
+ fieldName: String(field.fieldName),
44
+ required: field.required !== false,
45
+ })),
46
+ parameters: list(config.parameters).map((field) => ({
47
+ fieldName: String(field.fieldName),
48
+ fieldType: typeof field.fieldType === 'string' ? field.fieldType : 'text',
49
+ required: field.required === true,
50
+ })),
51
+ outputs: list(outputContract.files)
52
+ .map((file) => file.fieldName)
53
+ .filter((name) => typeof name === 'string'),
54
+ ...(typeof resources.timeoutSeconds === 'number'
55
+ ? { timeoutSeconds: resources.timeoutSeconds }
56
+ : {}),
57
+ };
58
+ }
59
+ /** True when a path is test-case data rather than a unit test file. */
60
+ export function isCasePath(path) {
61
+ return path === CASES_ROOT || path.startsWith(`${CASES_ROOT}/`);
62
+ }
63
+ /** Finds and checks every case against config.yaml before anything runs. */
64
+ export function discoverCodepackCases(files, contract) {
65
+ const byCase = new Map();
66
+ for (const path of files.keys()) {
67
+ if (!path.startsWith(`${CASES_ROOT}/`))
68
+ continue;
69
+ const [name, ...rest] = path.slice(CASES_ROOT.length + 1).split('/');
70
+ if (rest.length === 0) {
71
+ throw new ValidationError('cases', `${path}: put each case in its own folder, ${CASES_ROOT}/<case>/`);
72
+ }
73
+ byCase.set(name, [...(byCase.get(name) ?? []), rest.join('/')]);
74
+ }
75
+ const fileInputs = new Map(contract.fileInputs.map((field) => [field.fieldName, field]));
76
+ const declaredParameters = new Set(contract.parameters.map((field) => field.fieldName));
77
+ const outputs = new Set(contract.outputs);
78
+ return [...byCase.keys()].sort().map((name) => {
79
+ const fail = (message) => {
80
+ throw new ValidationError('cases', `Case ${name}: ${message}`);
81
+ };
82
+ if (!CASE_NAME_PATTERN.test(name)) {
83
+ fail('case folder names use letters, digits, _, . or - (at most 64)');
84
+ }
85
+ const root = `${CASES_ROOT}/${name}`;
86
+ const testCase = { name, inputs: {}, parameters: {}, expected: {} };
87
+ for (const relativePath of (byCase.get(name) ?? []).sort()) {
88
+ const path = `${root}/${relativePath}`;
89
+ const parts = relativePath.split('/');
90
+ if (relativePath === 'case.json') {
91
+ Object.assign(testCase, parseCaseJson(files.get(path), fail));
92
+ }
93
+ else if (parts[0] === 'inputs' && parts.length === 3) {
94
+ const [, fieldName, fileName] = parts;
95
+ if (!fileInputs.has(fieldName)) {
96
+ fail(`inputs/${fieldName}: config.yaml declares no file input named ${fieldName}`);
97
+ }
98
+ if (!SAFE_FILE_NAME.test(fileName))
99
+ fail(`inputs/${fieldName}: unsafe file name`);
100
+ if (testCase.inputs[fieldName])
101
+ fail(`inputs/${fieldName} must hold exactly one file`);
102
+ testCase.inputs[fieldName] = path;
103
+ }
104
+ else if (parts[0] === 'expected' && parts.length === 2) {
105
+ const match = EXPECTED_FILE_PATTERN.exec(parts[1]);
106
+ if (!match)
107
+ fail(`expected/${parts[1]}: name it <output fieldName>.<extension>`);
108
+ const fieldName = match[1];
109
+ if (!outputs.has(fieldName)) {
110
+ fail(`expected/${parts[1]}: output_contract declares no output named ${fieldName}`);
111
+ }
112
+ if (testCase.expected[fieldName])
113
+ fail(`expected/ has two files for ${fieldName}`);
114
+ testCase.expected[fieldName] = path;
115
+ }
116
+ else {
117
+ fail(`unexpected file ${relativePath}; a case holds case.json, inputs/<fileInput>/<file> and expected/<output>.<ext>`);
118
+ }
119
+ }
120
+ for (const parameter of Object.keys(testCase.parameters)) {
121
+ if (!declaredParameters.has(parameter)) {
122
+ fail(`case.json: config.yaml declares no parameter named ${parameter}`);
123
+ }
124
+ }
125
+ if (testCase.expectError === undefined) {
126
+ for (const [fieldName, field] of fileInputs) {
127
+ if (field.required && !testCase.inputs[fieldName]) {
128
+ fail(`missing required file input inputs/${fieldName}/`);
129
+ }
130
+ }
131
+ for (const parameter of contract.parameters) {
132
+ if (parameter.required && !(parameter.fieldName in testCase.parameters)) {
133
+ fail(`case.json: missing required parameter ${parameter.fieldName}`);
134
+ }
135
+ }
136
+ }
137
+ else if (Object.keys(testCase.expected).length > 0) {
138
+ fail('a case that expects an error cannot also expect outputs');
139
+ }
140
+ return testCase;
141
+ });
142
+ }
143
+ function parseCaseJson(raw, fail) {
144
+ let data;
145
+ try {
146
+ data = JSON.parse(raw.toString('utf8'));
147
+ }
148
+ catch {
149
+ return fail('case.json is not valid JSON');
150
+ }
151
+ if (!isRecord(data))
152
+ return fail('case.json must be an object');
153
+ for (const key of Object.keys(data)) {
154
+ if (!CASE_KEYS.has(key))
155
+ fail(`case.json: unknown key ${key}`);
156
+ }
157
+ const parameters = data.parameters ?? {};
158
+ if (!isRecord(parameters))
159
+ return fail('case.json: parameters must be an object');
160
+ for (const [name, value] of Object.entries(parameters)) {
161
+ if (!['string', 'number', 'boolean'].includes(typeof value)) {
162
+ fail(`case.json: parameter ${name} must be a string, number or boolean`);
163
+ }
164
+ }
165
+ if (data.description !== undefined && typeof data.description !== 'string') {
166
+ fail('case.json: description must be a string');
167
+ }
168
+ if (data.expectError !== undefined && typeof data.expectError !== 'string') {
169
+ fail('case.json: expectError must be a string');
170
+ }
171
+ return {
172
+ ...(typeof data.description === 'string' ? { description: data.description } : {}),
173
+ parameters: parameters,
174
+ ...(typeof data.expectError === 'string' ? { expectError: data.expectError } : {}),
175
+ };
176
+ }
177
+ /** process.py's command line, as financial-executor builds it. */
178
+ export function processArguments(testCase, contract, directory) {
179
+ const args = [];
180
+ for (const field of contract.fileInputs) {
181
+ const path = testCase.inputs[field.fieldName];
182
+ if (path && field.required)
183
+ args.push(resolve(directory, path));
184
+ }
185
+ for (const field of contract.fileInputs) {
186
+ const path = testCase.inputs[field.fieldName];
187
+ if (path && !field.required)
188
+ args.push(`--${field.fieldName}`, resolve(directory, path));
189
+ }
190
+ for (const field of contract.parameters) {
191
+ if (!(field.fieldName in testCase.parameters))
192
+ continue;
193
+ const value = testCase.parameters[field.fieldName];
194
+ if (field.fieldType === 'boolean') {
195
+ if (value === true || value === 'true')
196
+ args.push(`--${field.fieldName}`);
197
+ }
198
+ else {
199
+ args.push(`--${field.fieldName}`, String(value));
200
+ }
201
+ }
202
+ return args;
203
+ }
204
+ /** The folder's contract and cases, checked; unit test files listed separately. */
205
+ export async function loadCodepackCases(directory) {
206
+ const root = resolve(directory);
207
+ const configYaml = await readFile(join(root, 'config.yaml'), 'utf8').catch(() => {
208
+ throw new ValidationError('config.yaml', `No config.yaml in ${root}`);
209
+ });
210
+ const contract = readCodepackContract(configYaml);
211
+ const testFiles = await readTree(root, 'tests');
212
+ return {
213
+ contract,
214
+ cases: discoverCodepackCases(testFiles, contract),
215
+ unitTestFiles: [...testFiles.keys()].filter((path) => UNIT_TEST_PATTERN.test(path) && !isCasePath(path)),
216
+ };
217
+ }
218
+ /** Runs the unit tests, then every case, with the author's Python. */
219
+ export async function runLocalCodepackTests(directory, options = {}) {
220
+ const root = resolve(directory);
221
+ const loaded = await loadCodepackCases(root);
222
+ const { contract, unitTestFiles } = loaded;
223
+ const cases = selectCases(loaded.cases, options.cases);
224
+ if (unitTestFiles.length === 0 && cases.length === 0) {
225
+ throw new ValidationError('tests', 'No tests: add tests/test_*.py files or cases under tests/cases/<case>/');
226
+ }
227
+ const python = options.python ?? (await defaultPython(root));
228
+ const work = await mkdtemp(join(tmpdir(), 'zl-codepack-test-'));
229
+ try {
230
+ const unitTests = unitTestFiles.length === 0 || options.cases
231
+ ? { status: 'not_run' }
232
+ : await runUnitTests(python, root, join(work, 'unit-outputs'));
233
+ let caseResults = [];
234
+ if (cases.length > 0) {
235
+ const timeoutSeconds = options.timeoutSeconds ?? contract.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
236
+ const plan = {
237
+ cases: cases.map((testCase, index) => ({
238
+ name: testCase.name,
239
+ command: [python, 'process.py', ...processArguments(testCase, contract, root)],
240
+ cwd: root,
241
+ env: { OUTPUT_DIR: join(work, String(index), 'outputs') },
242
+ outputDir: join(work, String(index), 'outputs'),
243
+ results: 'registration',
244
+ timeoutSeconds,
245
+ expected: Object.fromEntries(Object.entries(testCase.expected).map(([field, path]) => [field, resolve(root, path)])),
246
+ ...(testCase.expectError !== undefined ? { expectError: testCase.expectError } : {}),
247
+ })),
248
+ };
249
+ await writeFile(join(work, 'run_cases.py'), CODEPACK_CASES_HARNESS);
250
+ await writeFile(join(work, 'cases-plan.json'), JSON.stringify(plan));
251
+ const run = await runProcess(python, [join(work, 'run_cases.py'), join(work, 'cases-plan.json')], root);
252
+ caseResults = parseCasesReport(run.stdout);
253
+ if (caseResults.length !== cases.length) {
254
+ throw new ValidationError('python', `The case harness did not finish with ${python}: ${(run.stderr || run.stdout).slice(-LOG_TAIL)}`);
255
+ }
256
+ }
257
+ return { python, unitTests, cases: caseResults };
258
+ }
259
+ finally {
260
+ await rm(work, { recursive: true, force: true });
261
+ }
262
+ }
263
+ /** Keeps only the named cases; an unknown name is an error. */
264
+ export function selectCases(cases, names) {
265
+ if (!names || names.length === 0)
266
+ return cases;
267
+ const known = new Set(cases.map((testCase) => testCase.name));
268
+ const unknown = names.filter((name) => !known.has(name));
269
+ if (unknown.length > 0) {
270
+ throw new ValidationError('case', `No case named ${unknown.join(', ')} under ${CASES_ROOT}/ (have: ${[...known].join(', ') || 'none'})`);
271
+ }
272
+ return cases.filter((testCase) => names.includes(testCase.name));
273
+ }
274
+ export function parseCasesReport(stdout) {
275
+ const line = stdout.trim().split('\n').at(-1) ?? '';
276
+ let parsed;
277
+ try {
278
+ parsed = JSON.parse(line);
279
+ }
280
+ catch {
281
+ return [];
282
+ }
283
+ if (!isRecord(parsed) || !Array.isArray(parsed.cases))
284
+ return [];
285
+ return parsed.cases.filter(isRecord).map((entry) => ({
286
+ name: String(entry.name ?? ''),
287
+ status: entry.status === 'passed' ? 'passed' : 'failed',
288
+ seconds: typeof entry.seconds === 'number' ? entry.seconds : 0,
289
+ problems: Array.isArray(entry.problems) ? entry.problems.map(String) : [],
290
+ log: typeof entry.log === 'string' ? entry.log : '',
291
+ }));
292
+ }
293
+ async function runUnitTests(python, root, outputDir) {
294
+ const run = await runProcess(python, ['-m', 'pytest', 'tests', '-q', '-p', 'no:cacheprovider', '--ignore=tests/cases'], root, { OUTPUT_DIR: outputDir, PYTHONPATH: root });
295
+ const log = `${run.stdout}${run.stderr}`.slice(-LOG_TAIL);
296
+ if (/No module named pytest/.test(log)) {
297
+ return {
298
+ status: 'failed',
299
+ exitCode: run.exitCode,
300
+ log: `pytest is not installed for ${python}; install it (pip install pytest) or pass --python`,
301
+ };
302
+ }
303
+ return { status: run.exitCode === 0 ? 'passed' : 'failed', exitCode: run.exitCode, log };
304
+ }
305
+ async function defaultPython(root) {
306
+ const venv = join(root, '.venv', 'bin', 'python');
307
+ return access(venv).then(() => venv, () => 'python3');
308
+ }
309
+ function runProcess(command, args, cwd, env = {}) {
310
+ return new Promise((resolvePromise, reject) => {
311
+ const child = spawn(command, args, { cwd, env: { ...process.env, ...env } });
312
+ let stdout = '';
313
+ let stderr = '';
314
+ child.stdout.on('data', (chunk) => {
315
+ stdout += chunk.toString('utf8');
316
+ });
317
+ child.stderr.on('data', (chunk) => {
318
+ stderr += chunk.toString('utf8');
319
+ });
320
+ child.on('error', (error) => {
321
+ reject(error.code === 'ENOENT'
322
+ ? new ValidationError('python', `Python not found: ${command}; pass --python <path>`)
323
+ : error);
324
+ });
325
+ child.on('close', (code) => resolvePromise({ exitCode: code ?? 1, stdout, stderr }));
326
+ });
327
+ }
328
+ /** Files under `<root>/<subdirectory>` keyed by their path from root, dotfiles skipped. */
329
+ async function readTree(root, subdirectory) {
330
+ const files = new Map();
331
+ const walk = async (directory) => {
332
+ const entries = await readdir(directory, { withFileTypes: true }).catch((error) => {
333
+ if (error.code === 'ENOENT')
334
+ return [];
335
+ throw error;
336
+ });
337
+ for (const entry of entries) {
338
+ if (entry.name.startsWith('.') || entry.name === '__pycache__')
339
+ continue;
340
+ const absolute = join(directory, entry.name);
341
+ if (entry.isDirectory())
342
+ await walk(absolute);
343
+ else if (entry.isFile()) {
344
+ files.set(relative(root, absolute).split(sep).join('/'), await readFile(absolute));
345
+ }
346
+ }
347
+ };
348
+ await walk(join(root, subdirectory));
349
+ return files;
350
+ }
351
+ function isRecord(value) {
352
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
353
+ }
354
+ /**
355
+ * Runs each case in a plan and compares its outputs with the expected files.
356
+ * Identical copy of packages/cli/src/services/codepacks/codepack-cases.ts.
357
+ */
358
+ export const CODEPACK_CASES_HARNESS = String.raw `
359
+ import csv
360
+ import json
361
+ import os
362
+ import signal
363
+ import subprocess
364
+ import sys
365
+ import time
366
+ from pathlib import Path
367
+
368
+ MAX_PROBLEMS = 20
369
+ LOG_TAIL = 4000
370
+
371
+
372
+ class TimeLimit(BaseException):
373
+ """The run's time limit sent SIGTERM; report what finished instead of nothing."""
374
+
375
+
376
+ def stop(_signum, _frame):
377
+ raise TimeLimit()
378
+
379
+
380
+ def main():
381
+ plan = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
382
+ signal.signal(signal.SIGTERM, stop)
383
+ cases = plan["cases"]
384
+ results = []
385
+ try:
386
+ for case in cases:
387
+ results.append(run_case_safely(case))
388
+ except TimeLimit:
389
+ for case in cases[len(results):]:
390
+ results.append({
391
+ "name": case["name"],
392
+ "status": "failed",
393
+ "seconds": 0,
394
+ "problems": ["Not finished: the test run hit its time limit"],
395
+ "log": "",
396
+ })
397
+ failed = sum(1 for result in results if result["status"] != "passed")
398
+ print(json.dumps({"cases": results, "passed": len(results) - failed, "failed": failed}))
399
+ return 1 if failed else 0
400
+
401
+
402
+ def run_case_safely(case):
403
+ """One case's error never costs the others their results."""
404
+ started = time.monotonic()
405
+ try:
406
+ return run_case(case)
407
+ except Exception as error:
408
+ return finish(case, started, [f"The case could not be checked: {error!r}"], "")
409
+
410
+
411
+ def run_case(case):
412
+ started = time.monotonic()
413
+ for path, content in (case.get("writeFiles") or {}).items():
414
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
415
+ Path(path).write_text(json.dumps(content), encoding="utf-8")
416
+ output_dir = Path(case["outputDir"])
417
+ output_dir.mkdir(parents=True, exist_ok=True)
418
+ env = {**os.environ, **(case.get("env") or {})}
419
+ timeout = case.get("timeoutSeconds")
420
+ try:
421
+ completed = subprocess.run(
422
+ case["command"],
423
+ cwd=case.get("cwd") or None,
424
+ env=env,
425
+ capture_output=True,
426
+ text=True,
427
+ timeout=timeout,
428
+ )
429
+ except subprocess.TimeoutExpired:
430
+ return finish(case, started, [f"Timed out after {timeout}s"], "")
431
+ except OSError as error:
432
+ return finish(case, started, [f"Could not start the run: {error}"], "")
433
+
434
+ if case.get("results") == "executor":
435
+ outputs, error, log = executor_outputs(completed.stdout)
436
+ log = "\n".join(part for part in (log, completed.stderr) if part)
437
+ else:
438
+ outputs, error = registered_outputs(output_dir), None
439
+ log = "\n".join(part for part in (completed.stdout, completed.stderr) if part)
440
+ failed = completed.returncode != 0 or error is not None
441
+
442
+ problems = []
443
+ expect_error = case.get("expectError")
444
+ if expect_error is not None:
445
+ if not failed:
446
+ problems.append("Expected the run to fail, but it succeeded")
447
+ elif expect_error and expect_error not in "\n".join([log, error or ""]):
448
+ problems.append(f"The run failed, but its message does not contain {expect_error!r}")
449
+ elif failed:
450
+ problems.append(
451
+ f"The run failed (exit code {completed.returncode})" + (f": {error}" if error else "")
452
+ )
453
+ else:
454
+ for field, expected in sorted(case.get("expected", {}).items()):
455
+ actual = outputs.get(field)
456
+ if actual is None:
457
+ problems.append(f"{field}: the run registered no {field} output")
458
+ continue
459
+ try:
460
+ found = compare(Path(expected), Path(actual))
461
+ except Exception as error:
462
+ found = [f"could not be compared: {error!r}"]
463
+ problems.extend(f"{field}: {problem}" for problem in found)
464
+ return finish(case, started, problems, log)
465
+
466
+
467
+ def finish(case, started, problems, log):
468
+ return {
469
+ "name": case["name"],
470
+ "status": "failed" if problems else "passed",
471
+ "seconds": round(time.monotonic() - started, 2),
472
+ "problems": problems[:MAX_PROBLEMS]
473
+ + ([f"... and {len(problems) - MAX_PROBLEMS} more"] if len(problems) > MAX_PROBLEMS else []),
474
+ "log": log[-LOG_TAIL:] if problems else "",
475
+ }
476
+
477
+
478
+ def executor_outputs(stdout):
479
+ """financial-executor prints one JSON result: outputFiles with logicalName and localPath."""
480
+ payload = None
481
+ for line in reversed(stdout.strip().splitlines()):
482
+ try:
483
+ payload = json.loads(line)
484
+ break
485
+ except ValueError:
486
+ continue
487
+ if not isinstance(payload, dict):
488
+ return {}, "financial-executor printed no result", stdout
489
+ outputs = {
490
+ str(item.get("logicalName")): item.get("localPath")
491
+ for item in payload.get("outputFiles") or []
492
+ if isinstance(item, dict) and item.get("localPath")
493
+ }
494
+ error = payload.get("error")
495
+ if isinstance(error, dict):
496
+ error = error.get("message")
497
+ if not payload.get("ok", False) and not error:
498
+ error = f"status {payload.get('status')}"
499
+ return outputs, (str(error) if error else None), str(payload.get("stdout") or "")
500
+
501
+
502
+ def registered_outputs(output_dir):
503
+ """What register_output wrote: OUTPUT_DIR/.zalos_outputs.json."""
504
+ manifest = output_dir / ".zalos_outputs.json"
505
+ if not manifest.is_file():
506
+ return {}
507
+ entries = json.loads(manifest.read_text(encoding="utf-8")).get("files", [])
508
+ return {entry["fieldName"]: str(output_dir / entry["path"]) for entry in entries}
509
+
510
+
511
+ def compare(expected, actual):
512
+ suffix = expected.suffix.lower()
513
+ if actual.suffix.lower() != suffix:
514
+ return [f"expected a {suffix} file, got {actual.name}"]
515
+ if suffix in (".csv", ".tsv"):
516
+ return compare_tables(read_delimited(expected, suffix), read_delimited(actual, suffix), None)
517
+ if suffix == ".json":
518
+ return compare_values(load_json(expected), load_json(actual), "$")
519
+ if suffix == ".jsonl":
520
+ return compare_rows([load_json_line(l) for l in lines(expected)], [load_json_line(l) for l in lines(actual)])
521
+ if suffix in (".xlsx", ".xlsm"):
522
+ return compare_workbooks(expected, actual)
523
+ if expected.read_bytes() != actual.read_bytes():
524
+ return [f"content differs ({expected.stat().st_size} bytes expected, {actual.stat().st_size} written)"]
525
+ return []
526
+
527
+
528
+ def read_delimited(path, suffix):
529
+ with path.open(newline="", encoding="utf-8-sig") as handle:
530
+ return list(csv.reader(handle, delimiter="\t" if suffix == ".tsv" else ","))
531
+
532
+
533
+ def load_json(path):
534
+ return json.loads(path.read_text(encoding="utf-8"))
535
+
536
+
537
+ def lines(path):
538
+ return [line for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
539
+
540
+
541
+ def load_json_line(line):
542
+ return json.loads(line)
543
+
544
+
545
+ def compare_rows(expected, actual):
546
+ problems = []
547
+ if len(expected) != len(actual):
548
+ problems.append(f"{len(expected)} lines expected, {len(actual)} written")
549
+ for index, (want, got) in enumerate(zip(expected, actual), start=1):
550
+ problems.extend(compare_values(want, got, f"line {index}"))
551
+ if len(problems) > MAX_PROBLEMS:
552
+ break
553
+ return problems
554
+
555
+
556
+ def compare_values(expected, actual, where):
557
+ if isinstance(expected, dict) and isinstance(actual, dict):
558
+ problems = []
559
+ for key in sorted(set(expected) | set(actual), key=str):
560
+ if key not in actual:
561
+ problems.append(f"{where}.{key}: missing")
562
+ elif key not in expected:
563
+ problems.append(f"{where}.{key}: not expected, got {actual[key]!r}")
564
+ else:
565
+ problems.extend(compare_values(expected[key], actual[key], f"{where}.{key}"))
566
+ return problems
567
+ if isinstance(expected, list) and isinstance(actual, list):
568
+ problems = [] if len(expected) == len(actual) else [f"{where}: {len(expected)} items expected, {len(actual)} written"]
569
+ for index, (want, got) in enumerate(zip(expected, actual)):
570
+ problems.extend(compare_values(want, got, f"{where}[{index}]"))
571
+ return problems
572
+ if is_number(expected) and is_number(actual):
573
+ # JSON does not distinguish 350 from 350.0; compare amounts by value.
574
+ return [] if expected == actual else [f"{where}: expected {expected!r}, got {actual!r}"]
575
+ if expected != actual or type(expected) is not type(actual):
576
+ return [f"{where}: expected {expected!r}, got {actual!r}"]
577
+ return []
578
+
579
+
580
+ def is_number(value):
581
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
582
+
583
+
584
+ def compare_tables(expected, actual, sheet):
585
+ """Row by row; columns are named by the header row when there is one."""
586
+ prefix = f"sheet {sheet!r} " if sheet is not None else ""
587
+ problems = []
588
+ if len(expected) != len(actual):
589
+ problems.append(f"{prefix}{len(expected)} rows expected, {len(actual)} written")
590
+ header = expected[0] if expected else []
591
+ for row_index, (want, got) in enumerate(zip(expected, actual), start=1):
592
+ for column in range(max(len(want), len(got))):
593
+ want_cell = want[column] if column < len(want) else None
594
+ got_cell = got[column] if column < len(got) else None
595
+ if want_cell != got_cell:
596
+ if sheet is not None:
597
+ place = f"{column_letter(column)}{row_index}"
598
+ elif row_index > 1 and column < len(header) and header[column]:
599
+ place = f"row {row_index}, column {header[column]!r}"
600
+ else:
601
+ place = f"row {row_index}, column {column + 1}"
602
+ problems.append(f"{prefix}{place}: expected {want_cell!r}, got {got_cell!r}")
603
+ if len(problems) > MAX_PROBLEMS:
604
+ return problems
605
+ return problems
606
+
607
+
608
+ def compare_workbooks(expected, actual):
609
+ """Cell values and formulas, sheet by sheet; workbook metadata is ignored."""
610
+ try:
611
+ import openpyxl
612
+ except ImportError:
613
+ return ["install openpyxl to compare workbooks"]
614
+ want = sheets(openpyxl, expected)
615
+ got = sheets(openpyxl, actual)
616
+ if list(want) != list(got):
617
+ return [f"sheets {list(want)} expected, got {list(got)}"]
618
+ problems = []
619
+ for name in want:
620
+ problems.extend(compare_tables(want[name], got[name], name))
621
+ if len(problems) > MAX_PROBLEMS:
622
+ break
623
+ return problems
624
+
625
+
626
+ def sheets(openpyxl, path):
627
+ workbook = openpyxl.load_workbook(path, read_only=True, data_only=False)
628
+ try:
629
+ result = {}
630
+ for sheet in workbook.worksheets:
631
+ rows = [list(row) for row in sheet.iter_rows(values_only=True)]
632
+ for row in rows:
633
+ while row and row[-1] is None:
634
+ row.pop()
635
+ while rows and not rows[-1]:
636
+ rows.pop()
637
+ result[sheet.title] = rows
638
+ return result
639
+ finally:
640
+ workbook.close()
641
+
642
+
643
+ def column_letter(index):
644
+ letters = ""
645
+ index += 1
646
+ while index:
647
+ index, remainder = divmod(index - 1, 26)
648
+ letters = chr(65 + remainder) + letters
649
+ return letters
650
+
651
+
652
+ if __name__ == "__main__":
653
+ sys.exit(main())
654
+ `;
655
+ //# sourceMappingURL=codepack-cases.js.map
@@ -8,6 +8,8 @@ import { ValidationError } from './errors.js';
8
8
  * for agent-studio's private `zalosai.agent_tools`, writing the same
9
9
  * `OUTPUT_DIR` registration manifest and progress lines the Mesh executor
10
10
  * reads. `inputs/` and `tests/` help the author iterate but are never packed.
11
+ * `tests/cases/` starts with one example that must match and one that must
12
+ * fail, the shape `zl codepack test` runs.
11
13
  */
12
14
  const CODEPACK_NAME_PATTERN = /^[a-z][a-z0-9_]{1,62}$/;
13
15
  function titleCase(name) {
@@ -205,6 +207,22 @@ Acme Ltd,1000.00
205
207
  Globex,500.50
206
208
  Initech,250.00
207
209
  `;
210
+ const SAMPLE_CASE_JSON = `{
211
+ "description": "The sample file: three customers",
212
+ "parameters": { "period_end": "2026-10-31" }
213
+ }
214
+ `;
215
+ const SAMPLE_CASE_EXPECTED = `period_end,rows,total_amount
216
+ 2026-10-31,3,1750.5
217
+ `;
218
+ const NO_AMOUNT_CASE_JSON = `{
219
+ "description": "A file without an Amount column is refused with a clear message",
220
+ "expectError": "No Amount column"
221
+ }
222
+ `;
223
+ const NO_AMOUNT_CSV = `Customer,Total
224
+ Acme Ltd,1000.00
225
+ `;
208
226
  const GITIGNORE = `outputs/
209
227
  __pycache__/
210
228
  .venv/
@@ -228,6 +246,11 @@ export async function scaffoldCodepack(name, directory) {
228
246
  'codepack_runtime.py': RUNTIME_PY,
229
247
  'inputs/sample.csv': SAMPLE_CSV,
230
248
  'tests/test_process.py': TEST_PY,
249
+ 'tests/cases/sample/case.json': SAMPLE_CASE_JSON,
250
+ 'tests/cases/sample/inputs/source/sample.csv': SAMPLE_CSV,
251
+ 'tests/cases/sample/expected/summary.csv': SAMPLE_CASE_EXPECTED,
252
+ 'tests/cases/no_amount/case.json': NO_AMOUNT_CASE_JSON,
253
+ 'tests/cases/no_amount/inputs/source/no_amount.csv': NO_AMOUNT_CSV,
231
254
  '.gitignore': GITIGNORE,
232
255
  };
233
256
  for (const [path, contents] of Object.entries(files)) {
@@ -95,9 +95,12 @@ export async function packCodepack(directory) {
95
95
  * caches, local environments and dotfiles. It always contains the runtime
96
96
  * files, so the server can check it matches the published codepack.
97
97
  */
98
- export async function packCodepackSource(directory) {
99
- const files = [];
100
- await collect(directory, directory, files, [], SOURCE_SELECTION);
98
+ export async function packCodepackSource(directory, options = {}) {
99
+ const collected = [];
100
+ await collect(directory, directory, collected, [], SOURCE_SELECTION);
101
+ const files = options.exclude
102
+ ? collected.filter((file) => !options.exclude(file.path))
103
+ : collected;
101
104
  const archive = buildTarGz(files);
102
105
  if (archive.byteLength > MAX_ARCHIVE_BYTES) {
103
106
  throw new ValidationError('codepack', 'Codepack source exceeds 25 MiB; move large fixtures to Team Files or private/');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zalosai/zalos-cli",
3
- "version": "0.2.34",
3
+ "version": "0.2.35",
4
4
  "description": "API-only product command-line interface for Zalos",
5
5
  "repository": {
6
6
  "type": "git",
@@ -18,12 +18,17 @@ the selected team (`zl team list`, `zl team switch <tm_…>`).
18
18
 
19
19
  1. **Scaffold:** `zl codepack init <snake_name>` creates a runnable folder. It is
20
20
  offline and needs no login.
21
- 2. **Build:** edit `config.yaml` and `process.py`, using the contract below.
22
- 3. **Run locally:** run it on sample files exactly as the executor will:
21
+ 2. **Write the cases first:** for each example you know the right answer to, add a
22
+ folder under `tests/cases/` (see "Test cases" below). The cases are the spec:
23
+ ask the user for a real input and the output they expect, and turn every
24
+ example they give into a case.
25
+ 3. **Build:** edit `config.yaml` and `process.py`, using the contract below, until
26
+ `zl codepack test <folder>` passes. It runs `tests/test_*.py` with pytest, then
27
+ every case, with the folder's `.venv` Python (or `--python <path>`), and names
28
+ each cell, row or key that differs. To look at a run by hand:
23
29
  ```bash
24
30
  cd <snake_name>
25
31
  python process.py inputs/<file> --<parameter> <value> # writes ./outputs
26
- python -m pytest tests
27
32
  ```
28
33
  - **Inputs and tests:** put sample files in `inputs/` and tests in `tests/`.
29
34
  Runs never get them. They are kept with the team's copy of the source, so
@@ -33,9 +38,14 @@ the selected team (`zl team list`, `zl team switch <tm_…>`).
33
38
  `python3.12 -m venv .venv && .venv/bin/pip install pandas openpyxl xlsxwriter pytest`.
34
39
  - **Clean runs:** delete `outputs/` between runs, or set `OUTPUT_DIR` to a fresh
35
40
  folder, so stale files don't hide a missing output.
36
- 4. **Validate:** `zl codepack validate <folder>` checks the config and prints the
41
+ 4. **Test on the production runtime:** `zl --environment <env> codepack test <folder> --remote`
42
+ runs the same tests and cases in Mesh, through the executor a workflow uses, on
43
+ its exact Python and packages. Local Python can differ (for example pandas 3
44
+ locally, pandas 2 in the runtime), so run it before publishing. `--case <name>`
45
+ runs only the named cases.
46
+ 5. **Validate:** `zl codepack validate <folder>` checks the config and prints the
37
47
  `codepack:sha256:…` ref it would publish as, plus the files it packs and skips.
38
- 5. **Publish:**
48
+ 6. **Publish:**
39
49
  - **First time:** `zl --environment <env> codepack publish <folder>` prints a
40
50
  Codepack node to paste into workflow JSON (`zl workflow import`/`update`).
41
51
  - **New version of an existing node:** use
@@ -44,7 +54,7 @@ the selected team (`zl team list`, `zl team switch <tm_…>`).
44
54
  named checkpoint.
45
55
  - **Lineage:** `--parent <codepack ref>` records which version this one was changed
46
56
  from, and `--label` records what changed. `zl codepack info <ref>` shows both.
47
- 6. **Make it live:** a workflow with a published version keeps running that version
57
+ 7. **Make it live:** a workflow with a published version keeps running that version
48
58
  until `zl --environment <env> workflow publish <id> --apply`. Then run it with
49
59
  `zl workflow run <id>`, and check the result with `zl execution view <execution-id>`
50
60
  and `zl file download <output-file-id> --output <path>`.
@@ -52,14 +62,50 @@ the selected team (`zl team list`, `zl team switch <tm_…>`).
52
62
  ### Changing a published codepack
53
63
 
54
64
  `zl --environment <env> codepack source <ref> --output <folder>` downloads the
55
- folder a node pins, tests and sample inputs included, into an empty folder. Edit
56
- it, run its tests, then publish it with `--parent <ref> --label "<what changed>"`.
65
+ folder a node pins, tests and sample inputs included, into an empty folder. Add a
66
+ case for the change, edit until `zl codepack test` passes, then publish it with
67
+ `--parent <ref> --label "<what changed>"`.
57
68
  Codepacks published before sources were kept come back without `tests/` and
58
69
  `inputs/` (`"source": "runtime"`).
59
70
 
60
- Always run locally and validate before publishing. After publishing, run the workflow
71
+ Always pass `zl codepack test`, locally and with `--remote`, and validate before publishing. After publishing, run the workflow
61
72
  once on real inputs and check the outputs before telling the user it works.
62
73
 
74
+ ## Test cases
75
+
76
+ A case is an example input with the output it must produce, in its own folder:
77
+
78
+ ```text
79
+ tests/cases/<case>/
80
+ case.json optional
81
+ inputs/<fileInput>/<file> one file per file input, under its fieldName
82
+ expected/<output>.<ext> the expected content of an output, by fieldName
83
+ ```
84
+
85
+ ```json
86
+ {
87
+ "description": "October close: two vendors below the threshold",
88
+ "parameters": { "period_end": "2026-10-31", "threshold": 2500 }
89
+ }
90
+ ```
91
+
92
+ - **Inputs:** every required file input needs a file, and every required parameter
93
+ a value. File names and extensions reach `process.py` unchanged.
94
+ - **Expected outputs:** `expected/summary.csv` is compared with the output
95
+ registered as `summary`. CSV and TSV are compared cell by cell, `.xlsx` cell by
96
+ cell on every sheet (values and formulas, not styling or metadata), JSON and JSONL
97
+ by value, anything else byte for byte. Outputs without an expected file are not
98
+ compared, but the run must still succeed.
99
+ - **Expected failures:** `"expectError": "No Amount column"` passes only when the run
100
+ fails with a message containing that text. Add one for every input the codepack
101
+ must refuse. Such a case has no `expected/` files.
102
+ - **Real data:** copy a past period's inputs and the output the user signed off into
103
+ a case to pin that behaviour. Cases are kept with the published source
104
+ (`zl codepack source` returns them) but never run in a workflow.
105
+ - **Unit tests:** `tests/test_*.py` still suit small rules such as a date parser.
106
+ When the Mesh runtime has no pytest, only the `tmp_path` fixture is available, so
107
+ keep them to plain functions.
108
+
63
109
  ## The contract
64
110
 
65
111
  ### `config.yaml`