@ancha-labs/cli 0.4.12 → 0.4.14

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.
@@ -29,6 +29,13 @@ var SIGNS = {
29
29
  ItemRcpt: [null, 1, 1],
30
30
  Journal: [null, 1, 1]
31
31
  };
32
+ var KEPT_DDL = `
33
+ CREATE TABLE ns_records (type TEXT NOT NULL, id INTEGER NOT NULL, externalid TEXT, fields TEXT NOT NULL DEFAULT '{}', PRIMARY KEY(type, id));
34
+ CREATE INDEX ns_records_externalid ON ns_records (type, externalid COLLATE NOCASE);
35
+ CREATE TABLE ns_record_types (type TEXT PRIMARY KEY);
36
+ CREATE TABLE ns_extra (owner TEXT NOT NULL, id INTEGER NOT NULL, fields TEXT NOT NULL DEFAULT '{}', PRIMARY KEY(owner, id));
37
+ CREATE TABLE ns_fields (recordtype TEXT NOT NULL, sublist TEXT NOT NULL DEFAULT '', field TEXT NOT NULL, owner TEXT NOT NULL, kind TEXT NOT NULL, target TEXT,
38
+ PRIMARY KEY(recordtype, sublist, field));`;
32
39
  var signed = (column, which) => `CASE t.type ${Object.entries(SIGNS).filter(([, s]) => s[which] !== null).map(([type, s]) => `WHEN '${type}' THEN ${s[which]} * ${column}`).join(" ")} ELSE NULL END`;
33
40
  var bool = (column) => `CASE ${column} WHEN 1 THEN 'T' ELSE 'F' END`;
