@lotics/cli 0.318.32 → 0.318.34

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/docs/workflows.md CHANGED
@@ -83,7 +83,7 @@ All three carry `trigger.trigger_id`.
83
83
  | for | `for (const <name> of <expr>) { ... }` |
84
84
  | wait | `await wait({ duration_in_minutes: 5 });` |
85
85
  | wait for an event | `await wait_for_event({ event_type: "webhook", event_ref: <expr>, timeout_in_minutes: 60 });` |
86
- | return | `return({ status: "success" \| "error", message: <expr>, field_errors: { ... }?, data: { ... }? });` — `data` holds the outputs a Workflow node declares — a return of `error` undoes no write a step before it made, so every refusal stands before the body's first write |
86
+ | return | `return({ status: "success" \| "error", message: <expr>, field_errors: { ... }?, data: { ... }? });` — `data` holds the outputs a Workflow node declares — a body whose steps only read and write the workspace's rows and make papers runs as one transaction: a return of `error`, a failed `validate`, a table's refusal or a failure takes back every write of the run, and a run too long to hold one starts again step by step; a body that also calls out (a send, a connected service, an import of rows, another workflow), waits or runs an agent runs step by step: each step's writes stand as they land and a return of `error` undoes none, so its refusals stand before its first write; an Act's own write (`set`, asks, signature) and its papers land after the body, before each `success` return and where the body ends, so a refusal leaves the row as it stood, and the body's `row` and any read of the row in the body see it as the press found it |
87
87
  | validate | `validate({ checks: [{ fail_when: <expr>, field_key: "...", message: <expr> }, ...] });` |
88
88
 
89
89
  A delayed run is never cancelled from a workflow: after a `wait`, it reads the row's state and acts only if it still holds.