34
41
  var NS_DDL = `
@@ -65,6 +72,7 @@ CREATE TABLE ns_applications (payment INTEGER NOT NULL, source INTEGER NOT NULL,
65
72
  doc INTEGER NOT NULL, docline INTEGER NOT NULL DEFAULT 0, amount REAL NOT NULL CHECK(amount > 0), PRIMARY KEY(payment, source, sourceline, doc, docline));
66
73
  CREATE INDEX ns_applications_source ON ns_applications (source, sourceline);
67
74
  CREATE INDEX ns_applications_target ON ns_applications (doc, docline);
75
+ CREATE INDEX ns_lines_item ON ns_lines (item);
68
76
  -- General ledger impact, rewritten whenever its transaction is saved: one row per account a line debits or credits.
69
77
  CREATE TABLE ns_gl (id INTEGER PRIMARY KEY AUTOINCREMENT, "transaction" INTEGER NOT NULL, line INTEGER NOT NULL, account INTEGER NOT NULL, debit REAL, credit REAL,
70
78
  entity INTEGER, department INTEGER, location INTEGER, class INTEGER, memo TEXT);
@@ -92,13 +100,14 @@ CREATE TABLE ns_oauth (token TEXT PRIMARY KEY, kind TEXT NOT NULL, client TEXT N
92
100
  CREATE INDEX ns_oauth_chain ON ns_oauth (chain);
93
101
  CREATE TABLE ns_sequences (recordtype TEXT PRIMARY KEY, next INTEGER NOT NULL);
94
102
  CREATE TABLE ns_history (ordinal INTEGER PRIMARY KEY AUTOINCREMENT, recordtype TEXT NOT NULL, id INTEGER NOT NULL, operation TEXT NOT NULL, at TEXT NOT NULL);
103
+ ${KEPT_DDL}
95
104
 
96
- -- What an invoice or bill still owes: its total less what payments, credits and deposit applications applied to it.
97
- CREATE VIEW ns_open AS SELECT t.id, t.total - COALESCE((SELECT SUM(a.amount) FROM ns_applications a WHERE a.doc = t.id), 0) AS unpaid FROM ns_transactions t;
98
- -- What a payment, credit or deposit has left: its total less what it applied, what refunds paid out of it and, for a deposit, what was applied from it.
99
- CREATE VIEW ns_unapplied AS SELECT t.id, t.total - COALESCE((SELECT SUM(a.amount) FROM ns_applications a WHERE a.source = t.id), 0)
105
+ -- What an invoice or bill still owes, in cents: its total less what payments, credits and deposit applications applied to it.
106
+ CREATE VIEW ns_open AS SELECT t.id, ROUND(t.total - COALESCE((SELECT SUM(a.amount) FROM ns_applications a WHERE a.doc = t.id), 0), 2) AS unpaid FROM ns_transactions t;
107
+ -- What a payment, credit or deposit has left, in cents: its total less what it applied, what refunds paid out of it and, for a deposit, what was applied from it.
108
+ CREATE VIEW ns_unapplied AS SELECT t.id, ROUND(t.total - COALESCE((SELECT SUM(a.amount) FROM ns_applications a WHERE a.source = t.id), 0)
100
109
  - COALESCE((SELECT SUM(a.amount) FROM ns_applications a WHERE a.doc = t.id), 0)
101
- - COALESCE((SELECT SUM(d.total) FROM ns_transactions d WHERE d.type = 'DepAppl' AND d.createdfrom = t.id), 0) AS unapplied FROM ns_transactions t;
110
+ - COALESCE((SELECT SUM(d.total) FROM ns_transactions d WHERE d.type = 'DepAppl' AND d.createdfrom = t.id), 0), 2) AS unapplied FROM ns_transactions t;
102
111
  -- Original open items, with opposite journal lines netted in original line order within each party/account.
103
112
  CREATE VIEW ns_item_original AS WITH raw AS (
104
113
  SELECT t.id AS doc, l.line, CASE a.accttype WHEN 'AcctRec' THEN 'receivable' ELSE 'payable' END AS side,
@@ -133,18 +142,18 @@ CREATE VIEW ns_stock AS
133
142
  CREATE VIEW ns_q_customer AS SELECT e.id, e.entityid, e.companyname, e.firstname, e.lastname, ${bool("e.isperson")} AS isperson,
134
143
  e.email, e.phone, e.fax, e.url, ${bool("e.isinactive")} AS isinactive, e.creditlimit, e.credithold, e.credithold AS creditholdoverride, e.terms, e.subsidiary, e.currency, e.comments,
135
144
  e.salesrep, e.externalid, e.datecreated, e.lastmodifieddate, e.extra,
136
- COALESCE((SELECT SUM(CASE i.role WHEN 'debt' THEN i.original ELSE -i.original END) FROM ns_item_original i WHERE i.side='receivable' AND i.entity=e.id AND i.currency=e.currency),0)
145
+ ROUND(COALESCE((SELECT SUM(CASE i.role WHEN 'debt' THEN i.original ELSE -i.original END) FROM ns_item_original i WHERE i.side='receivable' AND i.entity=e.id AND i.currency=e.currency),0)
137
146
  - COALESCE((SELECT SUM(t.total) FROM ns_transactions t WHERE t.type='DepAppl' AND t.entity=e.id AND t.currency=e.currency),0)
138
- + COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions p ON p.id=a.payment JOIN ns_transactions d ON d.id=a.doc WHERE p.type='CustRfnd' AND p.entity=e.id AND p.currency=e.currency AND d.type<>'CustDep'),0) AS balance,
139
- COALESCE((SELECT SUM(o.unpaid) FROM ns_transactions t JOIN ns_open o ON o.id = t.id WHERE t.entity = e.id AND t.type = 'CustInvc' AND t.duedate < ns_today()), 0) AS overduebalance,
140
- COALESCE((SELECT SUM(u.unapplied) FROM ns_transactions t JOIN ns_unapplied u ON u.id = t.id WHERE t.entity = e.id AND t.type = 'CustDep'), 0) AS depositbalance,
147
+ + COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions p ON p.id=a.payment JOIN ns_transactions d ON d.id=a.doc WHERE p.type='CustRfnd' AND p.entity=e.id AND p.currency=e.currency AND d.type<>'CustDep'),0), 2) AS balance,
148
+ ROUND(COALESCE((SELECT SUM(o.unpaid) FROM ns_transactions t JOIN ns_open o ON o.id = t.id WHERE t.entity = e.id AND t.type = 'CustInvc' AND t.duedate < ns_today()), 0), 2) AS overduebalance,
149
+ ROUND(COALESCE((SELECT SUM(u.unapplied) FROM ns_transactions t JOIN ns_unapplied u ON u.id = t.id WHERE t.entity = e.id AND t.type = 'CustDep'), 0), 2) AS depositbalance,
141
150
  COALESCE((SELECT SUM(ROUND(CASE WHEN l.quantity > 0 THEN MAX(0, l.quantity - l.quantitybilled) * l.amount / l.quantity ELSE 0 END, 2)) FROM ns_lines l JOIN ns_transactions t ON t.id = l."transaction"
142
151
  WHERE t.entity = e.id AND t.type = 'SalesOrd' AND COALESCE(t.status, '') NOT IN ('C', 'H') AND l.sublist = 'item' AND l.isclosed = 0), 0) AS unbilledorders
143
152
  FROM ns_entities e WHERE e.kind = 'customer';
144
153
  CREATE VIEW ns_q_vendor AS SELECT e.id, e.entityid, e.companyname, e.legalname, e.accountnumber, e.email, e.phone, e.fax, e.url, ${bool("e.isinactive")} AS isinactive,
145
154
  ${bool("e.is1099eligible")} AS is1099eligible, e.terms, e.subsidiary, e.currency, e.comments, e.externalid, e.datecreated, e.lastmodifieddate, e.extra,
146
- COALESCE((SELECT SUM(CASE i.role WHEN 'debt' THEN i.original ELSE -i.original END) FROM ns_item_original i WHERE i.side='payable' AND i.entity=e.id AND i.currency=e.currency),0)
147
- - COALESCE((SELECT SUM(t.total) FROM ns_transactions t WHERE t.type='VendPymt' AND t.entity=e.id AND t.currency=e.currency),0) AS balance
155
+ ROUND(COALESCE((SELECT SUM(CASE i.role WHEN 'debt' THEN i.original ELSE -i.original END) FROM ns_item_original i WHERE i.side='payable' AND i.entity=e.id AND i.currency=e.currency),0)
156
+ - COALESCE((SELECT SUM(t.total) FROM ns_transactions t WHERE t.type='VendPymt' AND t.entity=e.id AND t.currency=e.currency),0), 2) AS balance
148
157
  FROM ns_entities e WHERE e.kind = 'vendor';
149
158
  CREATE VIEW ns_q_contact AS SELECT e.id, e.entityid, e.firstname, e.lastname, e.title, e.email, e.phone, e.mobilephone, e.company, ${bool("e.isinactive")} AS isinactive,
150
159
  e.comments, e.subsidiary, e.externalid, e.datecreated, e.lastmodifieddate, e.extra FROM ns_entities e WHERE e.kind = 'contact';
@@ -185,23 +194,24 @@ CREATE VIEW ns_q_transaction AS SELECT t.id, t.tranid, t.trandate, t.type, t.rec
185
194
  t.currency, t.exchangerate, t.otherrefnum, t.externalid, t.datecreated AS createddate, t.lastmodifieddate, t.total AS foreigntotal, t.postingperiod, t.employee, t.salesrep, t.extra,
186
195
  ${bool('EXISTS (SELECT 1 FROM ns_gl g WHERE g."transaction" = t.id)')} AS posting, 'F' AS voided,
187
196
  CASE WHEN t.type IN ('CustInvc', 'VendBill') THEN o.unpaid END AS foreignamountunpaid,
188
- CASE WHEN t.type IN ('CustInvc', 'VendBill') THEN t.total - o.unpaid END AS foreignamountpaid,
197
+ CASE WHEN t.type IN ('CustInvc', 'VendBill') THEN ROUND(t.total - o.unpaid, 2) END AS foreignamountpaid,
189
198
  CASE WHEN t.type IN ('CustInvc', 'VendBill') AND o.unpaid > 0 AND t.duedate < ns_today()
190
199
  THEN CAST(julianday(ns_today()) - julianday(t.duedate) AS INTEGER) ELSE 0 END AS daysoverdue
191
200
  FROM ns_transactions t JOIN ns_open o ON o.id = t.id;
192
201
  -- One row per transaction for its main line (the AR/AP/bank side), then one per sublist line. Lines carry NetSuite's
193
- -- native signs: an invoice's main line is +total and its item lines are negative; a bill's are the reverse.
202
+ -- native signs: an invoice's main line is +total and its item lines are negative; a bill's are the reverse. foreignamount
203
+ -- is in the transaction's currency, netamount in the base currency at the transaction's exchange rate.
194
204
  CREATE VIEW ns_q_transactionline AS
195
205
  -- Reserve four digits for the line; transaction IDs up to 2000000000 stay below 2^53.
196
206
  SELECT 0 AS id, t.id * 10000 AS uniquekey, t.id AS "transaction", 0 AS linesequencenumber, 'T' AS mainline, 'F' AS taxline, NULL AS item, NULL AS itemtype, NULL AS quantity,
197
- NULL AS rate, ${signed("t.total", 0)} AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
207
+ NULL AS rate, ns_round(${signed("t.total", 0)} * t.exchangerate) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
198
208
  t.department, t.location, t.class, t.createdfrom, 'F' AS isclosed,
199
209
  NULL AS debit, NULL AS credit, NULL AS quantitybilled, NULL AS quantityshiprecv, NULL AS quantitycommitted, NULL AS category, NULL AS costestimate, t.extra, 'F' AS iscogs
200
210
  FROM ns_transactions t WHERE t.type <> 'Journal'
201
211
  UNION ALL
202
212
  SELECT l.line AS id, l."transaction" * 10000 + l.line AS uniquekey, l."transaction", l.line, 'F', 'F', l.item, i.itemtype,
203
213
  ${signed("l.quantity", 2)}, l.rate,
204
- CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END,
214
+ ns_round(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate),
205
215
  CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END,
206
216
  COALESCE(l.memo, l.description), l.account, l.account, COALESCE(l.entity, t.entity), t.subsidiary, COALESCE(l.department, t.department),
207
217
  COALESCE(l.location, t.location), COALESCE(l.class, t.class), l.createdfrom, ${bool("l.isclosed")}, l.debit, l.credit,
@@ -211,7 +221,7 @@ CREATE VIEW ns_q_transactionline AS
211
221
  FROM ns_lines l JOIN ns_transactions t ON t.id = l."transaction" LEFT JOIN ns_items i ON i.id = l.item WHERE l.sublist <> 'apply'
212
222
  UNION ALL
213
223
  SELECT 5000 + l.line, t.id * 10000 + 5000 + l.line, t.id, 5000 + l.line, 'F', 'F', l.item, i.itemtype,
214
- ${signed("l.quantity", 2)}, NULL, (COALESCE(g.debit, 0) - COALESCE(g.credit, 0)) / t.exchangerate,
224
+ ${signed("l.quantity", 2)}, NULL, COALESCE(g.debit, 0) - COALESCE(g.credit, 0),
215
225
  (COALESCE(g.debit, 0) - COALESCE(g.credit, 0)) / t.exchangerate, COALESCE(l.memo, l.description), g.account, g.account,
216
226
  g.entity, t.subsidiary, g.department, g.location, g.class, l.createdfrom, 'F', g.debit / t.exchangerate, g.credit / t.exchangerate,
217
227
  NULL, NULL, NULL, NULL, l.cost, l.extra, 'T'
@@ -531,7 +541,115 @@ var CUSTOM_TABLES = {
531
541
  custitem: ["item"]
532
542
  };
533
543
  var ENTITY_KINDS = { customer: "customer", vendor: "vendor", contact: "contact", employee: "employee" };
534
- function suiteqlTables(fields) {
544
+ function readCatalog(db) {
545
+ if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'ns_fields'").get()) return { plain: [], fields: [] };
546
+ return {
547
+ plain: db.prepare("SELECT type FROM ns_record_types ORDER BY type").all().map((row) => row.type),
548
+ fields: db.prepare("SELECT recordtype, sublist, field, owner, kind, target FROM ns_fields ORDER BY recordtype, sublist, field").all()
549
+ };
550
+ }
551
+ function givenSql(json, field, kind) {
552
+ const path = `'$."${field}"'`;
553
+ if (kind === "boolean") return `CASE json_type(${json}, ${path}) WHEN 'true' THEN 'T' WHEN 'false' THEN 'F' END`;
554
+ const value = `CASE json_type(${json}, ${path}) WHEN 'object' THEN json_extract(${json}, '$."${field}".id') ELSE json_extract(${json}, ${path}) END`;
555
+ return kind === "ref" ? `CAST(${value} AS INTEGER)` : value;
556
+ }
557
+ var KIND_TYPES = { "": "text", text: "text", enum: "text", number: "number", boolean: "boolean", date: "date", datetime: "datetime", ref: "id" };
558
+ var TRANSACTION_TYPES = /* @__PURE__ */ new Set([
559
+ "estimate",
560
+ "salesOrder",
561
+ "itemFulfillment",
562
+ "invoice",
563
+ "cashSale",
564
+ "cashRefund",
565
+ "creditMemo",
566
+ "customerPayment",
567
+ "customerDeposit",
568
+ "depositApplication",
569
+ "customerRefund",
570
+ "returnAuthorization",
571
+ "purchaseOrder",
572
+ "itemReceipt",
573
+ "vendorBill",
574
+ "vendorCredit",
575
+ "vendorPayment",
576
+ "vendorReturnAuthorization",
577
+ "journalEntry",
578
+ "expenseReport"
579
+ ]);
580
+ var targetTable = (target) => /Item$/.test(target) ? "item" : TRANSACTION_TYPES.has(target) ? "transaction" : target.toLowerCase();
581
+ var keptTable = (field) => field.owner === "entity" ? field.recordtype : field.owner === "item" ? "item" : field.owner === "transaction" ? field.sublist ? "transactionline" : "transaction" : field.recordtype.toLowerCase();
582
+ function merge(a, b) {
583
+ const both = (x, y) => a === x && b === y || a === y && b === x;
584
+ return a === b || b === "" ? a : a === "" ? b : both("ref", "enum") ? "enum" : both("date", "datetime") ? "datetime" : both("ref", "number") ? "ref" : "text";
585
+ }
586
+ function keptTables(tables, catalog) {
587
+ const byName = new Map(tables.map((table) => [table.name, table]));
588
+ const lookups = [];
589
+ const lookup = (table, column, kind, json, field, from) => {
590
+ const name = `${table}.${column}`, id = givenSql(json, field, kind);
591
+ lookups.push({
592
+ name,
593
+ view: "ns_records",
594
+ display: "name",
595
+ columns: [col("id", KIND_TYPES[kind]), col("name", "text")],
596
+ source: `SELECT ${id} AS "id", MIN(json_extract(${json}, '$."${field}".refName')) AS "name" FROM ${from} AND json_type(${json}, '$."${field}"') = 'object' GROUP BY 1`
597
+ });
598
+ return name;
599
+ };
600
+ const reference = (field, kind, table, column, json, from) => {
601
+ if (kind !== "ref" && kind !== "enum") return {};
602
+ const target = field.target === null ? void 0 : targetTable(field.target);
603
+ return { ref: target !== void 0 && (byName.has(target) || catalog.plain.some((type) => type.toLowerCase() === target)) ? target : lookup(table, column, kind, json, field.field, from) };
604
+ };
605
+ const plainName = (field) => /^[A-Za-z][A-Za-z0-9_]*$/.test(field) ? field.toLowerCase() : void 0;
606
+ const kinds = (fields) => {
607
+ const merged = /* @__PURE__ */ new Map();
608
+ for (const field of fields) {
609
+ const prior = merged.get(field.field);
610
+ merged.set(field.field, prior ? { ...prior, kind: merge(prior.kind, field.kind), target: prior.target ?? field.target } : field);
611
+ }
612
+ return [...merged.values()];
613
+ };
614
+ const extended = tables.map((table) => {
615
+ const fields = kinds(catalog.fields.filter((field) => field.owner !== "" && keptTable(field) === table.name));
616
+ if (!fields.length) return table;
617
+ const columns = [...table.columns], names = new Set(columns.map((c) => c.name)), lines = table.name === "transactionline";
618
+ for (const field of fields) {
619
+ const name = plainName(field.field), type = KIND_TYPES[field.kind];
620
+ if (name === void 0 || type === void 0 || names.has(name)) continue;
621
+ names.add(name);
622
+ const json = lines ? "extra" : "x.fields";
623
+ const value = givenSql(json, field.field, field.kind);
624
+ const from = lines ? `${table.view} WHERE 1 = 1` : `ns_extra x WHERE x.owner = '${field.owner}'`;
625
+ columns.push(col(name, type, {
626
+ sql: lines ? value : `(SELECT ${value} FROM ns_extra x WHERE x.owner = '${field.owner}' AND x.id = "${table.view}"."id")`,
627
+ ...reference(field, field.kind, table.name, name, json, from)
628
+ }));
629
+ }
630
+ return { ...table, columns };
631
+ });
632
+ const plain = catalog.plain.map((type) => {
633
+ const name = type.toLowerCase(), columns = [col("id", "id"), col("externalid", "text")], selects = ['r.id AS "id"', 'r.externalid AS "externalid"'];
634
+ const names = /* @__PURE__ */ new Set(["id", "externalid"]), from = `ns_records r WHERE r.type = '${type}'`;
635
+ for (const field of kinds(catalog.fields.filter((f) => f.owner === "" && f.recordtype === type))) {
636
+ const column = plainName(field.field), kind = field.kind, nsType = KIND_TYPES[kind];
637
+ if (column === void 0 || nsType === void 0 || names.has(column)) continue;
638
+ names.add(column);
639
+ columns.push(col(column, nsType, reference(field, kind, name, column, "r.fields", from)));
640
+ selects.push(`${givenSql("r.fields", field.field, kind)} AS "${column}"`);
641
+ }
642
+ const display = ["name", "entityid", "companyname", "title", "tranid"].find((column) => names.has(column)) ?? "id";
643
+ return { name, view: "ns_records", display, columns, source: `SELECT ${selects.join(", ")} FROM ${from}` };
644
+ });
645
+ const replaced = new Set(plain.map((table) => table.name));
646
+ return [...extended.filter((table) => !replaced.has(table.name)), ...plain, ...lookups];
647
+ }
648
+ function suiteqlTables(fields, catalog) {
649
+ const custom = customTables(fields);
650
+ return catalog && (catalog.plain.length || catalog.fields.length) ? keptTables(custom, catalog) : custom;
651
+ }
652
+ function customTables(fields) {
535
653
  if (!fields.length) return SUITEQL_TABLES;
536
654
  return SUITEQL_TABLES.map((table) => {
537
655
  const extra = fields.filter((f) => {
@@ -669,6 +787,15 @@ var DISPLAY = {
669
787
  shipstatus: { A: "Picked", B: "Packed", C: "Shipped" }
670
788
  };
671
789
 
790
+ // packages/core/src/tools/netsuite-money.ts
791
+ var netsuiteRound = (value) => Math.sign(value) * Math.round(Number(`${Math.abs(value).toFixed(10)}e2`)) / 100 || 0;
792
+
793
+ // packages/server/src/twins/netsuite/money.ts
794
+ var round = netsuiteRound;
795
+ function registerRound(db) {
796
+ db.function("ns_round", { deterministic: true }, (value) => value === null || value === void 0 ? null : round(Number(value)));
797
+ }
798
+
672
799
  // packages/server/src/twins/netsuite/suiteql.ts
673
800
  var SuiteqlError = class extends Error {
674
801
  gap;
@@ -1419,7 +1546,7 @@ var Compiler = class {
1419
1546
  const table = this.tables.find((t) => t.name === source.table);
1420
1547
  if (!table) invalid(`Record '${source.table}' was not found.`);
1421
1548
  const computed = table.columns.filter((c) => c.sql);
1422
- value = computed.length ? sql("(SELECT *, ", computed.map((c) => `${c.sql} AS ${quote(c.name)}`).join(", "), " FROM ", quote(table.view), ")") : sql(quote(table.view));
1549
+ value = table.source ? sql("(", table.source, ")") : computed.length ? sql("(SELECT *, ", computed.map((c) => `${c.sql} AS ${quote(c.name)}`).join(", "), " FROM ", quote(table.view), ")") : sql(quote(table.view));
1423
1550
  columns = table.columns.map((column) => ({ name: column.name, type: column.type, value: sql(""), origin: { table, column, relation: alias } }));
1424
1551
  }
1425
1552
  columns = columns.map((c) => ({ ...c, value: sql(`${quote(alias)}.${quote(c.name)}`) }));
@@ -1724,7 +1851,7 @@ var Compiler = class {
1724
1851
  if (!mode || !modes.includes(mode)) invalid("BUILTIN.HIERARCHY requires a valid expansion type literal.");
1725
1852
  const table = origin && this.tables.find((t) => t.name === (origin.column.ref ?? (origin.column.name === "id" ? origin.table.name : "")));
1726
1853
  const parent = table?.columns.find((c) => c.name === "parent" || c.name === "supervisor");
1727
- if (!table || !parent) invalid("BUILTIN.HIERARCHY requires a hierarchical field.");
1854
+ if (!table || !parent || table.source) invalid("BUILTIN.HIERARCHY requires a hierarchical field.");
1728
1855
  return bound(sql("ns_suiteql_hierarchy(", param(table.view), ", ", param(parent.name), ", ", param(table.display), ", ", a, ", ", args[1], ")"), mode === "LEVEL" ? "integer" : "text", args);
1729
1856
  }
1730
1857
  case "builtin.df": {
@@ -1734,7 +1861,7 @@ var Compiler = class {
1734
1861
  const table = this.tables.find((t) => t.name === origin.column.ref);
1735
1862
  if (!table) invalid("BUILTIN.DF requires a reference or coded column.");
1736
1863
  const alias = "sq_display";
1737
- return bound(sql("(SELECT ", `${quote(alias)}.${quote(table.display)}`, " FROM ", quote(table.view), " AS ", quote(alias), " WHERE ", `${quote(alias)}."id" = `, a, ")"), "text", args);
1864
+ return bound(sql("(SELECT ", `${quote(alias)}.${quote(table.display)}`, " FROM ", table.source ? `(${table.source})` : quote(table.view), " AS ", quote(alias), " WHERE ", `${quote(alias)}."id" = `, a, ")"), "text", args);
1738
1865
  }
1739
1866
  if (origin.column.display) {
1740
1867
  return bound(sql("(CASE ", a, ...Object.entries(DISPLAY[origin.column.display]).map(([k, v]) => sql(" WHEN ", param(k), " THEN ", param(v))), " ELSE NULL END)"), "text", args);
@@ -1833,7 +1960,7 @@ var Compiler = class {
1833
1960
  function compileSuiteql(query, opts) {
1834
1961
  const values = (opts.params ?? []).map(bindValue), parser = new Parser(query), parsed = parser.parse();
1835
1962
  if (parser.markers !== values.length) invalid(`The query has ${parser.markers} ? marker${parser.markers === 1 ? "" : "s"} and ${values.length} params value${values.length === 1 ? "" : "s"}.`);
1836
- const result = new Compiler({ today: opts.today, now: opts.now, tables: suiteqlTables(opts.customFields ?? []), values }).query(parsed, void 0, MAX_RESULTS);
1963
+ const result = new Compiler({ today: opts.today, now: opts.now, tables: suiteqlTables(opts.customFields ?? [], opts.catalog), values }).query(parsed, void 0, MAX_RESULTS);
1837
1964
  return { sql: result.sql, params: result.params, columns: result.columns.map((c) => ({ name: c.name, type: c.type === "null" ? "text" : c.type })) };
1838
1965
  }
1839
1966
  function bindValue(value) {
@@ -2211,6 +2338,7 @@ var nth = (re, source, position, occurrence) => {
2211
2338
  return void 0;
2212
2339
  };
2213
2340
  function installFunctions(db, hierarchy) {
2341
+ registerRound(db);
2214
2342
  const register = (name, fn) => {
2215
2343
  db.function(`ns_suiteql_${name}`, { deterministic: true, varargs: true }, fn);
2216
2344
  };
@@ -2454,7 +2582,7 @@ function runSuiteqlMapped(db, query, page, opts) {
2454
2582
  function scan(db, query, page, opts) {
2455
2583
  if (!Number.isSafeInteger(page.limit) || page.limit < 0 || !Number.isSafeInteger(page.offset) || page.offset < 0) invalid("Invalid paging values.");
2456
2584
  if (page.offset >= MAX_RESULTS) invalid("Offset must be less than the 100000 result limit.");
2457
- const compiled = compileSuiteql(query, opts);
2585
+ const compiled = compileSuiteql(query, { ...opts, catalog: opts.catalog ?? readCatalog(db) });
2458
2586
  installFunctions(db, compiled.sql.includes("ns_suiteql_hierarchy("));
2459
2587
  try {
2460
2588
  return db.transaction(() => {
@@ -28,18 +28,51 @@ const calls = [
28
28
  ['LOB_API_URL', 'letters?limit=1', basic(env.LOB_API_KEY)],
29
29
  ['INTERCOM_API_URL', 'conversations?per_page=1', { ...bearer(env.INTERCOM_ACCESS_TOKEN), Accept: 'application/json' }],
30
30
  ['TWILIO_API_URL', `2010-04-01/Accounts/${env.TWILIO_ACCOUNT_SID}/Messages.json?PageSize=1`, basic(env.TWILIO_ACCOUNT_SID, env.TWILIO_AUTH_TOKEN)],
31
+ ['HUBSPOT_API_URL', 'crm/v3/objects/companies?limit=1', bearer(env.HUBSPOT_ACCESS_TOKEN)],
32
+ ['NETSUITE_API_URL', 'services/rest/record/v1/customer?limit=1', bearer(env.NETSUITE_ACCESS_TOKEN)],
33
+ ['LINKEDIN_ADS_API_URL', 'rest/adAccounts?q=search', { ...bearer(env.LINKEDIN_ADS_TOKEN), 'LinkedIn-Version': '202610', 'X-Restli-Protocol-Version': '2.0.0' }],
34
+ ['GONG_API_URL', 'v2/calls?fromDateTime=2000-01-01T00:00:00Z&toDateTime=2100-01-01T00:00:00Z', basic(env.GONG_ACCESS_KEY, env.GONG_ACCESS_KEY_SECRET)],
35
+ ['GA4_API_URL', 'v1beta/properties/0/metadata', bearer(env.GA4_ACCESS_TOKEN)],
36
+ ['OPENAI_ADS_API_URL', 'v1/ad_account', bearer(env.OPENAI_ADS_API_KEY)],
37
+ ['OPEN_METEO_API_URL', 'v1/forecast?latitude=52.52&longitude=13.41&current=temperature_2m', {}],
38
+ ['BETTER_STACK_API_URL', 'api/v2/monitors', bearer(env.BETTER_STACK_API_TOKEN)],
39
+ ['ATTIO_API_URL', 'v2/objects', bearer(env.ATTIO_API_KEY)],
40
+ ['JIRA_BASE_URL', 'rest/api/3/myself', { ...basic(env.JIRA_EMAIL, env.JIRA_API_TOKEN), Accept: 'application/json' }],
41
+ ['ZENDESK_API_URL', 'users/me.json', basic(`${env.ZENDESK_EMAIL}/token`, env.ZENDESK_API_TOKEN)],
42
+ ['ASANA_API_URL', 'users/me', bearer(env.ASANA_ACCESS_TOKEN)],
43
+ ['DISCORD_API_URL', 'users/@me', { Authorization: `Bot ${env.DISCORD_BOT_TOKEN}` }],
44
+ ['SENTRY_API_URL', 'api/0/organizations/', bearer(env.SENTRY_AUTH_TOKEN)],
45
+ ['AIRTABLE_API_URL', 'meta/bases', bearer(env.AIRTABLE_API_KEY)],
31
46
  ];
32
- for (const [variable, path, headers, body] of calls) {
33
- const base = env[variable];
34
- if (!base) continue;
47
+ /** The URL of `path` under a tool's base URL, which must be an Ancha twin. */
48
+ function twinUrl(base, path) {
35
49
  const url = new URL(path ? `${base.replace(/\/+$/, '')}/${path}` : base);
36
50
  // A twin URL is loopback (local server) or carries this environment's /e/<id>/ path (hosted server);
37
51
  // a real API has neither, so the reference companion can never reach one.
38
52
  const envId = env.ANCHA_ENV_ID;
39
53
  const twin = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname) || (envId && url.pathname.includes(`/e/${envId}/`));
40
54
  if (!twin) throw new Error('reference companions only call Ancha twins: a loopback URL or this environment\'s /e/<id>/ path');
41
- const response = await fetch(url, { method: body === undefined ? 'GET' : 'POST', headers, ...(body !== undefined && { body: JSON.stringify(body) }), signal: AbortSignal.timeout(3000) });
55
+ return url;
56
+ }
57
+ for (const [variable, path, headers, body] of calls) {
58
+ const base = env[variable];
59
+ if (!base) continue;
60
+ const response = await fetch(twinUrl(base, path), { method: body === undefined ? 'GET' : 'POST', headers, ...(body !== undefined && { body: JSON.stringify(body) }), signal: AbortSignal.timeout(3000) });
42
61
  if (!response.ok) throw new Error(`${variable}: HTTP ${response.status}`);
43
62
  const result = await response.json();
44
63
  if (result.ok === false) throw new Error(`${variable}: native API error`);
45
64
  }
65
+ // The carrier portal is a web app: sign in with its form (a CSRF token and a session cookie), then read the policies.
66
+ if (env.CARRIER_PORTAL_URL) {
67
+ const base = env.CARRIER_PORTAL_URL, signal = () => AbortSignal.timeout(3000);
68
+ const form = await fetch(twinUrl(base, 'sign-in'), { signal: signal() });
69
+ let cookie = form.headers.get('set-cookie')?.split(';')[0];
70
+ const csrf = /name="csrf" value="([^"]+)"/.exec(await form.text())?.[1] ?? '';
71
+ const fields = { csrf, agency_code: env.CARRIER_PORTAL_AGENCY_CODE, username: env.CARRIER_PORTAL_USERNAME, password: env.CARRIER_PORTAL_PASSWORD };
72
+ const signIn = await fetch(twinUrl(base, 'sign-in'), { method: 'POST', redirect: 'manual', body: new URLSearchParams(fields), signal: signal(),
73
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...(cookie && { Cookie: cookie }) } });
74
+ cookie = signIn.headers.get('set-cookie')?.split(';')[0] ?? cookie;
75
+ if (signIn.status !== 303 || !cookie) throw new Error(`CARRIER_PORTAL_URL: sign-in answered ${signIn.status}`);
76
+ const policies = await fetch(twinUrl(base, 'policies'), { headers: { Cookie: cookie }, redirect: 'manual', signal: signal() });
77
+ if (policies.status !== 200) throw new Error(`CARRIER_PORTAL_URL: HTTP ${policies.status}`);
78
+ }
@@ -415,6 +415,11 @@ function criterion(scene, check) {
415
415
  return [t.called?.length ? traceActions(t.called) : "", t.not_called?.length ? traceActions(t.not_called, true) : ""].filter(Boolean).join("; ");
416
416
  }
417
417
  if (check.judge) return "A grader assesses the agent\u2019s response";
418
+ if (check.answer) {
419
+ const a = check.answer, quoted = (v) => (Array.isArray(v) ? v : v === void 0 ? [] : [v]).map((text2) => `\u201C${text2}\u201D`).join(", ");
420
+ const parts = [a.contains ? `contains ${quoted(a.contains)}` : "", a.numbers?.length ? `states ${a.numbers.map((n) => String(n.value)).join(", ")}` : "", a.not_contains ? `never says ${quoted(a.not_contains)}` : ""].filter(Boolean);
421
+ return parts.length ? `The final answer ${parts.join("; ")}` : "The agent gives a final answer";
422
+ }
418
423
  return "Custom condition: " + String(check.id).replaceAll("_", " ");
419
424
  }
420
425
  function successCriteria(scene) {
@@ -619,6 +624,7 @@ function runStatus(run) {
619
624
  const c = runCounts(run);
620
625
  if (run.status === "stopped" && !c.graded) return "stopped";
621
626
  if (run.status === "error" && !c.graded) return "error";
627
+ if (run.verdict === "ungraded") return "ungraded";
622
628
  if (!c.graded) return c.invalid ? "invalid" : c.skipped && c.skipped === c.total ? "skipped" : "ungraded";
623
629
  if (run.verdict === "pass" || run.verdict === "fail") return run.verdict === "pass" ? "passed" : "failed";
624
630
  return c.passed === c.total ? "passed" : "failed";
@@ -672,7 +678,7 @@ function runMs(run, now) {
672
678
  return terminal(run.status) ? void 0 : now - start;
673
679
  }
674
680
  function view(run, now) {
675
- return { run, status: runStatus(run), title: runTitle(run), agent: String(run.agentName ?? run.entries?.[0]?.agentName ?? ""), where: whereKey(run.origin), ms: runMs(run, now) };
681
+ return { run, status: runStatus(run), title: runTitle(run), agent: String(run.agentName ?? run.entries?.[0]?.agentName ?? ""), command: String(run.agentCommand ?? ""), where: whereKey(run.origin), ms: runMs(run, now) };
676
682
  }
677
683
  function rateCell(row2) {
678
684
  const run = row2.run, c = runCounts(run);
@@ -693,7 +699,7 @@ function startedCell(row2, now) {
693
699
  function row(item, now) {
694
700
  const run = item.run, c = runCounts(run), states = attemptStates(run);
695
701
  const counted = `${c.finished} / ${c.total}`, label2 = `${counted} attempts finished${c.graded ? `, ${c.passed} passed` : ""}${c.invalid ? `, ${c.invalid} invalid` : ""}`;
696
- return `<a class="rt-row" href="/playgrounds/${encodeURIComponent(String(run.id))}" data-nav><span class="rt-result">${statusMark(item.status)}</span><span class="rt-test"><span class="rt-title" title="${h(item.title)}">${h(item.title)}</span><span class="rt-ref mono">${h(runRef(run))}</span></span><span class="rt-agent"><span class="rt-agent-name">${h(item.agent || "\u2014")}</span><span class="c-note">${h(whereLabel(run.origin))}</span></span><span class="rt-attempts">${strip(states, label2)}<span class="c-note">${h(counted)}</span></span><span class="rt-passed">${rateCell(item)}</span><span class="rt-prod">${productionTag(run.reproduction) || '<span class="c-note">\u2014</span>'}</span><span class="rt-started">${startedCell(item, now)}</span></a>`;
702
+ return `<a class="rt-row" href="/playgrounds/${encodeURIComponent(String(run.id))}" data-nav><span class="rt-result">${statusMark(item.status)}</span><span class="rt-test"><span class="rt-title" title="${h(item.title)}">${h(item.title)}</span><span class="rt-ref mono">${h(runRef(run))}</span></span><span class="rt-agent"><span class="rt-agent-name">${h(item.agent || "\u2014")}</span>${item.command ? `<span class="c-note mono rt-command" title="${h(item.command)}">${h(item.command)}</span>` : ""}<span class="c-note">${h(whereLabel(run.origin))}</span></span><span class="rt-attempts">${strip(states, label2)}<span class="c-note">${h(counted)}</span></span><span class="rt-passed">${rateCell(item)}</span><span class="rt-prod">${productionTag(run.reproduction) || '<span class="c-note">\u2014</span>'}</span><span class="rt-started">${startedCell(item, now)}</span></a>`;
697
703
  }
698
704
  function runsTable(runs, options = {}) {
699
705
  const now = options.now ?? Date.now();
@@ -765,7 +771,7 @@ function runsPage(runs, filters, options = {}) {
765
771
  const inRange = range ? all.filter((item) => now - timeOf(item.run.createdAt) <= RANGES[range][1]) : all;
766
772
  const values = (pick, chosen) => [...new Set([...all.map(pick), chosen].filter((v) => Boolean(v)))];
767
773
  const query = String(filters.q ?? "").trim().toLowerCase();
768
- const matches = (item) => !query || [item.title, item.run.id, item.agent, item.run.test?.name, ...(item.run.tasks ?? []).flatMap((t) => [t.id, t.title, t.prompt])].some((v) => String(v ?? "").toLowerCase().includes(query));
774
+ const matches = (item) => !query || [item.title, item.run.id, item.agent, item.command, item.run.test?.name, ...(item.run.tasks ?? []).flatMap((t) => [t.id, t.title, t.prompt])].some((v) => String(v ?? "").toLowerCase().includes(query));
769
775
  const shown = inRange.filter((item) => matches(item) && (!filters.agent || item.agent === filters.agent || item.run.agentId === filters.agent || item.run.entries?.some((entry) => entry.agentId === filters.agent)) && (!filters.result || item.status === filters.result) && (!filters.where || item.where === filters.where) && (!filters.commit || item.run.origin?.commit === filters.commit) && (!filters.source || item.run.origin?.source === filters.source) && (!filters.target || item.run.origin?.target === filters.target));
770
776
  const select = (name, label2, choices, all2 = "All") => `<label class="c-select"><span>${h(label2)}</span><select name="${name}" data-run-filter><option value="">${h(all2)}</option>${choices.map(([value, text2]) => `<option value="${h(value)}" ${filters[name] === value ? "selected" : ""}>${h(text2)}</option>`).join("")}</select></label>`;
771
777
  const commits = values((item) => item.run.origin?.commit, filters.commit);
@@ -1359,7 +1365,7 @@ function runMeta(batch, attempts, tasks) {
1359
1365
  }
1360
1366
  function savedResult(batch) {
1361
1367
  const reproduction = records(batch.reproduction);
1362
- const verdict = batch.summary?.graded === false ? "Ungraded" : batch.verdict === "pass" ? "Pass" : batch.verdict === "fail" ? "Fail" : "";
1368
+ const verdict = batch.summary?.graded === false || batch.verdict === "ungraded" ? "Ungraded" : batch.verdict === "pass" ? "Pass" : batch.verdict === "fail" ? "Fail" : "";
1363
1369
  if (!verdict && !reproduction.length) return "";
1364
1370
  return `<section class="aw-task-section" aria-label="Run result">${verdict ? `<p>Verdict: <strong>${h(verdict)}</strong>${batch.exitCode === void 0 ? "" : ` \xB7 Exit ${h(batch.exitCode)}`}</p>` : ""}${reproduction.length ? `<p>Production: ${reproduction.map((r) => `<code>${h(r.sceneId)}</code> ${h(String(r.verdict).replaceAll("-", " "))}`).join(" \xB7 ")}</p>` : ""}</section>`;
1365
1371
  }
@@ -2146,7 +2152,7 @@ function starterCount(tool, key, state) {
2146
2152
  }
2147
2153
 
2148
2154
  // frontend/src/generated/coding-agent-skill.ts
2149
- var codingAgentSkill = "---\nname: ancha\ndescription: Test, debug and fix an AI agent (a Slack bot, a support or on-call agent) against stateful replicas of the tools it uses, built from its production traces, and prove a fix with graded runs in the cloud. Use when asked to test an agent with Ancha, or in a repository that has ancha.yaml.\n---\n\n# Ancha\n\nAncha gives an AI agent the other side of its job: stateful replicas of the tools it uses (Slack, GitHub, Datadog, PagerDuty and more), seeded with one fictional company or rebuilt from a production trace, and checks that grade every attempt from the agent's calls and the world's end state. The verdict comes from the world, not from mocks you wrote yourself. `ancha run --on cloud` runs each attempt on a fresh machine of its own in Ancha's cloud.\n\n## Run the CLI\n\nBefore the CLI is installed, run every command as `npx -y @ancha-labs/cli <command>`. After `npm install -g @ancha-labs/cli` (Node 24 or newer), run `ancha <command>`. Never run `npx` with the bare name `ancha`: that npm name is not this package.\n\nAdd `--json` to every command. Runs print NDJSON events that end with `run_finished`; `ancha traces upload` prints the tests it made. `env list` and `sandbox list` return arrays; trace commands use the fields described in `ancha docs traces`. `ancha schema <kind> --json` prints the JSON Schema of `ancha.yaml`, test files (`scene.yaml`) and these outputs. If your command can time out, give `ancha run` an `--idempotency-key <key>`: running it again with the same key returns the same run instead of starting another.\n\n## First steps\n\n<!-- ancha:first-steps -->\n1. **Install the CLI and sign in.** It needs Node 24 or newer. Approve this computer in the browser, once.\n ```sh\n ancha --version || npm install -g @ancha-labs/cli\n ancha login\n ```\n2. **Set up the project.** Run it in the agent's project: it finds the command that starts the agent and how the agent takes its task, and writes both to `ancha.yaml`. It installs and runs nothing.\n ```sh\n ancha init\n ```\n - To name the command yourself: `ancha init --agent \"<the command that starts your agent>\"`.\n3. **Store the key it needs.** The agent's own model key, read from your shell, never from an argument: it is stored in your workspace and named under `agent.pass_env` in `ancha.yaml`, so the agent gets it in every cloud attempt.\n ```sh\n ancha secrets set ANTHROPIC_API_KEY\n ```\n4. **Upload your agent.** A fresh machine in the cloud installs the project's dependencies and starts the agent once with a task. It says the agent is ready, or shows the end of its log.\n ```sh\n ancha agent upload\n ```\n - The install follows the project's own manifests and lockfiles; `agent.install` in `ancha.yaml` sets the command instead.\n5. **Upload traces.** A file or a folder of traces, runs that went fine and runs that failed: each trace becomes a test, in `scenes/from-traces/` and in your workspace.\n ```sh\n ancha traces upload ./traces\n ```\n - From Langfuse or LangSmith, with your keys on this computer: `ancha traces upload --from langfuse --limit 50`, or `--from langsmith`.\n - A trace of a run that went wrong can say what went wrong: `ancha traces upload <trace file> --expect \"<what went wrong>\"`, or for a test already made, `ancha pull <test id> --expect \"<what went wrong>\"`.\n - Traces your agent already sent to your workspace: `ancha traces`, then `ancha pull <trace id>`.\n - A test lists what one trace cannot settle: answer with `ancha pull <test id> --answer <question>=<answer>`.\n6. **Point the agent at the test's tools.** In a test, the agent calls Ancha instead of production:\n - Its clients for Slack, GitHub and the other tools Ancha replicates take the URLs and credentials Ancha supplies: `ancha connect <tool>` prints the settings.\n - Its own functions: wrap them with `wrapTools` from `@ancha-labs/tools` (`ancha.wrap_tools` in Python), or serve them over MCP.\n7. **Run your tests.** Every test, each attempt on a fresh machine. The run grades each attempt check by check and ends with the link to its result.\n ```sh\n ancha run\n ```\n - Your agent and its worlds run in the cloud, each attempt on a fresh machine of its own; a run keeps going when your laptop closes, and its results land in Runs.\n - `--attempts <n>` sets how many attempts each test gets, `--concurrency <n>` how many run at once.\n - `ancha wait <run id>` follows a run again from any terminal; `ancha explain <run id>` shows why a check failed.\n - `ancha status` shows which of these steps your workspace has done.\n8. **Fix the agent and keep the test.** Keep the failing run as the reference, fix the agent, and run again: exit 0 means every check passes and nothing regressed.\n ```sh\n ancha baseline save before --from <run id>\n ancha run --compare before\n ```\n - Commit `scenes/from-traces/` so every run, in CI too, keeps it fixed.\n9. **Run it on this computer.** While you develop, `ancha run --on local` runs the agent and its worlds on this computer, with the same checks.\n ```sh\n ancha run --on local --attempts 1\n ```\n - Here the agent gets the keys in `agent.pass_env` from your shell, and model-graded checks need `OPENROUTER_API_KEY`.\n<!-- /ancha:first-steps -->\n\n## Cloud runs\n\n- `ancha run --on cloud` sends the project as one bundle: the agent's files, without hidden directories, dependencies or credential-like files, and its tests with their worlds and checks, which stay with the grader and never reach the agent. Each attempt's machine installs the dependencies, runs the agent and grades it with the same engine as a run on this computer. `--attempts <n>` sets the attempts per test, `--concurrency <n>` how many run at once.\n- The agent gets the workspace's secrets for the names in `agent.pass_env`, and its network reaches its tools and its model providers. Model-graded checks and the people in a world run on the workspace's model credit.\n- The `run_finished` event carries `url` (the result in the workspace) and `summary`, with `counts` of the attempts: requested, completed, invalid, skipped and cancelled. Interrupting the command stops the following, never the run: `ancha wait <run id>` follows it again, and `--detach` returns once the run is accepted.\n- `ancha explain <run id> --json` shows each failed check: what was expected, what happened, and the calls and world events behind it. Read it before guessing from the code; many bugs only show up with the world's data and timing.\n- When every attempt ended before the agent did anything (it exited within seconds without a call, or its command could not start), the run, `ancha wait` and `ancha explain` say that first: \"Your agent didn't run\", the end of its log once, and the likely fix read from it, such as the `agent.env` line that gives the agent its task under the name it reads. `agentNeverRan` in the JSON carries the same. Make that fix first: the failed checks follow from it, and `ancha explain <run id> --all` lists them.\n- `ancha status --json` shows the workspace's three steps (agent uploaded, traces uploaded, tests run in the cloud) and the next command. In CI, `ANCHA_SERVER_URL` and `ANCHA_API_KEY` replace the login. More: `ancha docs cloud`.\n\n## An app, not a command\n\nIf the AI feature lives inside an app (a web app or API server with its database, workers and scheduled jobs), don't wrap it in `agent.command`. Ancha starts the app once per attempt with `agent.start`, waits for `agent.ready_url`, delivers the tools' events to `agent.url`, and a scene's `world_rules.app_calls` call the app's own routes, such as its cron jobs, at a time. Read `ancha docs apps` before writing `ancha.yaml`. The start script gives the app a clean database, cache and seed every attempt: a new world has new URLs and tokens, and stale rows or sync cursors make an app silently do nothing.\n\n## More from production traces\n\n`ancha traces upload <file or folder> --json` sends the traces to the workspace, which rebuilds each one's world and checks, and writes each test to `scenes/from-traces/<name>/scene.yaml`: runs that went fine and runs that failed. `--from langfuse` or `--from langsmith` takes the newest traces there instead (`--limit`, `--since`), with the keys in this shell. For one trace of a failure, `--expect \"<what went wrong>\"` adds a check for it. A test lists the questions one trace cannot settle, each with the default it uses. Ask the user for the answers; don't guess them. Pass them with `ancha pull <test id> --answer <question>=<value>`. `ancha import --offline <trace file> --json` makes the tests on this computer instead, one per conversation, and uploads nothing; there, `--answer` and `--force` go on the import.\n\nA test from a run that failed should fail the same way production did. If it doesn't, run it on this computer: `ancha traces diff <trace file> latest` shows the calls production made and the attempt didn't, and the import also lists the app's own setup calls, which the start script or an `app_call` has to make.\n\nIf the user's workspace takes traces (their agents send them to it), each trace becomes a test there: `ancha pull --all --json` writes every test that is turned on (`--agent <name>` for one agent's), `ancha traces --failed --json` lists the ones where production failed a check, `ancha traces show <id> --json` previews the test, and `ancha pull <id> --json` writes one, with `--answer` for its questions. Checks you add to a pulled `scene.yaml` stay when you pull a newer version; any other edit stops the pull. More: `ancha docs traces`.\n\n## Other tests\n\nThe starter test `ancha init` writes when `scenes/` holds no tests only proves that the agent reaches each tool. For the agent's real job beyond its traces, `ancha test new \"<the test in one sentence>\" --json` drafts a test with people for the project's world (`ancha init --intent \"<company and scenario>\"` makes the world and a first test). Review its checks before you run it. To write a seed yourself, `ancha twins seed <tool> --json` prints the tool's fields, an example that validates as written, and the checks a test can make on it. More: `ancha docs scenes`.\n\n## The rule\n\nFix the agent, not the tests or their checks. `ancha.yaml` says how to start the agent and give it its task and keys: change it for that, never to make a check pass. The exception is a check that is wrong for the real API, such as a method the official SDK never sends. Then don't quietly edit it: tell the user, show the evidence (the call from `ancha explain`, the vendor's documentation), and change it only with their agreement.\n\nNever give the agent under test the tests, checks, seeds or reference companions (`oracle.mjs`, `null.mjs`), and never point it at a real SaaS API.\n\n## What the agent gets\n\nEach attempt gives the agent its tools as environment variables, with fake credentials that only work against the replicas:\n\n- Slack: `SLACK_API_URL` (ends in `/api/`), `SLACK_BOT_TOKEN`\n- GitHub: `GITHUB_API_URL`, `GITHUB_TOKEN`\n- Datadog: `DATADOG_API_URL`, `DD_API_KEY`, `DD_APP_KEY`\n- PagerDuty: `PAGERDUTY_API_URL`, `PAGERDUTY_API_TOKEN`, `PAGERDUTY_FROM_EMAIL`, `PAGERDUTY_ROUTING_KEY`\n- the same pattern for the other tools in the world; `ANCHA_TASK` carries a command-line task, and `ANCHA_TASK_FILE` names a file holding it. An agent that reads its task under another name gets it with `agent.env: { MY_TASK: \"{{task}}\" }` (`{{task_file}}` for the file); `ancha init` writes that line when it finds the name.\n\n`ancha connect <tool> --lang ts|py` prints the SDK settings. `ancha twins coverage <tool>` lists the endpoints each replica implements.\n\nGoogle clients (`googleapis`, `@googleapis/*`) take the replica's URL in each call's options: `drive.files.list(params, { rootUrl: process.env.GOOGLE_DRIVE_API_URL + '/' })`. A `rootUrl` set on the client keeps only the host; Ancha still routes those calls by their token, but the client sends file uploads to www.googleapis.com.\n\nThe agent's own keys are the names in `agent.pass_env` in `ancha.yaml`, such as `agent.pass_env: [OPENAI_API_KEY]`, and `agent.env` sets fixed values, such as the path of a key file. In the cloud each name comes from the workspace's secrets (`ancha secrets set NAME`). `ancha run --on local` starts the agent on this computer instead, with this computer's network and those names from this shell (or `--pass-env NAME`); `--on docker` seals it in a container (`agent.execution: { mode: container, image: node:24-slim }`, which needs Docker). An agent without its model key stops at its first model call.\n\n## When something fails\n\n- Exit 1: a check failed or the comparison regressed (a single check's drop counts, see `comparison.droppedChecks`). Run `ancha explain <run id> --json`.\n- Exit 2: usage, config, test file or authentication error, or a cancelled cloud run. `AUTH_INVALID` means `ancha login` again or a valid `ANCHA_API_KEY`; `CONFIG_INVALID` naming a workspace secret means `ancha secrets set NAME`. Read the `hint`.\n- Exit 3: infrastructure, or an attempt the harness couldn't run or grade. It counts as invalid, never as a failed check, so it's not the agent's fault; run again, and `ancha agent upload --json` if it repeats.\n- Exit 4, only with `--strict`: an endpoint coverage error or a verdict using simulated tool answers. The summary names the tests, trials and evaluated checks using those answers. `ancha explain` lists endpoint errors; `ancha twins coverage <tool>` shows the endpoint inventory.\n\nRead the error's stable `code` and `message`, then follow its `hint` when provided. More: `ancha docs`, `ancha docs <topic>` for setup, run, traces, explain, compare, scenes, integrations, cloud and playgrounds, and https://docs.ancha.io/coding-agents.\n\nTell the user what you ran, where it ran, the pass rate, the evidence and the result link. Never claim a fix until `ancha run --compare` exits 0.\n";
2155
+ var codingAgentSkill = "---\nname: ancha\ndescription: Test, debug and fix an AI agent (a Slack bot, a support or on-call agent) against stateful replicas of the tools it uses, built from its production traces, and prove a fix with graded runs in the cloud. Use when asked to test an agent with Ancha, or in a repository that has ancha.yaml.\n---\n\n# Ancha\n\nAncha gives an AI agent the other side of its job: stateful replicas of the tools it uses (Slack, GitHub, Datadog, PagerDuty and more), seeded with one fictional company or rebuilt from a production trace, and checks that grade every attempt from the agent's calls and the world's end state. The verdict comes from the world, not from mocks you wrote yourself. `ancha run --on cloud` runs each attempt on a fresh machine of its own in Ancha's cloud.\n\n## Run the CLI\n\nBefore the CLI is installed, run every command as `npx -y @ancha-labs/cli <command>`. After `npm install -g @ancha-labs/cli` (Node 24 or newer), run `ancha <command>`. Never run `npx` with the bare name `ancha`: that npm name is not this package.\n\nAdd `--json` to every command. Runs print NDJSON events that end with `run_finished`; `ancha traces upload` prints the tests it made. `env list` and `sandbox list` return arrays; trace commands use the fields described in `ancha docs traces`. `ancha schema <kind> --json` prints the JSON Schema of `ancha.yaml`, test files (`scene.yaml`) and these outputs. If your command can time out, give `ancha run` an `--idempotency-key <key>`: running it again with the same key returns the same run instead of starting another.\n\n## First steps\n\n<!-- ancha:first-steps -->\n1. **Install the CLI and sign in.** It needs Node 24 or newer. Approve this computer in the browser, once.\n ```sh\n ancha --version || npm install -g @ancha-labs/cli\n ancha login\n ```\n2. **Set up the project.** Run it in the agent's project: it finds the command that starts the agent and how the agent takes its task, and writes both to `ancha.yaml`. It installs and runs nothing.\n ```sh\n ancha init\n ```\n - To name the command yourself: `ancha init --agent \"<the command that starts your agent>\"`.\n - To name its tools yourself (NetSuite, Slack, ...): `ancha init --tools netsuite,slack`.\n3. **Store the key it needs.** The agent's own model key, read from your shell, never from an argument: it is stored in your workspace and named under `agent.pass_env` in `ancha.yaml`, so the agent gets it in every cloud attempt.\n ```sh\n ancha secrets set ANTHROPIC_API_KEY\n ```\n4. **Upload your agent.** A fresh machine in the cloud installs the project's dependencies and starts the agent once with a task. It says the agent is ready, or shows the end of its log.\n ```sh\n ancha agent upload\n ```\n - The install follows the project's own manifests and lockfiles; `agent.install` in `ancha.yaml` sets the command instead.\n5. **Without production traces.** For an agent that uses NetSuite, `ancha init` writes a NetSuite world of a private-equity portfolio company (four subsidiaries, two currencies, thousands of transactions) and 25 tests from the questions an operator asks.\n - Your data: `ancha world import netsuite <your exports> --id <id>` reads REST record JSON, SuiteQL results and saved search CSV into `ancha/worlds/<id>.yaml`; check it with `ancha world validate`. To write the seed yourself, `ancha twins seed netsuite` lists its fields.\n - Your evals: `ancha test import <file> --world <id>` (JSONL, JSON, CSV or YAML with a question and an expected answer).\n - One test from a sentence: `ancha test new \"<sentence>\" --world <id>`.\n6. **Upload traces.** A file or a folder of traces, runs that went fine and runs that failed: each trace becomes a test, in `scenes/from-traces/` and in your workspace.\n ```sh\n ancha traces upload ./traces\n ```\n - From Langfuse or LangSmith, with your keys on this computer: `ancha traces upload --from langfuse --limit 50`, or `--from langsmith`.\n - A trace of a run that went wrong can say what went wrong: `ancha traces upload <trace file> --expect \"<what went wrong>\"`, or for a test already made, `ancha pull <test id> --expect \"<what went wrong>\"`.\n - Traces your agent already sent to your workspace: `ancha traces`, then `ancha pull <trace id>`.\n - A test lists what one trace cannot settle: answer with `ancha pull <test id> --answer <question>=<answer>`.\n7. **Point the agent at the test's tools.** In a test, the agent calls Ancha instead of production:\n - Its clients for Slack, GitHub and the other tools Ancha replicates take the URLs and credentials Ancha supplies: `ancha connect <tool>` prints the settings.\n - Its own functions: wrap them with `wrapTools` from `@ancha-labs/tools` (`ancha.wrap_tools` in Python), or serve them over MCP.\n8. **Run your tests.** Every test, each attempt on a fresh machine. The run grades each attempt check by check and ends with the link to its result.\n ```sh\n ancha run\n ```\n - Your agent and its worlds run in the cloud, each attempt on a fresh machine of its own; a run keeps going when your laptop closes, and its results land in Runs.\n - `--attempts <n>` sets how many attempts each test gets, `--concurrency <n>` how many run at once.\n - `ancha wait <run id>` follows a run again from any terminal; `ancha explain <run id>` shows why a check failed.\n - `ancha status` shows which of these steps your workspace has done.\n9. **Fix the agent and keep the test.** Keep the failing run as the reference, fix the agent, and run again: exit 0 means every check passes and nothing regressed.\n ```sh\n ancha baseline save before --from <run id>\n ancha run --compare before\n ```\n - Commit `scenes/from-traces/` so every run, in CI too, keeps it fixed.\n10. **Run it on this computer.** While you develop, `ancha run --on local` runs the agent and its worlds on this computer, with the same checks.\n ```sh\n ancha run --on local --attempts 1\n ```\n - Here the agent gets the keys in `agent.pass_env` from your shell, and model-graded checks need `OPENROUTER_API_KEY`.\n<!-- /ancha:first-steps -->\n\n## Cloud runs\n\n- `ancha run --on cloud` sends the project as one bundle: the agent's files, without hidden directories, dependencies or credential-like files, and its tests with their worlds and checks, which stay with the grader and never reach the agent. Each attempt's machine installs the dependencies, runs the agent and grades it with the same engine as a run on this computer. `--attempts <n>` sets the attempts per test, `--concurrency <n>` how many run at once.\n- The agent gets the workspace's secrets for the names in `agent.pass_env`, and its network reaches its tools and its model providers. Model-graded checks and the people in a world run on the workspace's model credit.\n- The `run_finished` event carries `url` (the result in the workspace) and `summary`, with `counts` of the attempts: requested, completed, invalid, skipped and cancelled. Interrupting the command stops the following, never the run: `ancha wait <run id>` follows it again, and `--detach` returns once the run is accepted.\n- `ancha explain <run id> --json` shows each failed check: what was expected, what happened, and the calls and world events behind it. Read it before guessing from the code; many bugs only show up with the world's data and timing.\n- When every attempt ended before the agent did anything (it exited within seconds without a call, or its command could not start), the run, `ancha wait` and `ancha explain` say that first: \"Your agent didn't run\", the end of its log once, and the likely fix read from it, such as the `agent.env` line that gives the agent its task under the name it reads. `agentNeverRan` in the JSON carries the same. Make that fix first: the failed checks follow from it, and `ancha explain <run id> --all` lists them.\n- `ancha status --json` shows the workspace's three steps (agent uploaded, tests added, tests run in the cloud) and the next command. In CI, `ANCHA_SERVER_URL` and `ANCHA_API_KEY` replace the login. More: `ancha docs cloud`.\n\n## An app, not a command\n\nIf the AI feature lives inside an app (a web app or API server with its database, workers and scheduled jobs), don't wrap it in `agent.command`. Ancha starts the app once per attempt with `agent.start`, waits for `agent.ready_url`, delivers the tools' events to `agent.url`, and a scene's `world_rules.app_calls` call the app's own routes, such as its cron jobs, at a time. Read `ancha docs apps` before writing `ancha.yaml`. The start script gives the app a clean database, cache and seed every attempt: a new world has new URLs and tokens, and stale rows or sync cursors make an app silently do nothing.\n\n## More from production traces\n\n`ancha traces upload <file or folder> --json` sends the traces to the workspace, which rebuilds each one's world and checks, and writes each test to `scenes/from-traces/<name>/scene.yaml`: runs that went fine and runs that failed. `--from langfuse` or `--from langsmith` takes the newest traces there instead (`--limit`, `--since`), with the keys in this shell. For one trace of a failure, `--expect \"<what went wrong>\"` adds a check for it. A test lists the questions one trace cannot settle, each with the default it uses. Ask the user for the answers; don't guess them. Pass them with `ancha pull <test id> --answer <question>=<value>`. `ancha import --offline <trace file> --json` makes the tests on this computer instead, one per conversation, and uploads nothing; there, `--answer` and `--force` go on the import.\n\nA test from a run that failed should fail the same way production did. If it doesn't, run it on this computer: `ancha traces diff <trace file> latest` shows the calls production made and the attempt didn't, and the import also lists the app's own setup calls, which the start script or an `app_call` has to make.\n\nIf the user's workspace takes traces (their agents send them to it), each trace becomes a test there: `ancha pull --all --json` writes every test that is turned on (`--agent <name>` for one agent's), `ancha traces --failed --json` lists the ones where production failed a check, `ancha traces show <id> --json` previews the test, and `ancha pull <id> --json` writes one, with `--answer` for its questions. Checks you add to a pulled `scene.yaml` stay when you pull a newer version; any other edit stops the pull. More: `ancha docs traces`.\n\n## Other tests\n\nThe starter test `ancha init` writes when `scenes/` holds no tests only proves that the agent reaches each tool. For the agent's real job beyond its traces, `ancha test new \"<the test in one sentence>\" --json` drafts a test with people for the project's world (`ancha init --intent \"<company and scenario>\"` makes the world and a first test). Review its checks before you run it. To write a seed yourself, `ancha twins seed <tool> --json` prints the tool's fields, an example that validates as written, and the checks a test can make on it. More: `ancha docs scenes`.\n\n## The rule\n\nFix the agent, not the tests or their checks. `ancha.yaml` says how to start the agent and give it its task and keys: change it for that, never to make a check pass. The exception is a check that is wrong for the real API, such as a method the official SDK never sends. Then don't quietly edit it: tell the user, show the evidence (the call from `ancha explain`, the vendor's documentation), and change it only with their agreement.\n\nNever give the agent under test the tests, checks, seeds or reference companions (`oracle.mjs`, `null.mjs`), and never point it at a real SaaS API.\n\n## What the agent gets\n\nEach attempt gives the agent its tools as environment variables, with fake credentials that only work against the replicas:\n\n- Slack: `SLACK_API_URL` (ends in `/api/`), `SLACK_BOT_TOKEN`\n- GitHub: `GITHUB_API_URL`, `GITHUB_TOKEN`\n- Datadog: `DATADOG_API_URL`, `DD_API_KEY`, `DD_APP_KEY`\n- PagerDuty: `PAGERDUTY_API_URL`, `PAGERDUTY_API_TOKEN`, `PAGERDUTY_FROM_EMAIL`, `PAGERDUTY_ROUTING_KEY`\n- the same pattern for the other tools in the world; `ANCHA_TASK` carries a command-line task, and `ANCHA_TASK_FILE` names a file holding it. An agent that reads its task under another name gets it with `agent.env: { MY_TASK: \"{{task}}\" }` (`{{task_file}}` for the file); `ancha init` writes that line when it finds the name.\n\n`ancha connect <tool> --lang ts|py` prints the SDK settings. `ancha twins coverage <tool>` lists the endpoints each replica implements.\n\nGoogle clients (`googleapis`, `@googleapis/*`) take the replica's URL in each call's options: `drive.files.list(params, { rootUrl: process.env.GOOGLE_DRIVE_API_URL + '/' })`. A `rootUrl` set on the client keeps only the host; Ancha still routes those calls by their token, but the client sends file uploads to www.googleapis.com.\n\nThe agent's own keys are the names in `agent.pass_env` in `ancha.yaml`, such as `agent.pass_env: [OPENAI_API_KEY]`, and `agent.env` sets fixed values, such as the path of a key file. In the cloud each name comes from the workspace's secrets (`ancha secrets set NAME`). `ancha run --on local` starts the agent on this computer instead, with this computer's network and those names from this shell (or `--pass-env NAME`); `--on docker` seals it in a container (`agent.execution: { mode: container, image: node:24-slim }`, which needs Docker). An agent without its model key stops at its first model call.\n\n## When something fails\n\n- Exit 1: a check failed or the comparison regressed (a single check's drop counts, see `comparison.droppedChecks`). Run `ancha explain <run id> --json`.\n- Exit 2: usage, config, test file or authentication error, or a cancelled cloud run. `AUTH_INVALID` means `ancha login` again or a valid `ANCHA_API_KEY`; `CONFIG_INVALID` naming a workspace secret means `ancha secrets set NAME`. Read the `hint`.\n- Exit 3: infrastructure, or an attempt the harness couldn't run or grade. It counts as invalid, never as a failed check, so it's not the agent's fault; run again, and `ancha agent upload --json` if it repeats.\n- Exit 4, only with `--strict`: an endpoint coverage error or a verdict using simulated tool answers. The summary names the tests, trials and evaluated checks using those answers. `ancha explain` lists endpoint errors; `ancha twins coverage <tool>` shows the endpoint inventory.\n\nRead the error's stable `code` and `message`, then follow its `hint` when provided. More: `ancha docs`, `ancha docs <topic>` for setup, run, traces, explain, compare, scenes, integrations, cloud and playgrounds, and https://docs.ancha.io/coding-agents.\n\nTell the user what you ran, where it ran, the pass rate, the evidence and the result link. Never claim a fix until `ancha run --compare` exits 0.\n";
2150
2156
 
2151
2157
  // frontend/src/workspace-pages.ts
2152
2158
  var startSentence = "Set up Ancha for this agent: read https://app.ancha.io/llms.txt and follow its first steps.";
@@ -3716,6 +3722,7 @@ function resultBadge(r) {
3716
3722
  if (r.metadata?.diagnostic && r.verification) return connectionStatus(r.verification);
3717
3723
  const invalid = r.summary?.scenes?.some((s) => s.invalidTrials > 0);
3718
3724
  if (invalid) return badge("Evaluation error", "bad");
3725
+ if (r.summary?.verdict === "ungraded") return badge("Not graded", "warn");
3719
3726
  if (r.summary) return badge(r.summary.verdict === "pass" ? "Passed" : "Failed", r.summary.verdict === "pass" ? "good" : "bad");
3720
3727
  return badge(r.status?.state === "interrupted" ? "Stopped" : r.status?.state ?? (r.error ? "Unreadable result" : "Unknown"), r.status?.state === "running" ? "accent" : "warn");
3721
3728
  }
@@ -586,7 +586,7 @@ a.rt-row{min-height:56px;padding:7px 10px;border-bottom:1px solid var(--row-line
586
586
  .rt-scroll{overflow:visible;margin:0}.rt{min-width:0;padding:0}.rt-head{display:none}
587
587
  a.rt-row{grid-template-columns:18px minmax(0,1fr) auto;grid-template-areas:"result test passed" "result agent started" "result attempts prod";gap:3px 10px;padding:12px 2px;align-items:start}
588
588
  .rt-result{grid-area:result;padding-top:2px}.rt-result .c-status>span{display:none}
589
- .rt-test{grid-area:test}.rt-ref{display:none}.rt-agent{grid-area:agent;flex-direction:row;gap:6px;align-items:baseline}.rt-agent-name{font-weight:400;font-size:12px;color:var(--muted)}
589
+ .rt-test{grid-area:test}.rt-ref{display:none}.rt-agent{grid-area:agent;flex-direction:row;gap:6px;align-items:baseline}.rt-agent-name{font-weight:400;font-size:12px;color:var(--muted)}.rt-command{display:none}
590
590
  .rt-attempts{grid-area:attempts}.rt-attempts .c-note,.rt-passed .c-note,.rt-prod>.c-note{display:none}.rt-prod{grid-area:prod;justify-self:end}.rt-passed{grid-area:passed}.rt-started{grid-area:started}.rt-started .c-note{display:none}
591
591
  }
592
592
  /* SPEC-046: a run's page. Verdict first, its facts, the tests and attempts on the left, one attempt's evidence on the right. */