@@ -202,8 +202,10 @@ A body names a table or document template by its alias (`query_records({ table_i
202
202
  result `first(found.records).id`, a filter `rows.filter((r) => r.ok)[0].n`, a `(a ?? b).c`. `?.` reads
203
203
  through a null as usual, except on a value drawn at random (`sample(xs)?.id` is refused: bind it first).
204
204
  - A record reads in its declared shape wherever it comes from — the trigger, a tool result, a `let`, a
205
- callback parameter: a single select as its option alias or null, a member as its id, a link as its ids. (The record
206
- tools called outside a workflow return the stored arrays instead.)
205
+ callback parameter: a single select as its option alias or null, a member as its id, a link as its ids. A property read
206
+ by alias (`x.order.quantity`, `xs[0]["quantity"]`, `y.quantity`) also names the record's field when the record is held in an
207
+ object, a list or a spread (`{ order: record }`, `[record]`, `{ ...record }`); a helper's field-path text reads the
208
+ rows of a records tool and a loop over them only. (The record tools called outside a workflow return the stored arrays instead.)
207
209
  - `linked(record["link"])[n]["x"]` fetches the n-th linked row and reads a field of it; bare
208
210
  `linked(record["link"])` is every linked row, one fetch per row. Its argument is a path ending on
209
211
  a link field and carries the guard: `linked(record?.["link"])[0]`.
@@ -328,7 +330,8 @@ The same work can be written with the helpers below, which are additions to Java
328
330
  - **Dates**, in the workspace's timezone: `now`, `formatDate`, `parseDate`, `addDays`, `subDays`,
329
331
  `addHours`, `subHours`, `addMinutes`, `subMinutes`, `startOfDay`, `endOfDay`, `startOfMonth`, `endOfMonth`,
330
332
  `addMonths` (a day past the target month's end lands on its last day), `differenceInCalendarDays`, `differenceInHours`, `differenceInMinutes`, `isBefore`, `isAfter`,
331
- `isSameDay`, `isToday`, `isWithinRange`, `meetsBounds`
333
+ `isSameDay`, `isToday`, `isWithinRange`, `meetsBounds`. A date beside a moment compares by day, so `<=` means
334
+ through that day; `startOfMonth` and `endOfMonth` of a date answer a day
332
335
  - **Other**: `formatCurrency(amount, locale, currency)`, `randomNumber(len)`,
333
336
  `randomAlphaNumeric(len)`, `sample(items)` (a random item)
334
337
 
@@ -402,64 +405,17 @@ row of an `.xlsx`, `.xls` or `.csv` sheet in one call, each an object keyed by t
402
405
  A sheet past what one call reads is refused with its size, never cut short: the step's entry in
403
406
  `workflow_steps` states the bounds.
404
407
 
405
- `import_rows`, a workflow step, matches those rows to a table by a key and writes what differs. `match`
406
- names the fields that identify a row, compared as trimmed text with case ignored: a row matching no live
407
- row is added, one matching a row changes only the cells that differ, and one that changes nothing is
408
- counted and not written, so the same file run twice writes nothing the second time. `values` holds a
409
- row's cells by field alias, as `create_records` takes them; a key the row omits is left as the table holds
410
- it, and `null` is an empty cell, which differs from a filled one as any other value does. `dry_run: true` judges the import as a real one would be, rolls it back and answers what it would write or why it is refused.
411
-
412
- A `match` field may also be a link field holding one row, compared by the row linked: lines keyed by
413
- their parent and a line number state `match: ["invoice", "line"]`, the parent given as its
414
- record id or as `{ lookup: "<text>" }`.
415
-
416
- What the step is not certain of is held — answered with why, and not written: a row carrying `hold`
417
- (its text is the message); a row whose key several live rows carry, or an earlier row of the same call;
418
- a row the table's checks refuse, or whose row is locked; with `create: false`, a row matching none. A
419
- held row never fails the step, and the rows beside it are written. A row whose key names a row outside
420
- the rows the run may write is held `refused` with nothing of that row: no `record_id`, no `changes`.
421
-
422
- The step removes no row, and a row the source leaves out is never touched. A row carrying
423
- `remove: true`, with its key in `values`, proposes moving the row its key names to the trash: it is
424
- always held, whatever `create` and `conflicts` say, and a key naming no row is counted unchanged.
425
-
426
- `conflicts` states what a matched row does where a live cell holds another value: `"hold"` writes the
427
- row's empty cells and holds the differing ones, `"overwrite"` writes over them, `"fill_empty"` leaves
428
- them. `conflicts.fields` gives one field its own. A number and the field its unit or currency is read
429
- from on each row are one cell, under the number's policy: both are written, or both held.
430
-
431
- A link cell takes `{ lookup: "<text>" }` in place of record ids: the linked row is the one row holding
432
- that text in the linked table's unique or autonumber field, else the one titled it, among the rows the
433
- run reads of that table. A text naming no row, or several, holds the row, and the rows it could be are
434
- answered beside it. A link holding many rows takes a list, `[{ lookup: "<text>" }, …]`: each text is
435
- resolved by itself.
436
-
437
- The step keeps nothing of its own: its answer is everything it did. `written` lists each record it
438
- wrote — a changed one with each field from old to new as text, a created one by its id alone — and
439
- `held_rows` each row it held: its `kind`, `reason` and `message`, the `record_id` of the row it matched,
440
- its `key`, the `changes` it would make, the `links` it could not resolve with their `candidates`, and
441
- `values` — its key and the cells it would write, as the call gave them. A later call given a held row's
442
- `values` under `conflicts: { default: "overwrite" }` writes it. Both lists are read under the run's own
443
- reach of the table, and a workflow hands its caller only what it returns. Two calls matching one table
444
- by the same fields take turns, so the second matches the rows the first added. The step's entry in
445
- `workflow_steps` states its bounds.
446
-
447
- A workflow does not put an import back: that reads the history of what the run wrote, which a member's agent reads
448
- under the member's own access to the table and no workflow does. A member's agent puts an import back with
449
- `update_records`: `query_audit_logs` on the table shows what the run wrote — the run is what `runtime.execution_id` held in
450
- it, which a body keeps on a row of its own — and each field's value before it, `update_records` writes that value back as
451
- the member's own write, `update_records` with `restore: true` brings back a row the run moved to the trash, and
452
- `delete_records` removes a row the run created. Write a field back only where the row still holds what the run wrote.
453
-
454
- What a business keeps of an import — the file, its counts, the lines waiting for a person — is rows of
455
- its own tables, written by the workflow that ran the step. A garden centre brings its grower's price
456
- sheet into its plants, and keeps each sheet and its lines. A line names its plant through a link
457
- holding many rows: one holding a single row would make the line that plant's own, and a plant its
458
- lines belong to is not moved to the trash.
408
+ A sheet's rows are written with `save_record`, a workflow step, once per row. `match` is the row's identity,
409
+ `{ code: <the row's code> }`, and must be a uniqueness its table declares: the field is `unique`. A live row carrying
410
+ the key is found and only the cells of `set` that differ are written; none is found and the row is added. Run the same
411
+ file twice and the second run writes nothing new. A cell the row has no value for is left out of `set`, and `null` is an
412
+ empty cell, which differs from a filled one as any other value does. A row the body should not write is skipped and
413
+ counted in what the workflow returns, so the person who ran it is told; the step holds nothing back on its own, and a
414
+ row a table check or a lock refuses fails the call, naming the row.
459
415
 
460
- These tables are shown beside the plants, in the same app: the sheets as a List beside the plants'
461
- (a second List at the root, `reference/app-node`), a sheet's lines on the page it opens. A line keeping what a cell held
462
- and what it holds now in two fields reads one against the other (`compare`, `reference/list-node`).
416
+ A link cell takes the record id of the row it links. To find that row by the text a sheet holds, `query_records` the
417
+ linked table once, `groupBy` its key, and read the id from the group. A body that does not find the row skips the
418
+ sheet's row and counts it.
463
419
 
464
420
  ```
465
421
  const sheet = await excel_get_rows({ // a workflow step
@@ -467,96 +423,123 @@ const sheet = await excel_get_rows({ // a workflow step
467
423
  columns: ["Code", "Name", "Price"],
468
424
  });
469
425
 
470
- const imported = await import_rows({ // a workflow step
471
- table_id: "plants",
472
- match: ["code"],
473
- rows: sheet.rows.map((row, at) => ({
474
- line: at + 2,
475
- hold: isNull(row["Price"]) ? "The sheet states no price" : null,
476
- values: {
477
- code: toString(row["Code"]),
478
- name: toString(row["Name"]),
479
- price: toNumber(row["Price"]),
480
- },
481
- })),
482
- });
483
-
484
426
  const kept = await create_records({
485
427
  table_id: "price_sheets",
486
- records: [{
487
- file: [trigger.app_workflow.inputs.file],
488
- run: runtime.execution_id,
489
- read: imported.read,
490
- created: imported.created,
491
- changed: imported.changed,
492
- held: imported.held,
493
- }],
428
+ records: [{ file: [trigger.app_workflow.inputs.file], run: runtime.execution_id }],
494
429
  });
495
430
  const sheet_id = kept.record_ids[0];
496
431
 
497
- for (let start = 0; start < size(imported.written); start += 50) {
498
- await create_records({
499
- table_id: "sheet_lines",
500
- records: slice(imported.written, start, start + 50).map((one) => ({
501
- sheet: [sheet_id],
502
- plant: [one.record_id],
503
- line: one.line,
504
- outcome: one.kind,
505
- changes: join(one.changes.map((change) => `${change.label}: ${change.before ?? "—"} → ${change.after ?? "—"}`), "; "),
506
- })),
507
- });
432
+ let added = 0;
433
+ let changed = 0;
434
+ let skipped = 0;
435
+ for (let at = 0; at < size(sheet.rows); at += 1) {
436
+ const row = sheet.rows[at];
437
+ if (isNull(row["Price"])) {
438
+ skipped += 1;
439
+ await create_records({
440
+ table_id: "sheet_lines",
441
+ records: [{ sheet: [sheet_id], line: at + 2, outcome: "skipped", why: "The sheet states no price", code: toString(row["Code"]) }],
442
+ });
443
+ } else {
444
+ const saved = await save_record({ // a workflow step
445
+ table_id: "plants",
446
+ match: { code: toString(row["Code"]) },
447
+ set: { name: toString(row["Name"]), price: toNumber(row["Price"]) },
448
+ });
449
+ added += saved.created ? 1 : 0;
450
+ changed += !saved.created && size(saved.updated_field_keys) > 0 ? 1 : 0;
451
+ }
508
452
  }
509
- for (let start = 0; start < size(imported.held_rows); start += 50) {
510
- await create_records({
511
- table_id: "sheet_lines",
512
- records: slice(imported.held_rows, start, start + 50).map((one) => ({
513
- sheet: [sheet_id],
514
- plant: isNull(one.record_id) ? [] : [one.record_id],
515
- line: one.line,
516
- outcome: "held",
517
- why: one.message,
518
- code: toString(sheet.rows[coalesce(one.line, 2) - 2]["Code"]),
519
- name: toString(sheet.rows[coalesce(one.line, 2) - 2]["Name"]),
520
- price: toNumber(sheet.rows[coalesce(one.line, 2) - 2]["Price"]),
521
- changes: join(one.changes.map((change) => `${change.label}: ${change.before ?? "—"} → ${change.after ?? "—"}`), "; "),
522
- })),
453
+
454
+ return({ status: "success", message: `${added} added, ${changed} changed, ${skipped} skipped` });
455
+ ```
456
+
457
+ One `save_record`, a workflow step, per row writes about a hundred rows a second on a table of thirty fields with a link, a lookup and a
458
+ formula: a thousand rows took ten seconds. A run whose writes finish within twenty seconds lands all or nothing; a
459
+ longer one starts again, each row written as it is reached, and three thousand rows took seventy of the ninety seconds
460
+ an awaited call gives a run. A sheet of up to about a thousand rows loops; a larger one is written in batches.
461
+
462
+ The batched form reads the table's keys once and writes in calls of up to a thousand rows. `query_records` the table
463
+ in pages, `groupBy` the key, split the sheet's rows into those with no row yet and those whose cells differ, then
464
+ `create_records` the first and `update_records` the second in its per-record form (`field_keys` and one `rows` entry per
465
+ `record_ids` entry). Ten thousand rows took about seven seconds, a repeat with nothing changed under three, and the
466
+ whole of it is one transaction at that size. The body does the comparison, so it writes only what differs:
467
+
468
+ ```
469
+ const inputs = trigger.app_workflow.inputs;
470
+
471
+ const sheet = await excel_get_rows({ // a workflow step
472
+ file_id: inputs.file,
473
+ columns: ["Code", "Name", "Price"],
474
+ });
475
+ const rows = sheet.rows.map((row) => ({ code: toString(row["Code"]), name: toString(row["Name"]), price: toNumber(row["Price"]) }));
476
+
477
+ let held = (await query_records({ table_id: "plants", field_keys: ["code", "name", "price"], pagination: { offset: 0, limit: 1000 } })).records
478
+ .map((one) => ({ id: one.id, code: toString(one.data["code"]), name: toString(one.data["name"]), price: toNumber(one.data["price"]) }));
479
+ for (let start = 1000; start < inputs.row_count; start += 1000) {
480
+ const page = await query_records({ table_id: "plants", field_keys: ["code", "name", "price"], pagination: { offset: start, limit: 1000 } });
481
+ held = concat(held, page.records.map((one) => ({ id: one.id, code: toString(one.data["code"]), name: toString(one.data["name"]), price: toNumber(one.data["price"]) })));
482
+ }
483
+ const byCode = groupBy(held, (one) => one.code);
484
+
485
+ const fresh = filter(rows, (row) => size(byCode[row.code] ?? []) == 0);
486
+ const changed = filter(rows, (row) =>
487
+ size(byCode[row.code] ?? []) > 0 &&
488
+ (requireFirst(byCode[row.code] ?? []).name != row.name || requireFirst(byCode[row.code] ?? []).price != row.price));
489
+
490
+ for (let at = 0; at < size(fresh); at += 1000) {
491
+ await create_records({ table_id: "plants", records: slice(fresh, at, at + 1000) });
492
+ }
493
+ for (let at = 0; at < size(changed); at += 1000) {
494
+ const part = slice(changed, at, at + 1000);
495
+ await update_records({
496
+ table_id: "plants",
497
+ record_ids: part.map((row) => requireFirst(byCode[row.code] ?? []).id),
498
+ field_keys: ["name", "price"],
499
+ rows: part.map((row) => [row.name, row.price]),
523
500
  });
524
501
  }
525
502
 
526
- return({ status: "success", message: `${imported.created} added, ${imported.changed} changed, ${imported.held} held` });
503
+ return({ status: "success", message: `${size(fresh)} added, ${size(changed)} changed` });
527
504
  ```
528
505
 
529
- A held line keeps the cells the sheet states for it, found by the `line` the step answered, in
530
- fields of its own. A held row's `key` and `values` name fields by their keys, as every record a step answers a body does, so
531
- the body reads the sheet again rather than those names. It is applied by the act on it, whose workflow hands the step those values again and
532
- lets it write over what the plant holds. A cell the line holds none of is left out, so a held line
533
- never empties a cell of the plant:
506
+ `inputs.row_count` is a number the act asks beside the file. A key the table keeps `unique` refuses a second row with
507
+ it, so a sheet that carries one key twice fails the `create_records` call, naming it, before any row of that call is
508
+ written.
509
+
510
+ A workflow does not put a run's writes back: that reads the history of what the run wrote, which a member's agent reads
511
+ under the member's own access to the table and no workflow does. A member's agent puts them back with
512
+ `update_records`: `query_audit_logs` on the table shows what the run wrote — the run is what `runtime.execution_id` held in
513
+ it, which a body keeps on a row of its own — and each field's value before it, `update_records` writes that value back as
514
+ the member's own write, `update_records` with `restore: true` brings back a row the run moved to the trash, and
515
+ `delete_records` removes a row the run created. Write a field back only where the row still holds what the run wrote.
516
+
517
+ What a business keeps of a sheet — the file, its counts, the lines waiting for a person — is rows of its own tables,
518
+ written by the workflow that ran. A garden centre brings its grower's price sheet into its plants, and keeps each sheet
519
+ and the lines it skipped. These tables are shown beside the plants, in the same app: the sheets as a List beside the
520
+ plants' (a second List at the root, `reference/app-node`), a sheet's lines on the page it opens. A line keeping what a
521
+ cell held and what it holds now in two fields reads one against the other (`compare`, `reference/list-node`).
522
+
523
+ A skipped line is applied by the act on it, whose workflow reads the line and saves the plant from it. A cell the line
524
+ holds none of is left out, so a skipped line never empties a cell of the plant:
534
525
 
535
526
  ```
536
527
  const line = (await query_records({ table_id: "sheet_lines", record_ids: [trigger.app_workflow.inputs.record_id] })).records[0];
537
528
  const values = {
538
- code: line.data["code"],
539
529
  ...(isEmpty(line.data["name"]) ? {} : { name: line.data["name"] }),
540
530
  ...(isNull(line.data["price"]) ? {} : { price: line.data["price"] }),
541
531
  };
542
532
 
543
- const applied = await import_rows({ // a workflow step
533
+ await save_record({ // a workflow step
544
534
  table_id: "plants",
545
- match: ["code"],
546
- conflicts: { default: "overwrite" },
547
- rows: [{ values }],
535
+ match: { code: line.data["code"] },
536
+ set: values,
548
537
  });
549
- if (applied.held > 0) {
550
- return({ status: "error", message: applied.held_rows[0].message });
551
- }
552
538
 
553
539
  await update_records({ table_id: "sheet_lines", record_ids: [line.id], set: { outcome: "applied" } });
554
540
  return({ status: "success", message: "Applied." });
555
541
  ```
556
542
 
557
- A sheet is put back by a member's agent with `update_records` over the plants its lines name, 50 at a time, from the values
558
- `query_audit_logs` shows for the run the sheet kept.
559
-
560
543
  A shop matches a bank statement to the notes it is owed by an act that states `review`. That act's workflow only
561
544
  proposes: its body calls steps that read and no other, and runs no agent — either is refused when the body is saved —
562
545
  and returns in `data.review` one changeset of the act's table, which the platform writes the approved rows of. Called
@@ -672,6 +655,33 @@ return({
672
655
  });
673
656
  ```
674
657
 
658
+ ### Numbering a row at a moment
659
+
660
+ A number given when a row is signed or issued is an editable number field the workflow fills with the table's highest plus one,
661
+ only while the row has none, so a second press keeps its number. The field carries a one-field `unique` set on its table, so two
662
+ runs that read the same highest are refused, not doubled; the refused run reads the highest again, for three attempts in all, and
663
+ a run still refused after the third fails with that refusal. The last attempt stands outside the `try`, since a `catch` takes any
664
+ tool error, not the unique refusal alone. A sequence per series or year filters the query on it and states a two-field `unique`.
665
+
666
+ ```
667
+ if (isNull(record.no)) {
668
+ let numbered = false;
669
+ for (let attempt = 0; attempt < 2 && !numbered; attempt++) {
670
+ const top = await query_records({ table_id: "contracts", sort: [{ field_key: "no", order: "desc" }], limit: 1 });
671
+ try {
672
+ await update_records({ table_id: "contracts", record_ids: [record.id], set: { no: coalesce(first(top.records)?.data["no"], 0) + 1 } });
673
+ numbered = true;
674
+ } catch (e) {
675
+ numbered = false;
676
+ }
677
+ }
678
+ if (!numbered) {
679
+ const last = await query_records({ table_id: "contracts", sort: [{ field_key: "no", order: "desc" }], limit: 1 });
680
+ await update_records({ table_id: "contracts", record_ids: [record.id], set: { no: coalesce(first(last.records)?.data["no"], 0) + 1 } });
681
+ }
682
+ }
683
+ ```
684
+
675
685
  ## Reaching a connected service
676
686
 
677
687
  A service is reached only by a workflow step, and a step is called inside an app's workflow or an automation. From
@@ -751,8 +761,7 @@ neither `prev_record` nor `changes`.
751
761
  A write that recomputes another table's rows (a rollup over lines, a lookup or a formula over a parent) judges each recomputed row as an update, by the checks `on` `update` that read a field the recompute changed; `changes` is what the recompute changed. A check that refuses on `changes` or on a status the row holds can therefore refuse the write that moved the parent, so it is gated on the field it means (`!isNull(changes.status)`).
752
762
 
753
763
  A lookup reads with the access of the member who last saved the check, so saving one requires reading
754
- every table its lookups read. It reads committed rows: two writes at the same moment can each pass a
755
- check the other would fail, so values no two rows may share are the table's `unique`, not a check.
764
+ every table its lookups read. A check's reads wait on the writes they depend on: the rows its links name are locked before it reads, and any other lookup takes a lock per check, so two writes at the same moment can't both pass a check the other would fail. Values no two rows may share are the table's `unique`.
756
765
 
757
766
  A `when`, a lookup or a `fail_when` that cannot decide — it fails, or the write's time runs out —
758
767
  refuses the write, naming the part it was reading and, for an expression or a filter, what it met
@@ -834,7 +843,7 @@ that calls a tool changing a table, an app or any other structure is refused whe
834
843
  it reaches the tables the owner reaches, and its writes meet the table's checks like any other write; a write refused by a
835
844
  check fails that run and leaves the row as it was. A body names a field by alias where it can tell which table's field it is: a
836
845
  read of `record`, `prev_record` or `changes`, a row from `query_records` called with a literal `table_id`, and a
837
- loop over such rows. A name it cannot tie to a table, and an option compared to a value of unknown type (not a read of a field, and
846
+ loop over such rows, each also when held in an object, a list or a spread. A name it cannot tie to a table, and an option compared to a value of unknown type (not a read of a field, and
838
847
  not a text, number or other value the type proves holds no option), are refused with what to change. A link reads as the list of the row ids it holds, a one-row link too: compare `first(record.customer) == id`. A lookup reads as one flat list of what it looks up: `record.x != prev_record.x` on one is refused, so compare `first(record.x)` with `first(prev_record.x)`. A single member, a single select, a number or a text reads as the value itself: `first(record.technician)` is refused at save, naming the read.
839
848
 
840
849
  A write the workflow itself makes sets off the workflows of its table in turn, and a chain of them stops after five. A workflow
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lotics/cli",
3
- "version": "0.318.32",
3
+ "version": "0.318.34",
4
4
  "description": "Lotics SDK and CLI for AI agents",
5
5
  "type": "module",
6
6
  "bin": {