@ancha-labs/cli 0.4.49 → 0.4.51

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/lib/ancha.mjs CHANGED
@@ -6196,10 +6196,10 @@ function partPattern(schema4) {
6196
6196
  const own2 = schema4._zod.pattern?.source;
6197
6197
  const inner2 = def.innerType ?? schema4._zod.innerType;
6198
6198
  if (inner2) {
6199
- const before = inner2._zod.pattern?.source;
6199
+ const before2 = inner2._zod.pattern?.source;
6200
6200
  const after = partPattern(inner2);
6201
- if (own2 && before && after && after !== before) {
6202
- return own2.replace(cleanRegex(before), () => cleanRegex(after));
6201
+ if (own2 && before2 && after && after !== before2) {
6202
+ return own2.replace(cleanRegex(before2), () => cleanRegex(after));
6203
6203
  }
6204
6204
  return own2;
6205
6205
  }
@@ -24255,9 +24255,9 @@ function readNumbers(text31) {
24255
24255
  function readNumberSpans(text31) {
24256
24256
  const numbers3 = [];
24257
24257
  for (const match3 of text31.normalize("NFKC").matchAll(NUMBER)) {
24258
- const { open: open17, sign: sign4, before, minus, inner: inner2, digits, after, close: close2 } = match3.groups;
24258
+ const { open: open17, sign: sign4, before: before2, minus, inner: inner2, digits, after, close: close2 } = match3.groups;
24259
24259
  const parenthesized = (open17 !== void 0 || inner2 !== void 0) && close2 !== void 0;
24260
- const amount6 = before !== void 0 || after !== void 0 || /[,.]/.test(digits);
24260
+ const amount6 = before2 !== void 0 || after !== void 0 || /[,.]/.test(digits);
24261
24261
  const negative = sign4 !== void 0 && sign4 !== "+" || minus !== void 0 || parenthesized && amount6;
24262
24262
  const value6 = Number(digits.replaceAll(",", ""));
24263
24263
  numbers3.push({
@@ -24326,8 +24326,8 @@ function inferNumberLabels(text31, numbers3 = readNumberSpans(text31)) {
24326
24326
  const labels2 = numbers3.map((number7) => {
24327
24327
  let i = tokens7.findIndex((token5) => token5.start === number7.start) - 1;
24328
24328
  while (i >= 0) {
24329
- const word2 = tokens7[i].text, before = tokens7[i - 1]?.text;
24330
- if (word2 === "at" && before === "stands" || word2 === "to" && (before === "comes" || before === "came")) i -= 2;
24329
+ const word2 = tokens7[i].text, before2 = tokens7[i - 1]?.text;
24330
+ if (word2 === "at" && before2 === "stands" || word2 === "to" && (before2 === "comes" || before2 === "came")) i -= 2;
24331
24331
  else if (LINK_WORDS.has(word2) || CURRENCY_TOKEN.test(word2) || word2 === ":" || word2 === "=") i--;
24332
24332
  else break;
24333
24333
  }
@@ -36501,8 +36501,8 @@ function books(seed44, issue9, money24) {
36501
36501
  const peers = rows35.filter((l) => l.entity === line2.entity && l.account === line2.account), sign4 = accountById.get(line2.account)?.type === "AcctRec" ? 1 : -1;
36502
36502
  const signed2 = (l) => round24(((l.debit ?? 0) - (l.credit ?? 0)) * sign4), positive5 = signed2(line2) > 0;
36503
36503
  const debts = peers.reduce((sum6, l) => sum6 + Math.max(0, signed2(l)), 0), credits2 = peers.reduce((sum6, l) => sum6 + Math.max(0, -signed2(l)), 0);
36504
- const before = peers.filter((l) => l.line < line2.line && signed2(l) > 0 === positive5).reduce((sum6, l) => sum6 + Math.abs(signed2(l)), 0);
36505
- const amount6 = round24(Math.max(0, Math.abs(signed2(line2)) - Math.max(0, Math.min(debts, credits2) - before)));
36504
+ const before2 = peers.filter((l) => l.line < line2.line && signed2(l) > 0 === positive5).reduce((sum6, l) => sum6 + Math.abs(signed2(l)), 0);
36505
+ const amount6 = round24(Math.max(0, Math.abs(signed2(line2)) - Math.max(0, Math.min(debts, credits2) - before2)));
36506
36506
  open17.push({ doc: journal.id, line: line2.line, owner: line2.entity, account: line2.account, role: positive5 ? "debt" : "credit", amount: amount6 });
36507
36507
  }
36508
36508
  }
@@ -36519,12 +36519,12 @@ function books(seed44, issue9, money24) {
36519
36519
  const acct = control ?? ("customer" in t ? ar : ap) ?? 0;
36520
36520
  if (control !== void 0) account9(control, [name5, index, "customer" in t ? "arAcct" : "apAcct"], ["customer" in t ? "AcctRec" : "AcctPay"]);
36521
36521
  let gross = 0, credit = 0;
36522
- const before = new Map(used);
36522
+ const before2 = new Map(used);
36523
36523
  for (const [role3, list19] of [["debt", t.apply], ["credit", "credit" in t ? t.credit : []]]) {
36524
36524
  const seen = /* @__PURE__ */ new Set();
36525
36525
  for (const [i, a] of list19.entries()) {
36526
36526
  const eligible = open17.filter((o) => o.doc === a.doc && o.owner === owner6 && o.account === acct && o.role === role3 && o.amount > 4e-3);
36527
- const available2 = eligible.filter((o) => o.amount - (before.get(`${o.doc}:${o.line}`) ?? 0) > 4e-3);
36527
+ const available2 = eligible.filter((o) => o.amount - (before2.get(`${o.doc}:${o.line}`) ?? 0) > 4e-3);
36528
36528
  const item2 = a.line === void 0 && available2.length === 1 ? available2[0] : eligible.find((o) => o.line === (a.line ?? 0));
36529
36529
  const key5 = `${a.doc}:${item2?.line}`, path9 = [name5, index, role3 === "debt" ? "apply" : "credit", i];
36530
36530
  if (!item2 || seen.has(key5)) {
@@ -44382,11 +44382,11 @@ var require_compose_scalar = __commonJS({
44382
44382
  var require_util_empty_scalar_position = __commonJS({
44383
44383
  "node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/dist/compose/util-empty-scalar-position.js"(exports) {
44384
44384
  "use strict";
44385
- function emptyScalarPosition(offset20, before, pos) {
44386
- if (before) {
44387
- pos ?? (pos = before.length);
44385
+ function emptyScalarPosition(offset20, before2, pos) {
44386
+ if (before2) {
44387
+ pos ?? (pos = before2.length);
44388
44388
  for (let i = pos - 1; i >= 0; --i) {
44389
- let st = before[i];
44389
+ let st = before2[i];
44390
44390
  switch (st.type) {
44391
44391
  case "space":
44392
44392
  case "comment":
@@ -44394,10 +44394,10 @@ var require_util_empty_scalar_position = __commonJS({
44394
44394
  offset20 -= st.source.length;
44395
44395
  continue;
44396
44396
  }
44397
- st = before[++i];
44397
+ st = before2[++i];
44398
44398
  while (st?.type === "space") {
44399
44399
  offset20 += st.source.length;
44400
- st = before[++i];
44400
+ st = before2[++i];
44401
44401
  }
44402
44402
  break;
44403
44403
  }
@@ -44475,10 +44475,10 @@ var require_compose_node = __commonJS({
44475
44475
  node5.srcToken = token5;
44476
44476
  return node5;
44477
44477
  }
44478
- function composeEmptyNode(ctx, offset20, before, pos, { spaceBefore, comment: comment10, anchor: anchor2, tag: tag3, end }, onError) {
44478
+ function composeEmptyNode(ctx, offset20, before2, pos, { spaceBefore, comment: comment10, anchor: anchor2, tag: tag3, end }, onError) {
44479
44479
  const token5 = {
44480
44480
  type: "scalar",
44481
- offset: utilEmptyScalarPosition.emptyScalarPosition(offset20, before, pos),
44481
+ offset: utilEmptyScalarPosition.emptyScalarPosition(offset20, before2, pos),
44482
44482
  indent: -1,
44483
44483
  source: ""
44484
44484
  };
@@ -47797,7 +47797,7 @@ function netsuitePeWriteTargets(seed44, startTime) {
47797
47797
  function netsuitePeWriteEvals(seed44, startTime) {
47798
47798
  const t = netsuitePeWriteTargets(seed44, startTime), { cal } = t;
47799
47799
  const evals = [];
47800
- const counts2 = (type, before, created4 = false) => ({ type, count: before + Number(created4) });
47800
+ const counts2 = (type, before2, created4 = false) => ({ type, count: before2 + Number(created4) });
47801
47801
  const add = (name5, question, records6, allowed2, recordCounts, contains3) => {
47802
47802
  evals.push({
47803
47803
  id: `pe-write-${String(evals.length + 1).padStart(2, "0")}-${name5}`,
@@ -51681,10 +51681,10 @@ function candidates(world5, seed44) {
51681
51681
  ["Bill", ["5033", "5034"], 5e4],
51682
51682
  ["Bill", ["5059", "5060"], 12525]
51683
51683
  ]) {
51684
- const before = transactionAmount(rowById(world5, entity5, ids3[0]), entity5);
51685
- const amount6 = before + (defaults4 ? delta2 : rng.fork(ids3[0]).int(1, 75e3));
51684
+ const before2 = transactionAmount(rowById(world5, entity5, ids3[0]), entity5);
51685
+ const amount6 = before2 + (defaults4 ? delta2 : rng.fork(ids3[0]).int(1, 75e3));
51686
51686
  const docs2 = ids3.map((id15) => rowById(world5, entity5, id15).DocNumber).filter((v, i, values3) => values3.indexOf(v) === i).join("/");
51687
- add("amounts", `${entity5.toLowerCase()}-amount`, `${entity5} ${docs2} is $${money11(amount6)} in both copies instead of $${money11(before)}.`, { op: "duplicate_amount", entity: entity5, ids: [...ids3], amount_minor: amount6 });
51687
+ add("amounts", `${entity5.toLowerCase()}-amount`, `${entity5} ${docs2} is $${money11(amount6)} in both copies instead of $${money11(before2)}.`, { op: "duplicate_amount", entity: entity5, ids: [...ids3], amount_minor: amount6 });
51688
51688
  }
51689
51689
  const occupied = new Set(Object.values(world5.seed.quickbooks.entities).flatMap((rows35) => (rows35 ?? []).map((r2) => String(r2.Id))));
51690
51690
  const copyRng = rng.fork("copy-id");
@@ -51759,9 +51759,9 @@ function applyRecipe(parent3, input5) {
51759
51759
  return world5;
51760
51760
  }
51761
51761
  function validateChange(parent3, changed, recipe) {
51762
- const before = structuredClone(parent3), after = structuredClone(changed);
51762
+ const before2 = structuredClone(parent3), after = structuredClone(changed);
51763
51763
  const entity5 = recipe.op === "rename_vendor" ? "Vendor" : recipe.entity;
51764
- const oldRows = records(before, entity5), newRows = records(after, entity5);
51764
+ const oldRows = records(before2, entity5), newRows = records(after, entity5);
51765
51765
  if (recipe.op === "extra_copy" || recipe.op === "page_padding") {
51766
51766
  const addedIds = recipe.op === "extra_copy" ? [recipe.new_id] : recipe.ids;
51767
51767
  if (newRows.length !== oldRows.length + addedIds.length) invalid(`${recipe.op}: incorrect added record count`);
@@ -51770,12 +51770,12 @@ function validateChange(parent3, changed, recipe) {
51770
51770
  if (recipe.op === "extra_copy") {
51771
51771
  const copy = structuredClone(additions[0]);
51772
51772
  copy.Id = recipe.source_id;
51773
- copy.DocNumber = rowById(before, entity5, recipe.source_id).DocNumber;
51774
- if (!equal2(copy, rowById(before, entity5, recipe.source_id))) invalid("extra_copy: changed economic event");
51773
+ copy.DocNumber = rowById(before2, entity5, recipe.source_id).DocNumber;
51774
+ if (!equal2(copy, rowById(before2, entity5, recipe.source_id))) invalid("extra_copy: changed economic event");
51775
51775
  }
51776
51776
  } else {
51777
51777
  for (const id15 of recipe.ids) {
51778
- const a = rowById(before, entity5, id15), b = rowById(after, entity5, id15);
51778
+ const a = rowById(before2, entity5, id15), b = rowById(after, entity5, id15);
51779
51779
  if (recipe.op === "duplicate_amount") {
51780
51780
  delete a.Line[0].Amount;
51781
51781
  delete b.Line[0].Amount;
@@ -51800,7 +51800,7 @@ function validateChange(parent3, changed, recipe) {
51800
51800
  }
51801
51801
  }
51802
51802
  }
51803
- if (!equal2(before, after)) invalid(`${recipe.op}: fields outside the declared change differ`);
51803
+ if (!equal2(before2, after)) invalid(`${recipe.op}: fields outside the declared change differ`);
51804
51804
  if (!equal2(applyRecipe(parent3, recipe), changed)) invalid(`${recipe.op}: changed fields do not match the recipe`);
51805
51805
  }
51806
51806
  var invalid, rowById, equal2;
@@ -63536,12 +63536,12 @@ var init_ajvProvider_DyjnscPj = __esm({
63536
63536
  RULES.all[keyword] = rule;
63537
63537
  (_a7 = definition3.implements) === null || _a7 === void 0 || _a7.forEach((kwd) => this.addKeyword(kwd));
63538
63538
  }
63539
- function addBeforeRule(ruleGroup, rule, before) {
63540
- const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
63539
+ function addBeforeRule(ruleGroup, rule, before2) {
63540
+ const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before2);
63541
63541
  if (i >= 0) ruleGroup.rules.splice(i, 0, rule);
63542
63542
  else {
63543
63543
  ruleGroup.rules.push(rule);
63544
- this.logger.warn(`rule ${before} is not defined`);
63544
+ this.logger.warn(`rule ${before2} is not defined`);
63545
63545
  }
63546
63546
  }
63547
63547
  function keywordMetaschema(def) {
@@ -93995,8 +93995,8 @@ function functionToolObservation(ctx) {
93995
93995
  };
93996
93996
  }
93997
93997
  function registration(ctx, names8) {
93998
- const before = JSON.parse(getState(ctx, "wrapped") ?? "[]");
93999
- const wrapped = [.../* @__PURE__ */ new Set([...before, ...names8])].sort();
93998
+ const before2 = JSON.parse(getState(ctx, "wrapped") ?? "[]");
93999
+ const wrapped = [.../* @__PURE__ */ new Set([...before2, ...names8])].sort();
94000
94000
  setState(ctx, "wrapped", JSON.stringify(wrapped));
94001
94001
  return { wrapped, missing: toolsToWrap(ctx).filter((name5) => !wrapped.includes(name5)) };
94002
94002
  }
@@ -95088,24 +95088,24 @@ function unsupported(what) {
95088
95088
  throw new ResendError(501, "application_error", `ancha: not implemented: ${what}`, true);
95089
95089
  }
95090
95090
  function page5(items2, query12) {
95091
- const raw3 = query12.get("limit"), after = query12.get("after"), before = query12.get("before");
95091
+ const raw3 = query12.get("limit"), after = query12.get("after"), before2 = query12.get("before");
95092
95092
  const limit2 = raw3 === null ? 20 : Number(raw3);
95093
95093
  if (!Number.isInteger(limit2) || limit2 < 1 || limit2 > 100) invalid6("The `limit` parameter must be an integer between 1 and 100.");
95094
- if (after !== null && before !== null) invalid6("The `after` and `before` parameters cannot be used together.");
95094
+ if (after !== null && before2 !== null) invalid6("The `after` and `before` parameters cannot be used together.");
95095
95095
  let start2 = 0, end = items2.length;
95096
95096
  if (after !== null) {
95097
95097
  const i = items2.findIndex((x) => x.id === after);
95098
95098
  if (i < 0) invalid6("The `after` cursor is invalid.");
95099
95099
  start2 = i + 1;
95100
95100
  }
95101
- if (before !== null) {
95102
- const i = items2.findIndex((x) => x.id === before);
95101
+ if (before2 !== null) {
95102
+ const i = items2.findIndex((x) => x.id === before2);
95103
95103
  if (i < 0) invalid6("The `before` cursor is invalid.");
95104
95104
  end = i;
95105
95105
  start2 = Math.max(0, i - limit2);
95106
95106
  }
95107
95107
  const data7 = items2.slice(start2, Math.min(end, start2 + limit2));
95108
- return { object: "list", has_more: before !== null ? start2 > 0 : start2 + limit2 < end, data: data7 };
95108
+ return { object: "list", has_more: before2 !== null ? start2 > 0 : start2 + limit2 < end, data: data7 };
95109
95109
  }
95110
95110
  function handle(route15) {
95111
95111
  return async (c) => {
@@ -97086,9 +97086,9 @@ function botAccounts(env2) {
97086
97086
  return out;
97087
97087
  }
97088
97088
  function unread(rows35, seen, highest) {
97089
- const before = new Set(seen ?? rows35.filter((row2) => row2.id <= highest).map((row2) => row2.id));
97090
- const fresh = rows35.filter((row2) => !before.has(row2.id));
97091
- return { fresh, seen: [...before, ...fresh.map((row2) => row2.id)] };
97089
+ const before2 = new Set(seen ?? rows35.filter((row2) => row2.id <= highest).map((row2) => row2.id));
97090
+ const fresh = rows35.filter((row2) => !before2.has(row2.id));
97091
+ return { fresh, seen: [...before2, ...fresh.map((row2) => row2.id)] };
97092
97092
  }
97093
97093
  function readMessages(env2, after = { slack: 0, issue: 0, comment: 0 }) {
97094
97094
  const out = [];
@@ -99519,9 +99519,9 @@ function text17(bytes4) {
99519
99519
  }
99520
99520
  }
99521
99521
  function diffFiles(ctx, repoId, base6, head) {
99522
- const before = files(ctx, repoId, base6), after = files(ctx, repoId, head), repo4 = getRepo(ctx, repoId);
99523
- return [.../* @__PURE__ */ new Set([...before.keys(), ...after.keys()])].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b))).flatMap((filename) => {
99524
- const old = before.get(filename), next2 = after.get(filename);
99522
+ const before2 = files(ctx, repoId, base6), after = files(ctx, repoId, head), repo4 = getRepo(ctx, repoId);
99523
+ return [.../* @__PURE__ */ new Set([...before2.keys(), ...after.keys()])].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b))).flatMap((filename) => {
99524
+ const old = before2.get(filename), next2 = after.get(filename);
99525
99525
  if (old && next2 && old.sha === next2.sha && old.mode === next2.mode) return [];
99526
99526
  const from = text17(old?.bytes ?? Buffer.alloc(0)), to = text17(next2?.bytes ?? Buffer.alloc(0));
99527
99527
  let additions = 0, deletions = 0, patch;
@@ -99934,15 +99934,15 @@ function openHeadPulls(ctx, repo4, ref23) {
99934
99934
  if (!ref23.startsWith("refs/heads/")) return [];
99935
99935
  return ctx.store.db.prepare("SELECT p.* FROM github_pulls p JOIN github_issues i ON i.repo_id = p.repo_id AND i.number = p.number WHERE p.repo_id = ? AND p.head_ref = ? AND p.merged = 0 AND i.state = 'open' ORDER BY p.number").all(repo4.id, ref23.slice(11));
99936
99936
  }
99937
- function refEvents(ctx, repo4, ref23, before, after, previousPulls = [], pusher) {
99938
- if (!ref23.startsWith("refs/heads/") || before === after) return;
99937
+ function refEvents(ctx, repo4, ref23, before2, after, previousPulls = [], pusher) {
99938
+ if (!ref23.startsWith("refs/heads/") || before2 === after) return;
99939
99939
  const semantic = githubEventContext(ctx), user9 = pusher ?? botUser(ctx);
99940
- const excludedTip = before ?? branchTip(ctx, repo4.id, repo4.default_branch), excluded3 = new Set(excludedTip ? history(ctx, repo4.id, excludedTip) : []);
99940
+ const excludedTip = before2 ?? branchTip(ctx, repo4.id, repo4.default_branch), excluded3 = new Set(excludedTip ? history(ctx, repo4.id, excludedTip) : []);
99941
99941
  const commits = after ? history(ctx, repo4.id, after).filter((id15) => !excluded3.has(id15)).map((id15) => pushCommit(ctx, repo4, id15)) : [];
99942
- githubEvent(ctx, "push", { ref: ref23, before: before ?? zero, after: after ?? zero, created: before === void 0, deleted: after === void 0, forced: !!before && !!after && !isAncestor(ctx, repo4.id, before, after), base_ref: null, compare: `https://github.com/${repo4.full_name}/compare/${before ?? excludedTip ?? zero}...${after ?? zero}`, commits, head_commit: after ? pushCommit(ctx, repo4, after) : null, pusher: { name: user9.login, email: user9.email ?? `${user9.login}@users.noreply.github.com` }, repository: repositoryShape(semantic, repo4) });
99942
+ githubEvent(ctx, "push", { ref: ref23, before: before2 ?? zero, after: after ?? zero, created: before2 === void 0, deleted: after === void 0, forced: !!before2 && !!after && !isAncestor(ctx, repo4.id, before2, after), base_ref: null, compare: `https://github.com/${repo4.full_name}/compare/${before2 ?? excludedTip ?? zero}...${after ?? zero}`, commits, head_commit: after ? pushCommit(ctx, repo4, after) : null, pusher: { name: user9.login, email: user9.email ?? `${user9.login}@users.noreply.github.com` }, repository: repositoryShape(semantic, repo4) });
99943
99943
  if (after) {
99944
99944
  for (const pull2 of openHeadPulls(ctx, repo4, ref23)) {
99945
- const previousHead = before ?? previousPulls.find((previous) => previous.number === pull2.number)?.head_sha;
99945
+ const previousHead = before2 ?? previousPulls.find((previous) => previous.number === pull2.number)?.head_sha;
99946
99946
  if (previousHead && previousHead !== after) pullEvent(ctx, repo4, pull2, "synchronize", { before: previousHead, after });
99947
99947
  }
99948
99948
  }
@@ -102394,12 +102394,12 @@ function ensureLabel(ctx, repo4, name5) {
102394
102394
  function applyIssueLabels(ctx, repo4, issue9, names8, mode, senderId, emit2 = true) {
102395
102395
  const previous = issueLabels(ctx, repo4.id, issue9.number);
102396
102396
  const ids3 = names8.map((name5) => ensureLabel(ctx, repo4, name5).id);
102397
- const before = ctx.store.db.prepare("SELECT label_id FROM github_issue_labels WHERE repo_id = ? AND issue_number = ? ORDER BY label_id").all(repo4.id, issue9.number).map((row2) => row2.label_id);
102397
+ const before2 = ctx.store.db.prepare("SELECT label_id FROM github_issue_labels WHERE repo_id = ? AND issue_number = ? ORDER BY label_id").all(repo4.id, issue9.number).map((row2) => row2.label_id);
102398
102398
  if (mode === "set") ctx.store.db.prepare("DELETE FROM github_issue_labels WHERE repo_id = ? AND issue_number = ?").run(repo4.id, issue9.number);
102399
102399
  const insert = ctx.store.db.prepare("INSERT OR IGNORE INTO github_issue_labels (repo_id,issue_number,label_id) VALUES (?,?,?)");
102400
102400
  for (const id15 of ids3) insert.run(repo4.id, issue9.number, id15);
102401
102401
  const after = ctx.store.db.prepare("SELECT label_id FROM github_issue_labels WHERE repo_id = ? AND issue_number = ? ORDER BY label_id").all(repo4.id, issue9.number).map((row2) => row2.label_id);
102402
- if (before.join() === after.join()) return { added: [], removed: [] };
102402
+ if (before2.join() === after.join()) return { added: [], removed: [] };
102403
102403
  ctx.store.db.prepare("UPDATE github_issues SET updated_at = ? WHERE id = ?").run(ctx.clock.now().toISOString(), issue9.id);
102404
102404
  const current = issueLabels(ctx, repo4.id, issue9.number);
102405
102405
  const changes = { added: current.filter((label7) => !previous.some((p2) => p2.id === label7.id)), removed: previous.filter((label7) => !current.some((c) => c.id === label7.id)) };
@@ -103642,12 +103642,12 @@ function initializeCatalogIntegrations(env2) {
103642
103642
  }
103643
103643
  function reconcileCatalogIntegrations(env2) {
103644
103644
  if (!hasTable5(env2, "world_catalog_cursor")) return { activity: false };
103645
- const all9 = entries(env2), before = env2.events.tail;
103645
+ const all9 = entries(env2), before2 = env2.events.tail;
103646
103646
  let cursor4 = env2.store.db.prepare("SELECT cursor FROM world_catalog_cursor WHERE id = 1").get().cursor;
103647
103647
  let activity3 = false;
103648
103648
  scan: for (let batch3 = env2.events.list(cursor4, 100); batch3.length; batch3 = env2.events.list(cursor4, 100)) {
103649
103649
  for (const event3 of batch3) {
103650
- if (event3.cursor > before + MAX_CASCADE) {
103650
+ if (event3.cursor > before2 + MAX_CASCADE) {
103651
103651
  issue2(env2, void 0, `their own actions emitted more than ${MAX_CASCADE} events in one round, so they may be triggering each other; the rest were skipped`);
103652
103652
  cursor4 = env2.events.tail;
103653
103653
  break scan;
@@ -107897,8 +107897,8 @@ function page7(items2, params10, url4, objectName) {
107897
107897
  const limit2 = int2(params10.limit, "limit") ?? 10;
107898
107898
  if (limit2 < 1) invalid10("This value must be greater than or equal to 1.", "limit");
107899
107899
  if (limit2 > 100) invalid10("This value must be less than or equal to 100.", "limit");
107900
- const after = str(params10.starting_after, "starting_after"), before = str(params10.ending_before, "ending_before");
107901
- if (after !== void 0 && before !== void 0) invalid10("You may only specify one of these parameters: starting_after, ending_before.", "starting_after");
107900
+ const after = str(params10.starting_after, "starting_after"), before2 = str(params10.ending_before, "ending_before");
107901
+ if (after !== void 0 && before2 !== void 0) invalid10("You may only specify one of these parameters: starting_after, ending_before.", "starting_after");
107902
107902
  let window5 = items2;
107903
107903
  if (after !== void 0) {
107904
107904
  const i = items2.findIndex((item2) => item2.id === after);
@@ -107906,9 +107906,9 @@ function page7(items2, params10, url4, objectName) {
107906
107906
  window5 = items2.slice(i + 1, i + 1 + limit2);
107907
107907
  return { object: "list", data: window5, has_more: i + 1 + limit2 < items2.length, url: url4 };
107908
107908
  }
107909
- if (before !== void 0) {
107910
- const i = items2.findIndex((item2) => item2.id === before);
107911
- if (i < 0) missing2(objectName, before, "ending_before");
107909
+ if (before2 !== void 0) {
107910
+ const i = items2.findIndex((item2) => item2.id === before2);
107911
+ if (i < 0) missing2(objectName, before2, "ending_before");
107912
107912
  window5 = items2.slice(Math.max(0, i - limit2), i);
107913
107913
  return { object: "list", data: window5, has_more: i - limit2 > 0, url: url4 };
107914
107914
  }
@@ -108381,14 +108381,14 @@ function eventRequest(ctx, request2) {
108381
108381
  if (request2) requests.set(ctx, request2);
108382
108382
  else requests.delete(ctx);
108383
108383
  }
108384
- function recordChange(ctx, row2, before) {
108385
- if (row2.object === "customer" && row2.balance !== (before?.balance ?? 0)) {
108384
+ function recordChange(ctx, row2, before2) {
108385
+ if (row2.object === "customer" && row2.balance !== (before2?.balance ?? 0)) {
108386
108386
  const account9 = load2(ctx, "__account");
108387
108387
  save3(ctx, {
108388
108388
  id: newId(ctx, "cbtxn"),
108389
108389
  object: "customer_balance_transaction",
108390
- amount: row2.balance - (before?.balance ?? 0),
108391
- created: before ? nowSeconds(ctx) : row2.created,
108390
+ amount: row2.balance - (before2?.balance ?? 0),
108391
+ created: before2 ? nowSeconds(ctx) : row2.created,
108392
108392
  currency: row2.currency ?? account9.currency,
108393
108393
  customer: row2.id,
108394
108394
  customer_account: null,
@@ -108405,26 +108405,26 @@ function recordChange(ctx, row2, before) {
108405
108405
  }
108406
108406
  const prefix2 = PREFIX[row2.object], connectTypes = connectEventTypes.get(row2.object);
108407
108407
  if (!prefix2 && !connectTypes || load2(ctx, "__account")?.__seeding) return;
108408
- const previous = before ? clean(before) : void 0, current = clean(row2);
108408
+ const previous = before2 ? clean(before2) : void 0, current = clean(row2);
108409
108409
  if (previous && JSON.stringify(previous) === JSON.stringify(current)) return;
108410
108410
  let types;
108411
- if (connectTypes) types = connectTypes(row2, before);
108411
+ if (connectTypes) types = connectTypes(row2, before2);
108412
108412
  else if (row2.object === "checkout.session") {
108413
- types = before && row2.status !== before.status && ["complete", "expired"].includes(row2.status) ? [`checkout.session.${row2.status === "complete" ? "completed" : "expired"}`] : [];
108414
- } else if (!before) {
108413
+ types = before2 && row2.status !== before2.status && ["complete", "expired"].includes(row2.status) ? [`checkout.session.${row2.status === "complete" ? "completed" : "expired"}`] : [];
108414
+ } else if (!before2) {
108415
108415
  types = row2.object === "charge" ? [`charge.${row2.status === "succeeded" ? "succeeded" : "failed"}`] : row2.object === "payment_method" ? row2.customer ? ["payment_method.attached"] : [] : [`${prefix2}.created`];
108416
- } else if (row2.deleted && !before.deleted || row2.object === "subscription" && row2.status === "canceled" && before.status !== "canceled") types = [`${prefix2}.deleted`];
108417
- else if (row2.object === "payment_method") types = row2.customer !== before.customer ? [`payment_method.${row2.customer ? "attached" : "detached"}`] : ["payment_method.updated"];
108418
- else if (row2.object === "charge") types = row2.amount_refunded !== before.amount_refunded ? ["charge.refunded"] : ["charge.updated"];
108416
+ } else if (row2.deleted && !before2.deleted || row2.object === "subscription" && row2.status === "canceled" && before2.status !== "canceled") types = [`${prefix2}.deleted`];
108417
+ else if (row2.object === "payment_method") types = row2.customer !== before2.customer ? [`payment_method.${row2.customer ? "attached" : "detached"}`] : ["payment_method.updated"];
108418
+ else if (row2.object === "charge") types = row2.amount_refunded !== before2.amount_refunded ? ["charge.refunded"] : ["charge.updated"];
108419
108419
  else if (row2.object === "payment_intent") {
108420
- types = row2.status !== before.status || row2.latest_charge !== before.latest_charge ? row2.status === "requires_payment_method" && row2.last_payment_error ? ["payment_intent.payment_failed"] : ["succeeded", "canceled", "processing", "requires_action"].includes(row2.status) ? [`payment_intent.${row2.status}`] : [] : [];
108421
- } else if (row2.object === "invoice" && row2.status !== before.status) {
108422
- types = row2.status === "open" && before.status === "draft" ? ["invoice.finalized"] : row2.status === "paid" ? row2.amount_paid_off_stripe > before.amount_paid_off_stripe ? ["invoice.paid"] : ["invoice.paid", "invoice.payment_succeeded"] : row2.status === "void" ? ["invoice.voided"] : row2.status === "uncollectible" ? ["invoice.marked_uncollectible"] : ["invoice.updated"];
108423
- } else if (row2.object === "invoice" && row2.attempt_count > before.attempt_count && row2.status === "open") types = ["invoice.payment_failed"];
108420
+ types = row2.status !== before2.status || row2.latest_charge !== before2.latest_charge ? row2.status === "requires_payment_method" && row2.last_payment_error ? ["payment_intent.payment_failed"] : ["succeeded", "canceled", "processing", "requires_action"].includes(row2.status) ? [`payment_intent.${row2.status}`] : [] : [];
108421
+ } else if (row2.object === "invoice" && row2.status !== before2.status) {
108422
+ types = row2.status === "open" && before2.status === "draft" ? ["invoice.finalized"] : row2.status === "paid" ? row2.amount_paid_off_stripe > before2.amount_paid_off_stripe ? ["invoice.paid"] : ["invoice.paid", "invoice.payment_succeeded"] : row2.status === "void" ? ["invoice.voided"] : row2.status === "uncollectible" ? ["invoice.marked_uncollectible"] : ["invoice.updated"];
108423
+ } else if (row2.object === "invoice" && row2.attempt_count > before2.attempt_count && row2.status === "open") types = ["invoice.payment_failed"];
108424
108424
  else types = row2.object === "invoiceitem" ? [] : [`${prefix2}.updated`];
108425
108425
  const changed = previous ? Object.fromEntries(Object.keys(previous).filter((k) => JSON.stringify(previous[k]) !== JSON.stringify(current[k])).map((k) => [k, previous[k]])) : {};
108426
108426
  const owner6 = eventOwner(row2);
108427
- for (const type of types) emitEvent(ctx, type, current, { previous: type.endsWith(".updated") && before ? changed : void 0, account: owner6 });
108427
+ for (const type of types) emitEvent(ctx, type, current, { previous: type.endsWith(".updated") && before2 ? changed : void 0, account: owner6 });
108428
108428
  }
108429
108429
  function emitEvent(ctx, type, object28, o = {}) {
108430
108430
  const event3 = save3(ctx, {
@@ -108500,13 +108500,13 @@ function load2(ctx, id15) {
108500
108500
  return row2 ? JSON.parse(row2.json) : void 0;
108501
108501
  }
108502
108502
  function save3(ctx, value6) {
108503
- const before = load2(ctx, value6.id);
108503
+ const before2 = load2(ctx, value6.id);
108504
108504
  const db3 = ctx.store.db;
108505
108505
  const existing3 = db3.prepare("SELECT seq FROM stripe_objects WHERE id = ?").get(value6.id);
108506
108506
  const seq2 = existing3?.seq ?? ctx.store.counters.next("stripe:seq");
108507
108507
  const customer3 = typeof value6.customer === "string" ? value6.customer : value6.object === "customer" ? value6.id : null;
108508
108508
  db3.prepare("INSERT OR REPLACE INTO stripe_objects (id, type, seq, created, customer, json) VALUES (?, ?, ?, ?, ?, ?)").run(value6.id, value6.object, seq2, typeof value6.created === "number" ? value6.created : 0, customer3, JSON.stringify(value6));
108509
- recordChange(ctx, value6, before);
108509
+ recordChange(ctx, value6, before2);
108510
108510
  return value6;
108511
108511
  }
108512
108512
  function all2(ctx, type) {
@@ -109525,9 +109525,9 @@ var init_connect_funds = __esm({
109525
109525
  refundsOf = (ctx, id15) => all2(ctx, "fee_refund").filter((r2) => r2.fee === id15);
109526
109526
  transferView = (ctx, t) => ({ ...t, reversals: nestedList(reversalsOf(ctx, t.id), `/v1/transfers/${t.id}/reversals`) });
109527
109527
  feeView = (ctx, f2) => ({ ...f2, refunds: nestedList(refundsOf(ctx, f2.id), `/v1/application_fees/${f2.id}/refunds`) });
109528
- connectEventTypes.set("transfer", (row2, before) => !before ? ["transfer.created"] : row2.amount_reversed !== before.amount_reversed ? ["transfer.reversed", "transfer.updated"] : ["transfer.updated"]);
109529
- connectEventTypes.set("application_fee", (row2, before) => !before ? ["application_fee.created"] : row2.amount_refunded !== before.amount_refunded ? ["application_fee.refunded"] : []);
109530
- connectEventTypes.set("fee_refund", (_row, before) => before ? ["application_fee.refund.updated"] : []);
109528
+ connectEventTypes.set("transfer", (row2, before2) => !before2 ? ["transfer.created"] : row2.amount_reversed !== before2.amount_reversed ? ["transfer.reversed", "transfer.updated"] : ["transfer.updated"]);
109529
+ connectEventTypes.set("application_fee", (row2, before2) => !before2 ? ["application_fee.created"] : row2.amount_refunded !== before2.amount_refunded ? ["application_fee.refunded"] : []);
109530
+ connectEventTypes.set("fee_refund", (_row, before2) => before2 ? ["application_fee.refund.updated"] : []);
109531
109531
  fundsRoutes = [
109532
109532
  write3("POST", "/v1/transfers", ["amount", "currency", "destination", "source_transaction", "transfer_group", "description", "metadata", "source_type"], ({ ctx, params: p2 }) => {
109533
109533
  if (p2.source_type !== void 0 && str(p2.source_type, "source_type") !== "card") unsupported8("transfer source_type other than card");
@@ -137698,11 +137698,11 @@ function find2(access16, kind2, id15) {
137698
137698
  return row2;
137699
137699
  }
137700
137700
  function pagination2(rows35, query12, defaultLimit = 20, max = 500) {
137701
- const limit2 = integer5(query12.limit, "limit", defaultLimit, max), after = query12.after, before = query12.before;
137702
- if (after !== void 0 && before !== void 0) invalid12("Use only after or before");
137701
+ const limit2 = integer5(query12.limit, "limit", defaultLimit, max), after = query12.after, before2 = query12.before;
137702
+ if (after !== void 0 && before2 !== void 0) invalid12("Use only after or before");
137703
137703
  let start2 = 0, end = rows35.length;
137704
- if (after !== void 0 || before !== void 0) {
137705
- const cursor4 = text18(after ?? before, "cursor", 4096), index = rows35.findIndex((row2) => row2.id === cursor4);
137704
+ if (after !== void 0 || before2 !== void 0) {
137705
+ const cursor4 = text18(after ?? before2, "cursor", 4096), index = rows35.findIndex((row2) => row2.id === cursor4);
137706
137706
  if (index < 0) invalid12("Cursor is not visible in this result");
137707
137707
  if (after !== void 0) start2 = index + 1;
137708
137708
  else {
@@ -137711,7 +137711,7 @@ function pagination2(rows35, query12, defaultLimit = 20, max = 500) {
137711
137711
  }
137712
137712
  }
137713
137713
  const selected3 = rows35.slice(start2, Math.min(start2 + limit2, end));
137714
- return { object: "list", data: selected3, first_id: selected3[0]?.id ?? null, last_id: selected3.at(-1)?.id ?? null, has_more: before !== void 0 ? start2 > 0 : start2 + selected3.length < rows35.length };
137714
+ return { object: "list", data: selected3, first_id: selected3[0]?.id ?? null, last_id: selected3.at(-1)?.id ?? null, has_more: before2 !== void 0 ? start2 > 0 : start2 + selected3.length < rows35.length };
137715
137715
  }
137716
137716
  function canonical4(value6) {
137717
137717
  if (Array.isArray(value6)) return `[${value6.map(canonical4).join(",")}]`;
@@ -139956,10 +139956,10 @@ var init_git = __esm({
139956
139956
  if (typeof force !== "boolean") throw new GitHubError(422, "Invalid force");
139957
139957
  ctx.signal?.throwIfAborted();
139958
139958
  return withMutation(ctx, () => {
139959
- const before = findRef(ctx, repo4, ref23);
139960
- if (!before) throw new GitHubError(422, "Reference does not exist");
139959
+ const before2 = findRef(ctx, repo4, ref23);
139960
+ if (!before2) throw new GitHubError(422, "Reference does not exist");
139961
139961
  moveRef(ctx, repo4.id, ref23, id15, { force });
139962
- refEvents(ctx, repo4, ref23, before.sha, id15);
139962
+ refEvents(ctx, repo4, ref23, before2.sha, id15);
139963
139963
  return refShape(ctx, repo4, ref23, id15);
139964
139964
  });
139965
139965
  } },
@@ -139969,10 +139969,10 @@ var init_git = __esm({
139969
139969
  ctx.signal?.throwIfAborted();
139970
139970
  return withMutation(ctx, () => {
139971
139971
  if (ref23 === `refs/heads/${repo4.default_branch}`) throw new GitHubError(422, "Cannot delete the default branch");
139972
- const before = findRef(ctx, repo4, ref23);
139973
- if (!before) throw new GitHubError(422, "Reference does not exist");
139972
+ const before2 = findRef(ctx, repo4, ref23);
139973
+ if (!before2) throw new GitHubError(422, "Reference does not exist");
139974
139974
  ctx.store.db.prepare("DELETE FROM github_refs WHERE repo_id = ? AND ref = ?").run(repo4.id, ref23);
139975
- refEvents(ctx, repo4, ref23, before.sha, void 0);
139975
+ refEvents(ctx, repo4, ref23, before2.sha, void 0);
139976
139976
  return new Response(null, { status: 204 });
139977
139977
  });
139978
139978
  } }
@@ -142979,8 +142979,8 @@ function validated3(ctx, type, body8, prior) {
142979
142979
  }
142980
142980
  return record32;
142981
142981
  }
142982
- function history2(ctx, type, id15, operation, before, after) {
142983
- ctx.store.db.prepare("INSERT INTO salesforce_history(type,id,operation,at,before_json,after_json) VALUES(?,?,?,?,?,?)").run(type, id15, operation, ctx.clock.now().toISOString(), before ? JSON.stringify(before) : null, after ? JSON.stringify(after) : null);
142982
+ function history2(ctx, type, id15, operation, before2, after) {
142983
+ ctx.store.db.prepare("INSERT INTO salesforce_history(type,id,operation,at,before_json,after_json) VALUES(?,?,?,?,?,?)").run(type, id15, operation, ctx.clock.now().toISOString(), before2 ? JSON.stringify(before2) : null, after ? JSON.stringify(after) : null);
142984
142984
  }
142985
142985
  function createRecord2(ctx, type, body8) {
142986
142986
  permission5(ctx, true);
@@ -149293,7 +149293,7 @@ function connection2(r2, type, rows35, args, toObj) {
149293
149293
  }
149294
149294
  const limit2 = (n2) => Math.min(n2, 250);
149295
149295
  let window5 = kept.slice(start2, Math.max(start2, end));
149296
- const before = window5.length;
149296
+ const before2 = window5.length;
149297
149297
  if (args.last !== void 0 && args.last !== null && (args.first === void 0 || args.first === null)) window5 = window5.slice(Math.max(0, window5.length - limit2(args.last)));
149298
149298
  else window5 = window5.slice(0, limit2(args.first ?? 50));
149299
149299
  const firstIndex = kept.indexOf(window5[0]), lastIndex = kept.indexOf(window5[window5.length - 1]);
@@ -149303,7 +149303,7 @@ function connection2(r2, type, rows35, args, toObj) {
149303
149303
  startCursor: window5[0]?.id ?? null,
149304
149304
  endCursor: window5[window5.length - 1]?.id ?? null,
149305
149305
  hasPreviousPage: window5.length ? firstIndex > 0 : start2 > 0,
149306
- hasNextPage: window5.length ? lastIndex < kept.length - 1 : before > 0 && start2 + before < kept.length
149306
+ hasNextPage: window5.length ? lastIndex < kept.length - 1 : before2 > 0 && start2 + before2 < kept.length
149307
149307
  }
149308
149308
  };
149309
149309
  }
@@ -151438,7 +151438,7 @@ function capabilityView(a, name5) {
151438
151438
  }
151439
151439
  function recomputeAccount(ctx, a, persist = true) {
151440
151440
  initializeAccount(a);
151441
- const before = load2(ctx, a.id), r2 = a.requirements;
151441
+ const before2 = load2(ctx, a.id), r2 = a.requirements;
151442
151442
  const extra2 = a.__requirements_extra;
151443
151443
  const initial = a.details_submitted ? [] : requiredFields(a).filter((f2) => !a.__satisfied.includes(f2));
151444
151444
  const oldCurrent = new Set(r2.currently_due);
@@ -151463,9 +151463,9 @@ function recomputeAccount(ctx, a, persist = true) {
151463
151463
  r2.disabled_reason = r2.past_due.length ? "requirements.past_due" : a.__review_at != null ? "requirements.pending_verification" : r2.currently_due.length && !CAPABILITIES.some((k) => status6[k] === "active") ? "requirements.past_due" : null;
151464
151464
  if (!persist) return a;
151465
151465
  save3(ctx, a);
151466
- if (before && !a.__creating && !load2(ctx, "__account")?.__seeding) for (const k of CAPABILITIES) {
151467
- if ((before.capabilities?.[k] ?? "unrequested") !== (a.capabilities[k] ?? "unrequested")) {
151468
- emitEvent(ctx, "capability.updated", capabilityView(a, k), { account: a.id, previous: { status: before.capabilities?.[k] ?? "unrequested" } });
151466
+ if (before2 && !a.__creating && !load2(ctx, "__account")?.__seeding) for (const k of CAPABILITIES) {
151467
+ if ((before2.capabilities?.[k] ?? "unrequested") !== (a.capabilities[k] ?? "unrequested")) {
151468
+ emitEvent(ctx, "capability.updated", capabilityView(a, k), { account: a.id, previous: { status: before2.capabilities?.[k] ?? "unrequested" } });
151469
151469
  }
151470
151470
  }
151471
151471
  return a;
@@ -151551,8 +151551,8 @@ var init_connect_account_state = __esm({
151551
151551
  CAPABILITIES = ["card_payments", "transfers"];
151552
151552
  emptyRequirements2 = () => ({ alternatives: [], current_deadline: null, currently_due: [], disabled_reason: null, errors: [], eventually_due: [], past_due: [], pending_verification: [] });
151553
151553
  unique3 = (items2) => [...new Set(items2)].sort();
151554
- connectEventTypes.set("account", (row2, before) => before && !row2.deleted && !row2.__creating ? ["account.updated"] : []);
151555
- connectEventTypes.set("bank_account", (row2, before) => row2.deleted ? before && !before.deleted ? ["account.external_account.deleted"] : [] : before ? ["account.external_account.updated"] : ["account.external_account.created"]);
151554
+ connectEventTypes.set("account", (row2, before2) => before2 && !row2.deleted && !row2.__creating ? ["account.updated"] : []);
151555
+ connectEventTypes.set("bank_account", (row2, before2) => row2.deleted ? before2 && !before2.deleted ? ["account.external_account.deleted"] : [] : before2 ? ["account.external_account.updated"] : ["account.external_account.created"]);
151556
151556
  for (const type of ["review", "deadline"]) connectJobs.set(type, (ctx, p2) => {
151557
151557
  if (p2.type !== type || typeof p2.account !== "string" || !Number.isSafeInteger(p2.version) || p2.version < 1 || !Number.isSafeInteger(p2.at) || Object.keys(p2).some((k) => !["type", "account", "version", "at"].includes(k))) throw new InvalidJob(`invalid stripe.connect ${type} payload`);
151558
151558
  const a = findAccount(ctx, p2.account);
@@ -152106,9 +152106,9 @@ var init_connect_payouts = __esm({
152106
152106
  debit_not_authorized: "The bank account does not authorize this transaction.",
152107
152107
  invalid_currency: "The bank account cannot receive payouts in this currency."
152108
152108
  };
152109
- connectEventTypes.set("payout", (row2, before) => !before ? ["payout.created"] : [
152109
+ connectEventTypes.set("payout", (row2, before2) => !before2 ? ["payout.created"] : [
152110
152110
  "payout.updated",
152111
- ...row2.status !== before.status && ["paid", "failed", "canceled"].includes(row2.status) ? [`payout.${row2.status}`] : []
152111
+ ...row2.status !== before2.status && ["paid", "failed", "canceled"].includes(row2.status) ? [`payout.${row2.status}`] : []
152112
152112
  ]);
152113
152113
  for (const type of ["payout_submit", "payout_arrive"]) connectJobs.set(type, (ctx, p2) => {
152114
152114
  if (p2.type !== type || typeof p2.payout !== "string" || !p2.payout.startsWith("po_") || !Number.isSafeInteger(p2.at) || Object.keys(p2).some((k) => !["type", "payout", "at"].includes(k))) throw new InvalidJob(`invalid stripe.connect ${type} payload`);
@@ -153223,8 +153223,8 @@ function unchanged(ctx, args) {
153223
153223
  if (baseline === void 0) throw new AnchaError("USAGE", "Stripe seed baseline is absent from this checkpoint", { hint: "create a fresh world to evaluate stripe.unchanged" });
153224
153224
  const changes = args.objects.flatMap((object28) => {
153225
153225
  const row2 = resolve6(ctx, object28.type, object28.id);
153226
- const before = row2 && baseline?.[row2.id];
153227
- const reason2 = !row2 ? "object absent" : !before ? "seed baseline absent" : !isDeepStrictEqual2(present(row2), before) ? "object changed" : void 0;
153226
+ const before2 = row2 && baseline?.[row2.id];
153227
+ const reason2 = !row2 ? "object absent" : !before2 ? "seed baseline absent" : !isDeepStrictEqual2(present(row2), before2) ? "object changed" : void 0;
153228
153228
  return reason2 ? [{ ...object28, reason: reason2 }] : [];
153229
153229
  });
153230
153230
  return checkOutcome(changes.length === 0, `objects unchanged from seed: ${JSON.stringify(args.objects)}`, changes.length ? JSON.stringify(changes) : "all named objects equal their seed state");
@@ -153913,8 +153913,8 @@ function filterUsers(call4, query12) {
153913
153913
  })) : void 0;
153914
153914
  const contains3 = (value6, needle) => needle === null || (value6 ?? "").toLowerCase().includes(needle.toLowerCase());
153915
153915
  const q2 = query12.get("query"), banned = bool4(query12.get("banned") ?? void 0, "banned");
153916
- const before = time7("last_active_at_before"), after = time7("last_active_at_after") ?? time7("last_active_at_since"), createdBefore = time7("created_at_before"), createdAfter = time7("created_at_after");
153917
- return ctx.store.db.prepare("SELECT * FROM clerk_users").all().filter((user9) => (!emails.length || emails.includes(user9.email.toLowerCase())) && (!ids3.length || ids3.includes(user9.id)) && (!usernames.length || usernames.includes(user9.username ?? "")) && (!externals.length || externals.includes(user9.external_id ?? "")) && (!members4 || members4.has(user9.id)) && (q2 === null || [user9.email, user9.first_name, user9.last_name, user9.username, user9.id, user9.external_id, `${user9.first_name ?? ""} ${user9.last_name ?? ""}`].some((value6) => contains3(value6, q2))) && contains3(user9.email, query12.get("email_address_query")) && contains3(user9.username, query12.get("username_query")) && contains3(`${user9.first_name ?? ""} ${user9.last_name ?? ""}`, query12.get("name_query")) && (banned === void 0 || user9.banned === 1 === banned) && (before === void 0 || user9.last_active_ms !== null && user9.last_active_ms < before) && (after === void 0 || user9.last_active_ms !== null && user9.last_active_ms > after) && (createdBefore === void 0 || user9.created_ms < createdBefore) && (createdAfter === void 0 || user9.created_ms > createdAfter));
153916
+ const before2 = time7("last_active_at_before"), after = time7("last_active_at_after") ?? time7("last_active_at_since"), createdBefore = time7("created_at_before"), createdAfter = time7("created_at_after");
153917
+ return ctx.store.db.prepare("SELECT * FROM clerk_users").all().filter((user9) => (!emails.length || emails.includes(user9.email.toLowerCase())) && (!ids3.length || ids3.includes(user9.id)) && (!usernames.length || usernames.includes(user9.username ?? "")) && (!externals.length || externals.includes(user9.external_id ?? "")) && (!members4 || members4.has(user9.id)) && (q2 === null || [user9.email, user9.first_name, user9.last_name, user9.username, user9.id, user9.external_id, `${user9.first_name ?? ""} ${user9.last_name ?? ""}`].some((value6) => contains3(value6, q2))) && contains3(user9.email, query12.get("email_address_query")) && contains3(user9.username, query12.get("username_query")) && contains3(`${user9.first_name ?? ""} ${user9.last_name ?? ""}`, query12.get("name_query")) && (banned === void 0 || user9.banned === 1 === banned) && (before2 === void 0 || user9.last_active_ms !== null && user9.last_active_ms < before2) && (after === void 0 || user9.last_active_ms !== null && user9.last_active_ms > after) && (createdBefore === void 0 || user9.created_ms < createdBefore) && (createdAfter === void 0 || user9.created_ms > createdAfter));
153918
153918
  }
153919
153919
  function listUsers2(call4) {
153920
153920
  const query12 = params7(call4, [...USER_FILTERS, "limit", "offset", "order_by"]);
@@ -154707,7 +154707,7 @@ function resources(ctx) {
154707
154707
  return out;
154708
154708
  }
154709
154709
  function withClerkEvents(ctx, fn) {
154710
- const before = resources(ctx), result = fn(), after = resources(ctx);
154710
+ const before2 = resources(ctx), result = fn(), after = resources(ctx);
154711
154711
  const emit2 = (resource2, change4, deleted = false) => {
154712
154712
  if (resource2.json.object === "invitation") return;
154713
154713
  const type = `${resource2.type}.${change4}`;
@@ -154719,9 +154719,9 @@ function withClerkEvents(ctx, fn) {
154719
154719
  instance_id: ctx.store.meta.get("clerk.instanceId")
154720
154720
  } });
154721
154721
  };
154722
- for (const resource2 of [...before.values()].reverse()) if (!after.has(resource2.id)) emit2(resource2, resource2.type === "session" ? "removed" : "deleted", true);
154722
+ for (const resource2 of [...before2.values()].reverse()) if (!after.has(resource2.id)) emit2(resource2, resource2.type === "session" ? "removed" : "deleted", true);
154723
154723
  for (const [id15, resource2] of after) {
154724
- const previous = before.get(id15);
154724
+ const previous = before2.get(id15);
154725
154725
  if (!previous) {
154726
154726
  emit2(resource2, "created");
154727
154727
  continue;
@@ -160015,9 +160015,9 @@ function deleteEntry(call4) {
160015
160015
  const args = fields9(call4, ["path", "parent_rev"]);
160016
160016
  const entry3 = existing(call4, args.path, "path_lookup");
160017
160017
  if (args.parent_rev !== void 0 && entry3.rev !== args.parent_rev) throw endpoint("path_lookup/not_found", tagged("path_lookup", "not_found"));
160018
- const before = metadata7(call4.ctx, entry3);
160018
+ const before2 = metadata7(call4.ctx, entry3);
160019
160019
  removeEntry(call4.ctx, entry3, call4.ctx.clock.nowMs());
160020
- return json18({ metadata: before });
160020
+ return json18({ metadata: before2 });
160021
160021
  }
160022
160022
  function relocate(call4, copy) {
160023
160023
  const args = fields9(call4, ["from_path", "to_path", "autorename", "allow_ownership_transfer", "allow_shared_folder"], []);
@@ -161625,9 +161625,9 @@ function save8(ctx, mail, value6) {
161625
161625
  value6.hasAttachments = value6.attachments.some((a) => !a.isInline);
161626
161626
  value6.lastModifiedDateTime = iso10(ctx);
161627
161627
  value6.changeKey = ctx.ids.hex(16);
161628
- const before = message7(ctx, mail, value6.id);
161628
+ const before2 = message7(ctx, mail, value6.id);
161629
161629
  ctx.store.db.prepare("INSERT OR REPLACE INTO outlook_messages VALUES (?, ?, ?, ?)").run(value6.id, mail, value6.parentFolderId, JSON.stringify(value6));
161630
- change(ctx, mail, value6.parentFolderId, value6.id, value6, !!before && before.isRead !== value6.isRead);
161630
+ change(ctx, mail, value6.parentFolderId, value6.id, value6, !!before2 && before2.isRead !== value6.isRead);
161631
161631
  }
161632
161632
  function change(ctx, mail, fid, id15, data7, readChanged = false) {
161633
161633
  ctx.store.db.prepare("INSERT INTO outlook_changes(mailbox, folder, id, data, read_changed) VALUES (?, ?, ?, ?, ?)").run(mail, fid, id15, JSON.stringify(data7), Number(readChanged));
@@ -163014,7 +163014,7 @@ function decode4(cursor4) {
163014
163014
  }
163015
163015
  }
163016
163016
  function connection3(items2, args, key5, shape6) {
163017
- const { first: first2, last, after, before } = args;
163017
+ const { first: first2, last, after, before: before2 } = args;
163018
163018
  if ((first2 === void 0 || first2 === null) && (last === void 0 || last === null)) throw new import_graphql7.GraphQLError("you must provide one of first or last", { extensions: { code: "BAD_REQUEST" } });
163019
163019
  for (const [name5, n2] of [["first", first2], ["last", last]]) {
163020
163020
  if (n2 !== void 0 && n2 !== null && (n2 < 0 || n2 > MAX_PAGE)) throw new import_graphql7.GraphQLError(`The ${name5} argument must be between 0 and ${MAX_PAGE}.`, { extensions: { code: "BAD_REQUEST" } });
@@ -163027,7 +163027,7 @@ function connection3(items2, args, key5, shape6) {
163027
163027
  };
163028
163028
  let start2 = 0, end = ordered5.length;
163029
163029
  if (after !== void 0 && after !== null) start2 = at6(after, "after") + 1;
163030
- if (before !== void 0 && before !== null) end = Math.max(start2, at6(before, "before"));
163030
+ if (before2 !== void 0 && before2 !== null) end = Math.max(start2, at6(before2, "before"));
163031
163031
  if (first2 !== void 0 && first2 !== null) end = Math.min(end, start2 + first2);
163032
163032
  if (last !== void 0 && last !== null) start2 = Math.max(start2, end - last);
163033
163033
  const page20 = ordered5.slice(start2, end);
@@ -170129,34 +170129,34 @@ function applyFields3(r2, draft2, fields13, update5, creating, errors3) {
170129
170129
  }
170130
170130
  void project14;
170131
170131
  }
170132
- function diff(r2, before, after) {
170132
+ function diff(r2, before2, after) {
170133
170133
  const name5 = (id15) => id15 === null ? null : userById2(r2.ctx, id15)?.name ?? null;
170134
170134
  const items2 = [];
170135
170135
  const add = (field6, from, to, fromString, toString, fieldId3) => {
170136
170136
  if (JSON.stringify(from) !== JSON.stringify(to)) items2.push({ field: field6, fieldId: fieldId3, from: from === null ? null : String(from), fromString, to: to === null ? null : String(to), toString });
170137
170137
  };
170138
- if (before.summary !== after.summary) items2.push({ field: "summary", from: null, fromString: before.summary, to: null, toString: after.summary });
170139
- if (JSON.stringify(before.description) !== JSON.stringify(after.description)) items2.push({ field: "description", from: null, fromString: adfToText(before.description) || null, to: null, toString: adfToText(after.description) || null });
170140
- add("issuetype", TYPES.find((t) => t.name === before.type).id, TYPES.find((t) => t.name === after.type).id, before.type, after.type);
170141
- add("priority", PRIORITIES.find((p2) => p2.name === before.priority).id, PRIORITIES.find((p2) => p2.name === after.priority).id, before.priority, after.priority);
170142
- add("assignee", before.assignee, after.assignee, name5(before.assignee), name5(after.assignee));
170143
- add("reporter", before.reporter, after.reporter, name5(before.reporter), name5(after.reporter));
170144
- if (JSON.stringify(before.labels) !== JSON.stringify(after.labels)) items2.push({ field: "labels", from: null, fromString: before.labels.join(" "), to: null, toString: after.labels.join(" ") });
170145
- add("IssueParentAssociation", before.parent_id, after.parent_id, before.parent_id ? one3(r2.ctx, "jira_issues", before.parent_id)?.key ?? null : null, after.parent_id ? one3(r2.ctx, "jira_issues", after.parent_id)?.key ?? null : null, "parent");
170146
- add("duedate", before.due, after.due, before.due, after.due);
170138
+ if (before2.summary !== after.summary) items2.push({ field: "summary", from: null, fromString: before2.summary, to: null, toString: after.summary });
170139
+ if (JSON.stringify(before2.description) !== JSON.stringify(after.description)) items2.push({ field: "description", from: null, fromString: adfToText(before2.description) || null, to: null, toString: adfToText(after.description) || null });
170140
+ add("issuetype", TYPES.find((t) => t.name === before2.type).id, TYPES.find((t) => t.name === after.type).id, before2.type, after.type);
170141
+ add("priority", PRIORITIES.find((p2) => p2.name === before2.priority).id, PRIORITIES.find((p2) => p2.name === after.priority).id, before2.priority, after.priority);
170142
+ add("assignee", before2.assignee, after.assignee, name5(before2.assignee), name5(after.assignee));
170143
+ add("reporter", before2.reporter, after.reporter, name5(before2.reporter), name5(after.reporter));
170144
+ if (JSON.stringify(before2.labels) !== JSON.stringify(after.labels)) items2.push({ field: "labels", from: null, fromString: before2.labels.join(" "), to: null, toString: after.labels.join(" ") });
170145
+ add("IssueParentAssociation", before2.parent_id, after.parent_id, before2.parent_id ? one3(r2.ctx, "jira_issues", before2.parent_id)?.key ?? null : null, after.parent_id ? one3(r2.ctx, "jira_issues", after.parent_id)?.key ?? null : null, "parent");
170146
+ add("duedate", before2.due, after.due, before2.due, after.due);
170147
170147
  const sprintNames = (ids3) => ids3.map((id15) => one3(r2.ctx, "jira_sprints", id15)?.name).join(", ") || null;
170148
- add("Sprint", before.sprint_ids.join(", ") || null, after.sprint_ids.join(", ") || null, sprintNames(before.sprint_ids), sprintNames(after.sprint_ids), SPRINT_FIELD);
170149
- add("Story point estimate", before.story_points, after.story_points, before.story_points === null ? null : String(before.story_points), after.story_points === null ? null : String(after.story_points), POINTS_FIELD);
170148
+ add("Sprint", before2.sprint_ids.join(", ") || null, after.sprint_ids.join(", ") || null, sprintNames(before2.sprint_ids), sprintNames(after.sprint_ids), SPRINT_FIELD);
170149
+ add("Story point estimate", before2.story_points, after.story_points, before2.story_points === null ? null : String(before2.story_points), after.story_points === null ? null : String(after.story_points), POINTS_FIELD);
170150
170150
  return items2;
170151
170151
  }
170152
170152
  function addComment(r2, issue9, body8, visibility, atMs) {
170153
170153
  const id15 = nextId4(r2.ctx, "comment");
170154
170154
  return saveComment(r2.ctx, { id: id15, issue_id: issue9.id, author: r2.me, update_author: r2.me, body: body8, visibility, created_ms: atMs, updated_ms: atMs });
170155
170155
  }
170156
- function finish(r2, before, draft2) {
170156
+ function finish(r2, before2, draft2) {
170157
170157
  const comments = draft2._comments;
170158
170158
  delete draft2._comments;
170159
- if (before) record21(r2.ctx, draft2.id, r2.me, now7(r2), diff(r2, before, draft2));
170159
+ if (before2) record21(r2.ctx, draft2.id, r2.me, now7(r2), diff(r2, before2, draft2));
170160
170160
  draft2.updated_ms = now7(r2);
170161
170161
  saveIssue(r2.ctx, draft2);
170162
170162
  for (const c of comments ?? []) addComment(r2, draft2, c.body, c.visibility, now7(r2));
@@ -170164,13 +170164,13 @@ function finish(r2, before, draft2) {
170164
170164
  }
170165
170165
  function transition4(r2, issue9, to, resolution, atMs) {
170166
170166
  if (issue9.status === to) return issue9;
170167
- const before = { ...issue9 }, done = to === "Done";
170167
+ const before2 = { ...issue9 }, done = to === "Done";
170168
170168
  issue9.status = to;
170169
170169
  issue9.status_changed_ms = atMs;
170170
170170
  issue9.resolution = done ? resolution ?? "Done" : null;
170171
170171
  issue9.resolved_ms = done ? atMs : null;
170172
- const items2 = [{ field: "status", from: STATUSES2.find((s3) => s3.name === before.status).id, fromString: before.status, to: STATUSES2.find((s3) => s3.name === to).id, toString: to }];
170173
- if (before.resolution !== issue9.resolution) items2.push({ field: "resolution", from: before.resolution ? RESOLUTIONS.find((x) => x.name === before.resolution).id : null, fromString: before.resolution, to: issue9.resolution ? RESOLUTIONS.find((x) => x.name === issue9.resolution).id : null, toString: issue9.resolution });
170172
+ const items2 = [{ field: "status", from: STATUSES2.find((s3) => s3.name === before2.status).id, fromString: before2.status, to: STATUSES2.find((s3) => s3.name === to).id, toString: to }];
170173
+ if (before2.resolution !== issue9.resolution) items2.push({ field: "resolution", from: before2.resolution ? RESOLUTIONS.find((x) => x.name === before2.resolution).id : null, fromString: before2.resolution, to: issue9.resolution ? RESOLUTIONS.find((x) => x.name === issue9.resolution).id : null, toString: issue9.resolution });
170174
170174
  record21(r2.ctx, issue9.id, r2.me, atMs, items2);
170175
170175
  issue9.updated_ms = atMs;
170176
170176
  return saveIssue(r2.ctx, issue9);
@@ -171489,9 +171489,9 @@ function amendOrder(ctx, order6, change4) {
171489
171489
  if (change4.clientOrderId !== null && ctx.store.db.prepare("SELECT 1 FROM kx_orders WHERE client_order_id = ? AND id != ?").get(change4.clientOrderId, order6.id)) {
171490
171490
  throw new KalshiError(409, "order_already_exists", "order already exists", `client_order_id ${change4.clientOrderId} is already in use`);
171491
171491
  }
171492
- const before = collateral(order6), after = (change4.count - order6.filled) * (order6.book_side === "bid" ? change4.price : ONE - change4.price);
171492
+ const before2 = collateral(order6), after = (change4.count - order6.filled) * (order6.book_side === "bid" ? change4.price : ONE - change4.price);
171493
171493
  const { available: available2 } = balances(ctx, now11);
171494
- if (after - before > available2) throw new KalshiError(400, "insufficient_balance", "insufficient balance");
171494
+ if (after - before2 > available2) throw new KalshiError(400, "insufficient_balance", "insufficient balance");
171495
171495
  ctx.store.db.prepare("UPDATE kx_orders SET price = ?, initial = ?, client_order_id = ?, expiration_ms = ?, updated_ms = ? WHERE id = ?").run(change4.price, change4.count, change4.clientOrderId ?? order6.client_order_id, change4.expirationMs ?? order6.expiration_ms, now11, order6.id);
171496
171496
  const amended = getOrder(ctx, order6.id), fills2 = take(ctx, amended, plan2(ctx, market2, amended.book_side, amended.price, amended.initial - amended.filled), now11);
171497
171497
  return { order: getOrder(ctx, order6.id), fills: fills2 };
@@ -174094,13 +174094,13 @@ function paginate7(call4, key5, items2, render3, sideload = () => ({})) {
174094
174094
  return url4.href;
174095
174095
  };
174096
174096
  if ([...params10.keys()].some((name5) => name5.startsWith("page["))) {
174097
- const size2 = integer12(params10.get("page[size]"), "page[size]", 1, 100) ?? 100, after = params10.get("page[after]"), before = params10.get("page[before]");
174097
+ const size2 = integer12(params10.get("page[size]"), "page[size]", 1, 100) ?? 100, after = params10.get("page[after]"), before2 = params10.get("page[before]");
174098
174098
  let start3 = 0, end = Math.min(items2.length, size2);
174099
174099
  if (after) {
174100
174100
  start3 = decode5(after, "page[after]") + 1;
174101
174101
  end = Math.min(items2.length, start3 + size2);
174102
- } else if (before) {
174103
- end = decode5(before, "page[before]");
174102
+ } else if (before2) {
174103
+ end = decode5(before2, "page[before]");
174104
174104
  start3 = Math.max(0, end - size2);
174105
174105
  }
174106
174106
  const page21 = items2.slice(start3, end), more = end < items2.length;
@@ -175266,11 +175266,11 @@ function guardOrganizer(r2, cal, e, b) {
175266
175266
  const personal = /* @__PURE__ */ new Set(["attendees", "reminders", "colorId", "transparency", "kind", "etag", "id"]);
175267
175267
  const others = Object.keys(b).filter((k) => !personal.has(k));
175268
175268
  const changedOthers = b.attendees !== void 0 && (() => {
175269
- const before = new Map(e.attendees.map((a) => [a.email.toLowerCase(), a]));
175269
+ const before2 = new Map(e.attendees.map((a) => [a.email.toLowerCase(), a]));
175270
175270
  const after = b.attendees;
175271
- if (!Array.isArray(after) || after.length !== before.size) return true;
175271
+ if (!Array.isArray(after) || after.length !== before2.size) return true;
175272
175272
  return after.some((a) => {
175273
- const was = before.get(String(a.email).toLowerCase());
175273
+ const was = before2.get(String(a.email).toLowerCase());
175274
175274
  return !was || String(a.email).toLowerCase() !== r2.me.email.toLowerCase() && a.responseStatus !== void 0 && a.responseStatus !== was.response;
175275
175275
  });
175276
175276
  })();
@@ -175605,9 +175605,9 @@ var init_routes24 = __esm({
175605
175605
  if (occurrence !== null) unsupported29("changing one occurrence of a recurring event");
175606
175606
  if (e.status === "cancelled") fail4(410, "deleted", "Resource has been deleted");
175607
175607
  guardOrganizer(r2, cal, e, r2.body);
175608
- const before = JSON.stringify(e);
175608
+ const before2 = JSON.stringify(e);
175609
175609
  applyEvent(r2, cal, e, r2.body, false);
175610
- if (JSON.stringify(e) !== before) {
175610
+ if (JSON.stringify(e) !== before2) {
175611
175611
  e.updated_ms = now9(r2);
175612
175612
  notify2(r2, e, "update");
175613
175613
  }
@@ -176319,13 +176319,13 @@ var init_routes25 = __esm({
176319
176319
  dollars4 = (micro, places = 5) => micro === null ? null : (micro / 1e6).toFixed(places);
176320
176320
  accountPath = (ctx) => `/2010-04-01/Accounts/${accountSid(ctx)}`;
176321
176321
  dateFilter = (query12, name5) => {
176322
- const exact = query12.get(name5), before = query12.get(`${name5}<`), after = query12.get(`${name5}>`);
176322
+ const exact = query12.get(name5), before2 = query12.get(`${name5}<`), after = query12.get(`${name5}>`);
176323
176323
  const day10 = (value6) => {
176324
176324
  const ms2 = Date.parse(/^\d{4}-\d{2}-\d{2}$/.test(value6) ? `${value6}T00:00:00Z` : value6);
176325
176325
  if (Number.isNaN(ms2)) throw new TwilioError(400, 20001, `${name5} must be a date`);
176326
176326
  return ms2;
176327
176327
  };
176328
- return (ms2) => ms2 !== null && (exact === null || ms2 >= day10(exact) && ms2 < day10(exact) + 864e5) && (before === null || ms2 < day10(before) + (/^\d{4}-\d{2}-\d{2}$/.test(before) ? 864e5 : 0)) && (after === null || ms2 >= day10(after));
176328
+ return (ms2) => ms2 !== null && (exact === null || ms2 >= day10(exact) && ms2 < day10(exact) + 864e5) && (before2 === null || ms2 < day10(before2) + (/^\d{4}-\d{2}-\d{2}$/.test(before2) ? 864e5 : 0)) && (after === null || ms2 >= day10(after));
176329
176329
  };
176330
176330
  balanceRoute = (call4) => json29({ account_sid: accountSid(call4.ctx), balance: (balance(call4.ctx, call4.ctx.clock.nowMs()) / 1e6).toFixed(2), currency: "USD" });
176331
176331
  liveMessages = (ctx) => ctx.store.db.prepare("SELECT * FROM tw_messages WHERE deleted_ms IS NULL ORDER BY created_ms DESC, rowid DESC").all();
@@ -176869,17 +176869,17 @@ function sectionTasks(call4) {
176869
176869
  function addTaskToSection(call4) {
176870
176870
  const section3 = sectionBy(call4), data7 = call4.body, now11 = call4.ctx.clock.nowMs();
176871
176871
  if (data7.task === void 0) throw bad("task: Missing input");
176872
- const task2 = taskBy(call4, String(data7.task)), before = membershipsOf2(call4.ctx, task2.gid).find((membership) => membership.project === section3.project);
176872
+ const task2 = taskBy(call4, String(data7.task)), before2 = membershipsOf2(call4.ctx, task2.gid).find((membership) => membership.project === section3.project);
176873
176873
  placeTask(call4.ctx, task2.gid, section3.project, section3.gid, { before: data7.insert_before === void 0 ? void 0 : String(data7.insert_before), after: data7.insert_after === void 0 ? void 0 : String(data7.insert_after) });
176874
- if (before?.section !== section3.gid) {
176874
+ if (before2?.section !== section3.gid) {
176875
176875
  const project14 = getProject(call4.ctx, section3.project);
176876
176876
  addStory(
176877
176877
  call4.ctx,
176878
176878
  task2.gid,
176879
176879
  call4.me.gid,
176880
176880
  "system",
176881
- before ? "section_changed" : "added_to_project",
176882
- before ? `moved this task from "${getSection(call4.ctx, before.section).name}" to "${section3.name}" in ${project14.name}` : `added to ${project14.name}`,
176881
+ before2 ? "section_changed" : "added_to_project",
176882
+ before2 ? `moved this task from "${getSection(call4.ctx, before2.section).name}" to "${section3.name}" in ${project14.name}` : `added to ${project14.name}`,
176883
176883
  now11
176884
176884
  );
176885
176885
  call4.ctx.store.db.prepare("UPDATE as_tasks SET modified_ms = ? WHERE gid = ?").run(now11, task2.gid);
@@ -178859,8 +178859,8 @@ function regresses(ctx, i, e) {
178859
178859
  const fixed = release(ctx, res.version);
178860
178860
  return !fixed || rel.created_ms >= fixed.created_ms;
178861
178861
  }
178862
- const before = res.after ? release(ctx, res.after) : void 0;
178863
- return !before || rel.created_ms > before.created_ms;
178862
+ const before2 = res.after ? release(ctx, res.after) : void 0;
178863
+ return !before2 || rel.created_ms > before2.created_ms;
178864
178864
  }
178865
178865
  function wake(ctx, i, substatus2, reason2, type, data7, ms2) {
178866
178866
  Object.assign(i, { status: "unresolved", substatus: substatus2, substatus_ms: ms2, resolution: null, ignore: null, inbox: { reason: reason2, ms: ms2 } });
@@ -180560,8 +180560,8 @@ var init_model7 = __esm({
180560
180560
  /** Writes fields to a record, or creates one (`record` null); links stay in step on both sides. */
180561
180561
  write(table6, record32, input5, opts) {
180562
180562
  if (!input5 || typeof input5 !== "object" || Array.isArray(input5)) throw invalidRequest();
180563
- const now11 = this.ctx.clock.nowMs(), before = record32 ? { ...this.cells(record32) } : {};
180564
- const after = opts.replace || !record32 ? {} : { ...before };
180563
+ const now11 = this.ctx.clock.nowMs(), before2 = record32 ? { ...this.cells(record32) } : {};
180564
+ const after = opts.replace || !record32 ? {} : { ...before2 };
180565
180565
  for (const [key5, value6] of Object.entries(input5)) {
180566
180566
  const field6 = this.field(table6.id, key5);
180567
180567
  if (!field6) throw new AirtableError(422, "UNKNOWN_FIELD_NAME", `Unknown field name: "${key5}"`);
@@ -180581,9 +180581,9 @@ var init_model7 = __esm({
180581
180581
  this.#cells.set(row2.id, after);
180582
180582
  } else {
180583
180583
  row2 = record32;
180584
- if (!sameCells(before, after)) this.#save(row2, after, now11);
180584
+ if (!sameCells(before2, after)) this.#save(row2, after, now11);
180585
180585
  }
180586
- for (const field6 of this.fields(table6.id)) if (field6.type === "multipleRecordLinks") this.#syncInverse(field6, row2.id, before[field6.id] ?? [], after[field6.id] ?? [], now11);
180586
+ for (const field6 of this.fields(table6.id)) if (field6.type === "multipleRecordLinks") this.#syncInverse(field6, row2.id, before2[field6.id] ?? [], after[field6.id] ?? [], now11);
180587
180587
  return row2;
180588
180588
  }
180589
180589
  #save(record32, cells, now11) {
@@ -180592,7 +180592,7 @@ var init_model7 = __esm({
180592
180592
  this.#cells.set(record32.id, cells);
180593
180593
  this.ctx.store.db.prepare("UPDATE at_records SET cells = ?, modified_ms = ? WHERE id = ?").run(record32.cells, now11, record32.id);
180594
180594
  }
180595
- #syncInverse(field6, recordId, before, after, now11) {
180595
+ #syncInverse(field6, recordId, before2, after, now11) {
180596
180596
  const options5 = this.options(field6), inverse2 = options5.inverseLinkFieldId;
180597
180597
  if (!inverse2) return;
180598
180598
  const edit = (otherId, change4) => {
@@ -180603,8 +180603,8 @@ var init_model7 = __esm({
180603
180603
  else delete cells[inverse2];
180604
180604
  if (!sameCells(this.cells(other), cells)) this.#save(other, cells, now11);
180605
180605
  };
180606
- for (const id15 of before) if (!after.includes(id15)) edit(id15, (list19) => list19.filter((item2) => item2 !== recordId));
180607
- for (const id15 of after) if (!before.includes(id15)) edit(id15, (list19) => list19.includes(recordId) ? list19 : [...list19, recordId]);
180606
+ for (const id15 of before2) if (!after.includes(id15)) edit(id15, (list19) => list19.filter((item2) => item2 !== recordId));
180607
+ for (const id15 of after) if (!before2.includes(id15)) edit(id15, (list19) => list19.includes(recordId) ? list19 : [...list19, recordId]);
180608
180608
  }
180609
180609
  /** Marks a record deleted and takes it out of every link to it. */
180610
180610
  delete(table6, record32) {
@@ -183294,7 +183294,7 @@ function auditValues(ctx, type, id15) {
183294
183294
  return spec ? spec.write && spec.kind !== "sublist" && spec.kind !== "address" : /^cust/.test(key5);
183295
183295
  }).map(([key5, value6]) => [key5, valueText(value6)]));
183296
183296
  }
183297
- function auditChange(ctx, type, id15, before, operation, seed44) {
183297
+ function auditChange(ctx, type, id15, before2, operation, seed44) {
183298
183298
  const db3 = sql2(ctx), owner6 = AUDIT_OWNER + type;
183299
183299
  const stored = db3.prepare("SELECT fields FROM ns_extra WHERE owner=? AND id=?").get(owner6, id15);
183300
183300
  const audit2 = stored ? JSON.parse(stored.fields) : { notes: [] };
@@ -183322,8 +183322,8 @@ function auditChange(ctx, type, id15, before, operation, seed44) {
183322
183322
  append(isTx(type) ? "TRANDOC.NKEY" : "id", null, String(id15), 1);
183323
183323
  if (after.approvalStatus !== void 0 && after.approvalStatus !== null) append(fieldId(type, "approvalStatus"), null, after.approvalStatus, 4, seed44 ? null : name5);
183324
183324
  } else if (operation === "delete") append(isTx(type) ? "TRANDOC.NKEY" : "id", String(id15), null, 3);
183325
- else for (const key5 of /* @__PURE__ */ new Set([...Object.keys(before ?? {}), ...Object.keys(after)])) {
183326
- const oldvalue = before?.[key5] ?? null, newvalue = after[key5] ?? null;
183325
+ else for (const key5 of /* @__PURE__ */ new Set([...Object.keys(before2 ?? {}), ...Object.keys(after)])) {
183326
+ const oldvalue = before2?.[key5] ?? null, newvalue = after[key5] ?? null;
183327
183327
  if (oldvalue !== newvalue) append(fieldId(type, key5), oldvalue, newvalue, oldvalue === null ? 4 : newvalue === null ? 5 : 2);
183328
183328
  }
183329
183329
  db3.prepare("INSERT INTO ns_extra(owner,id,fields) VALUES (?,?,?) ON CONFLICT(owner,id) DO UPDATE SET fields=excluded.fields").run(owner6, id15, JSON.stringify(audit2));
@@ -183928,8 +183928,8 @@ function mergeExtra(prior, values3, custom3, creating, opts, path9 = "") {
183928
183928
  for (const f2 of custom3) if (f2.mandatory && creating && (out[f2.id] === void 0 || out[f2.id] === "")) throw missing7(f2.label, `${path9}${f2.id}`);
183929
183929
  return JSON.stringify(out);
183930
183930
  }
183931
- function history4(ctx, type, id15, operation, before) {
183932
- auditChange(ctx, type, id15, before, operation);
183931
+ function history4(ctx, type, id15, operation, before2) {
183932
+ auditChange(ctx, type, id15, before2, operation);
183933
183933
  sql2(ctx).prepare("INSERT INTO ns_history (recordtype, id, operation, at) VALUES (?, ?, ?, ?)").run(type, id15, operation, stamp7(ctx));
183934
183934
  }
183935
183935
  function postable(ctx, account9, path9, types) {
@@ -187338,7 +187338,7 @@ function installFunctions(db3, hierarchy) {
187338
187338
  return i < 0 ? c : target6[i] ?? "";
187339
187339
  }).join(""));
187340
187340
  });
187341
- strict2("initcap", (v) => textOrNull(str3(v).toLowerCase().replace(new RegExp("(^|[^\\p{L}\\p{N}])(\\p{L})", "gu"), (_, before, letter2) => before + letter2.toUpperCase())));
187341
+ strict2("initcap", (v) => textOrNull(str3(v).toLowerCase().replace(new RegExp("(^|[^\\p{L}\\p{N}])(\\p{L})", "gu"), (_, before2, letter2) => before2 + letter2.toUpperCase())));
187342
187342
  strict2("ascii", (v) => str3(v).codePointAt(0) ?? null);
187343
187343
  strict2("chr", (n2) => {
187344
187344
  const code5 = num3(n2);
@@ -189778,13 +189778,13 @@ function openOrders(side) {
189778
189778
  function register2(side) {
189779
189779
  return (ctx, p2) => {
189780
189780
  const type = side === "ar" ? "AcctRec" : "AcctPay", sign4 = side === "ar" ? 1 : -1, rows35 = [];
189781
- const before = balances2(ctx, { to: addDays2(p2.from, -1), subsidiary: p2.subsidiary });
189781
+ const before2 = balances2(ctx, { to: addDays2(p2.from, -1), subsidiary: p2.subsidiary });
189782
189782
  const lines2 = sql2(ctx).prepare(`SELECT g.account, g.entity, g.memo, g.debit, g.credit, t.trandate, t.tranid, t.type FROM ns_gl g
189783
189783
  JOIN ns_transactions t ON t.id=g."transaction" JOIN ns_accounts a ON a.id=g.account
189784
189784
  WHERE a.accttype=? AND t.trandate>=? AND t.trandate<=? AND (? IS NULL OR t.subsidiary=?) ORDER BY t.trandate,t.id,g.id`).all(type, p2.from, p2.to, p2.subsidiary ?? null, p2.subsidiary ?? null);
189785
189785
  for (const a of accounts(ctx).filter((a2) => a2.accttype === type)) {
189786
189786
  const mine = lines2.filter((l) => l.account === a.id);
189787
- let balance4 = (before.get(a.id) ?? 0) * sign4;
189787
+ let balance4 = (before2.get(a.id) ?? 0) * sign4;
189788
189788
  rows35.push(section(accountName(a), 0, 7), detail2(1, ["Beginning Balance", null, null, null, null, null, round(balance4)]));
189789
189789
  for (const l of mine) {
189790
189790
  const amount6 = round(((l.debit ?? 0) - (l.credit ?? 0)) * sign4);
@@ -191433,14 +191433,14 @@ function seededRecord(ctx, type, id15) {
191433
191433
  }
191434
191434
  function preserved(ctx, args) {
191435
191435
  const expected = `${args.type} ${args.id} retains its seed fields except ${args.except_fields.join(", ") || "(none)"}`;
191436
- const before = seededRecord(ctx, args.type, args.id);
191437
- if (before === void 0) return checkOutcome(false, expected, "record absent from seed");
191436
+ const before2 = seededRecord(ctx, args.type, args.id);
191437
+ if (before2 === void 0) return checkOutcome(false, expected, "record absent from seed");
191438
191438
  const after = preservedRecord(ctx, args.type, args.id);
191439
191439
  if (after === void 0) return checkOutcome(false, expected, "record: present -> absent");
191440
191440
  const ignored = new Set(args.except_fields);
191441
191441
  const show2 = (record32, key5) => Object.hasOwn(record32, key5) ? JSON.stringify(record32[key5]) : "(absent)";
191442
- const changed = [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].sort().filter((key5) => !ignored.has(key5) && (Object.hasOwn(before, key5) !== Object.hasOwn(after, key5) || !isDeepStrictEqual3(before[key5], after[key5])));
191443
- return checkOutcome(changed.length === 0, expected, changed.length ? changed.map((key5) => `${key5}: ${show2(before, key5)} -> ${show2(after, key5)}`).join("; ") : "all protected fields equal their seed state");
191442
+ const changed = [.../* @__PURE__ */ new Set([...Object.keys(before2), ...Object.keys(after)])].sort().filter((key5) => !ignored.has(key5) && (Object.hasOwn(before2, key5) !== Object.hasOwn(after, key5) || !isDeepStrictEqual3(before2[key5], after[key5])));
191443
+ return checkOutcome(changed.length === 0, expected, changed.length ? changed.map((key5) => `${key5}: ${show2(before2, key5)} -> ${show2(after, key5)}`).join("; ") : "all protected fields equal their seed state");
191444
191444
  }
191445
191445
  var BASELINE_KEY;
191446
191446
  var init_checks19 = __esm({
@@ -192578,8 +192578,8 @@ function readPostings(ctx, filter4 = {}) {
192578
192578
  function readChanges(ctx, sinceSeq = 0) {
192579
192579
  return ctx.store.db.prepare("SELECT * FROM qbo_changes WHERE seq>? ORDER BY seq").all(sinceSeq).map((r2) => ({ seq: r2.seq, entity: r2.entity, Id: r2.id, operation: r2.operation, time: r2.time, before: r2.before_json ? JSON.parse(r2.before_json) : null, after: r2.after_json ? JSON.parse(r2.after_json) : null }));
192580
192580
  }
192581
- function change3(ctx, entity5, id15, operation, before, after) {
192582
- ctx.store.db.prepare("INSERT INTO qbo_changes(entity,id,operation,time,before_json,after_json) VALUES (?,?,?,?,?,?)").run(entity5, id15, operation, companyTime(ctx), before ? JSON.stringify(before) : null, after ? JSON.stringify(after) : null);
192581
+ function change3(ctx, entity5, id15, operation, before2, after) {
192582
+ ctx.store.db.prepare("INSERT INTO qbo_changes(entity,id,operation,time,before_json,after_json) VALUES (?,?,?,?,?,?)").run(entity5, id15, operation, companyTime(ctx), before2 ? JSON.stringify(before2) : null, after ? JSON.stringify(after) : null);
192583
192583
  }
192584
192584
  function sent(ctx) {
192585
192585
  return ctx.store.db.prepare('SELECT seq,entity AS type,id,recipient AS "to",doc_number,time FROM qbo_sent ORDER BY seq').all();
@@ -192767,16 +192767,16 @@ function normalizeAmounts(ctx, type, row2) {
192767
192767
  if (row2.TotalAmt !== void 0) row2.TotalAmt = money20(cents7(row2.TotalAmt));
192768
192768
  if (row2.Amount !== void 0) row2.Amount = money20(cents7(row2.Amount));
192769
192769
  }
192770
- function rebuild(ctx, primary3, before, seed44 = false) {
192770
+ function rebuild(ctx, primary3, before2, seed44 = false) {
192771
192771
  const at6 = {};
192772
192772
  try {
192773
- return project11(ctx, primary3, before, seed44, at6);
192773
+ return project11(ctx, primary3, before2, seed44, at6);
192774
192774
  } catch (e) {
192775
192775
  if (seed44 && e instanceof QboError && at6.record) throw new QboError(e.code, `${at6.record.type} ${at6.record.id}: ${e.detail}`, e.element);
192776
192776
  throw e;
192777
192777
  }
192778
192778
  }
192779
- function project11(ctx, primary3, before, seed44, at6) {
192779
+ function project11(ctx, primary3, before2, seed44, at6) {
192780
192780
  const all9 = records4(ctx), byKey = new Map(all9.map((r2) => [`${r2.type}:${r2.id}`, r2])), postings2 = [];
192781
192781
  const output2 = new Map(all9.map((r2) => [`${r2.type}:${r2.id}`, structuredClone(r2.input)]));
192782
192782
  const body8 = (type, id15) => output2.get(`${type}:${id15}`);
@@ -192935,7 +192935,7 @@ function project11(ctx, primary3, before, seed44, at6) {
192935
192935
  for (const r2 of all9) {
192936
192936
  const b = body8(r2.type, r2.id), allowed2 = new Set(quickbooksFields(r2.type).map((f2) => f2[0]));
192937
192937
  for (const key5 of Object.keys(b)) if (!allowed2.has(key5)) delete b[key5];
192938
- const old = before.get(`${r2.type}:${r2.id}`), direct = r2.type === primary3.type && r2.id === primary3.id;
192938
+ const old = before2.get(`${r2.type}:${r2.id}`), direct = r2.type === primary3.type && r2.id === primary3.id;
192939
192939
  const oldComparable = old ? { ...old.body } : void 0;
192940
192940
  if (oldComparable) {
192941
192941
  delete oldComparable.MetaData;
@@ -192958,7 +192958,7 @@ function project11(ctx, primary3, before, seed44, at6) {
192958
192958
  for (const p2 of postings2) ctx.store.db.prepare("INSERT INTO qbo_gl(entity,id,date,account,debit,credit,name_type,name_id) VALUES (?,?,?,?,?,?,?,?)").run(p2.entity, p2.id, p2.date, p2.account, p2.debit, p2.credit, p2.nameType ?? null, p2.nameId ?? null);
192959
192959
  const deleted = find7(ctx, primary3.type, primary3.id, true);
192960
192960
  if (deleted.deleted) {
192961
- const old = before.get(`${primary3.type}:${primary3.id}`);
192961
+ const old = before2.get(`${primary3.type}:${primary3.id}`);
192962
192962
  deleted.body = { Id: deleted.id, SyncToken: String(Number(old.body.SyncToken) + 1), status: "Deleted", MetaData: { ...old.body.MetaData, LastUpdatedTime: companyTime(ctx) } };
192963
192963
  save13(ctx, deleted);
192964
192964
  if (!seed44) change3(ctx, deleted.type, deleted.id, "delete", old.body, deleted.body);
@@ -193216,7 +193216,7 @@ function writeEntity(ctx, type, request2, options5 = {}) {
193216
193216
  if (["delete", "void"].includes(operation) && !isTransaction(type) && !["TimeActivity", "Attachable"].includes(type)) fault(500, `${type} records use Active to change availability.`);
193217
193217
  if (operation === "void" && !["Invoice", "Payment", "SalesReceipt", "BillPayment"].includes(type)) gap7(`Void ${type}.`);
193218
193218
  if (old && ["Payment", "SalesReceipt"].includes(type) && ["delete", "void", "update"].includes(operation) && records4(ctx, "Deposit").some((d) => (d.input.Line ?? []).some((l) => (l.LinkedTxn ?? []).some((v) => ["Payment", "ReceivePayment", "SalesReceipt"].includes(v.TxnType) && v.TxnId === old.id)))) fault(6e3, `${type} ${old.id} belongs to a Deposit.`, "Id");
193219
- const before = seed44 ? /* @__PURE__ */ new Map() : new Map(records4(ctx, void 0, true).map((r2) => [`${r2.type}:${r2.id}`, r2]));
193219
+ const before2 = seed44 ? /* @__PURE__ */ new Map() : new Map(records4(ctx, void 0, true).map((r2) => [`${r2.type}:${r2.id}`, r2]));
193220
193220
  const id15 = old?.id ?? nextId7(ctx, type, options5.explicitId);
193221
193221
  if (!old && find7(ctx, type, id15, true)) fault(6e3, `${type} ${id15} already exists.`, "Id");
193222
193222
  if (operation === "delete" || operation === "void") {
@@ -193272,7 +193272,7 @@ function writeEntity(ctx, type, request2, options5 = {}) {
193272
193272
  }
193273
193273
  save13(ctx, other);
193274
193274
  }
193275
- return rebuild(ctx, { type, id: id15, operation }, before, seed44);
193275
+ return rebuild(ctx, { type, id: id15, operation }, before2, seed44);
193276
193276
  }
193277
193277
  const row2 = old && request2.sparse ? structuredClone(old.input) : {};
193278
193278
  for (const [key5, value6] of Object.entries(request2)) {
@@ -193346,7 +193346,7 @@ function writeEntity(ctx, type, request2, options5 = {}) {
193346
193346
  }
193347
193347
  save13(ctx, stored);
193348
193348
  projectedNames(ctx);
193349
- return rebuild(ctx, { type, id: id15, operation }, before, seed44);
193349
+ return rebuild(ctx, { type, id: id15, operation }, before2, seed44);
193350
193350
  });
193351
193351
  }
193352
193352
  function finishSeed(ctx) {
@@ -193364,12 +193364,12 @@ function sendEntity(ctx, type, id15, recipient2) {
193364
193364
  const to = recipient2 || record32.body.BillEmail?.Address;
193365
193365
  if (!to) fault(2020, "Supply sendTo or BillEmail.Address.", "BillEmail");
193366
193366
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(to)) fault(6e3, "sendTo must be an email address.", "sendTo");
193367
- const before = new Map(records4(ctx).map((r2) => [`${r2.type}:${r2.id}`, r2]));
193367
+ const before2 = new Map(records4(ctx).map((r2) => [`${r2.type}:${r2.id}`, r2]));
193368
193368
  record32.input.EmailStatus = "EmailSent";
193369
193369
  record32.input.DeliveryInfo = { DeliveryType: "Email", DeliveryTime: companyTime(ctx) };
193370
193370
  save13(ctx, record32);
193371
193371
  ctx.store.db.prepare("INSERT INTO qbo_sent(entity,id,recipient,doc_number,time) VALUES (?,?,?,?,?)").run(type, id15, to, record32.body.DocNumber ?? null, companyTime(ctx));
193372
- return rebuild(ctx, { type, id: id15, operation: "send" }, before);
193372
+ return rebuild(ctx, { type, id: id15, operation: "send" }, before2);
193373
193373
  });
193374
193374
  }
193375
193375
  var readOnly, companyReadOnly, refTypes, partyType;
@@ -193693,12 +193693,12 @@ function queryRecords(ctx, sql6) {
193693
193693
  if (!confirmed.has(key5) && !["TimeActivity", "Attachable", "TaxAgency", "ExchangeRate"].includes(type)) hasGap = true;
193694
193694
  return key5;
193695
193695
  }
193696
- const typed = (key5, value6) => {
193697
- if (typeof value6 !== "string") return value6;
193696
+ const typed = (key5, value7) => {
193697
+ if (typeof value7 !== "string") return value7;
193698
193698
  const declared = fields13.find((f2) => f2[0] === key5)?.[1];
193699
- if (["decimal", "int", "long", "positiveInteger"].includes(declared ?? "") && /^-?\d+(?:\.\d+)?$/.test(value6)) return Number(value6);
193700
- if (declared === "boolean" && /^(true|false)$/i.test(value6)) return value6.toLowerCase() === "true";
193701
- return value6;
193699
+ if (["decimal", "int", "long", "positiveInteger"].includes(declared ?? "") && /^-?\d+(?:\.\d+)?$/.test(value7)) return Number(value7);
193700
+ if (declared === "boolean" && /^(true|false)$/i.test(value7)) return value7.toLowerCase() === "true";
193701
+ return value7;
193702
193702
  };
193703
193703
  projection2 = projection2?.map((p2) => property4(p2));
193704
193704
  const conditions = [];
@@ -193711,6 +193711,11 @@ function queryRecords(ctx, sql6) {
193711
193711
  if (/^(true|false)$/i.test(t.text)) return t.text.toLowerCase() === "true";
193712
193712
  return parseError2("Expected a quoted string, number or boolean.");
193713
193713
  };
193714
+ const value6 = (key5) => {
193715
+ const token5 = ts3[i], read7 = typed(key5, literal4());
193716
+ if (token5?.kind === "number" && fields13.find((f2) => f2[0] === key5)?.[1] === "string") parseError2(`${key5} is text: give its value in single quotes.`);
193717
+ return read7;
193718
+ };
193714
193719
  if (peek("WHERE")) {
193715
193720
  i++;
193716
193721
  do {
@@ -193719,10 +193724,10 @@ function queryRecords(ctx, sql6) {
193719
193724
  const op2 = ts3[i++]?.text.toUpperCase();
193720
193725
  if (op2 === "IN") {
193721
193726
  take2("(");
193722
- const values3 = [typed(key5, literal4())];
193727
+ const values3 = [value6(key5)];
193723
193728
  while (peek(",")) {
193724
193729
  i++;
193725
- values3.push(typed(key5, literal4()));
193730
+ values3.push(value6(key5));
193726
193731
  }
193727
193732
  take2(")");
193728
193733
  conditions.push((row2) => {
@@ -193735,17 +193740,17 @@ function queryRecords(ctx, sql6) {
193735
193740
  const needle = pattern.replace(/^%/, "").replace(/%$/, "").toLowerCase();
193736
193741
  conditions.push((row2) => {
193737
193742
  const actual = scalar2(row2, key5);
193738
- return (Array.isArray(actual) ? actual : [actual]).some((value6) => {
193739
- const v = String(value6 ?? "").toLowerCase();
193743
+ return (Array.isArray(actual) ? actual : [actual]).some((value7) => {
193744
+ const v = String(value7 ?? "").toLowerCase();
193740
193745
  return pattern.startsWith("%") && pattern.endsWith("%") ? v.includes(needle) : pattern.startsWith("%") ? v.endsWith(needle) : pattern.endsWith("%") ? v.startsWith(needle) : v === needle;
193741
193746
  });
193742
193747
  });
193743
193748
  } else {
193744
193749
  if (!["=", "<", ">", "<=", ">="].includes(op2 ?? "")) parseError2("Expected a comparison, IN or LIKE.");
193745
- const expected = typed(key5, literal4());
193750
+ const expected = value6(key5);
193746
193751
  conditions.push((row2) => {
193747
- const value6 = scalar2(row2, key5);
193748
- return (Array.isArray(value6) ? value6 : [value6]).some((item2) => {
193752
+ const value7 = scalar2(row2, key5);
193753
+ return (Array.isArray(value7) ? value7 : [value7]).some((item2) => {
193749
193754
  let actual = item2, target6 = expected;
193750
193755
  if (actual === void 0) return false;
193751
193756
  if (key5.startsWith("MetaData.")) {
@@ -199558,6 +199563,7 @@ var init_sessions = __esm({
199558
199563
  });
199559
199564
  }
199560
199565
  authenticate(token5, allowFinished = false) {
199566
+ if (!token5) throw new AnchaError("SESSION_UNAUTHORIZED", "invalid session capability", { hint: "send Authorization: Bearer $ANCHA_TRIAL_TOKEN" });
199561
199567
  const env2 = token5 ? this.#manager.list().find((env3) => this.#records.get(env3)?.session.token === token5) : void 0;
199562
199568
  const record32 = env2 ? this.#records.get(env2) : void 0;
199563
199569
  if (!env2 || !record32 || record32.signal !== env2.signal) throw new AnchaError("SESSION_UNAUTHORIZED", "invalid session capability");
@@ -200077,7 +200083,7 @@ function inspectionRoutes(opts) {
200077
200083
  }
200078
200084
  const target6 = info2.services[service];
200079
200085
  if (!target6) return bad4(`sandbox does not contain ${service}`);
200080
- const before = env2.trace.list().at(-1)?.seq ?? 0;
200086
+ const before2 = env2.trace.list().at(-1)?.seq ?? 0;
200081
200087
  revisions.set(env2, revision2 + 1);
200082
200088
  const response6 = await fetch(target6.url.replace(/\/$/, "") + path9, { method: method2, signal: AbortSignal.timeout(1e4), headers: {
200083
200089
  "content-type": "application/json",
@@ -200091,7 +200097,7 @@ function inspectionRoutes(opts) {
200091
200097
  method: "ACTION",
200092
200098
  path: "console.manual_action",
200093
200099
  request: { kind: action.kind },
200094
- response: { sequences: env2.trace.list(before).filter((e) => e.source === "agent").map((e) => e.seq) },
200100
+ response: { sequences: env2.trace.list(before2).filter((e) => e.source === "agent").map((e) => e.seq) },
200095
200101
  note: "Manual action in exploration; not an agent evaluation"
200096
200102
  });
200097
200103
  revisions.set(env2, revision2 + 1);
@@ -204594,9 +204600,9 @@ var require_parse2 = __commonJS({
204594
204600
  continue;
204595
204601
  }
204596
204602
  const prior = prev.prev;
204597
- const before = prior.prev;
204603
+ const before2 = prior.prev;
204598
204604
  const isStart = prior.type === "slash" || prior.type === "bos";
204599
- const afterStar = before && (before.type === "star" || before.type === "globstar");
204605
+ const afterStar = before2 && (before2.type === "star" || before2.type === "globstar");
204600
204606
  if (opts.bash === true && (!isStart || rest2[0] && rest2[0] !== "/")) {
204601
204607
  push({ type: "star", value: value6, output: "" });
204602
204608
  continue;
@@ -230546,18 +230552,18 @@ function* schedules(scene2, capture4, state3) {
230546
230552
  };
230547
230553
  for (const id15 of targets) {
230548
230554
  const after = current.find((row2) => row2.id === id15);
230549
- const before = seed44.schedules?.find((row2) => row2.id === id15 || after?.ref !== void 0 && row2.ref === after.ref);
230550
- if (!before && !after) continue;
230555
+ const before2 = seed44.schedules?.find((row2) => row2.id === id15 || after?.ref !== void 0 && row2.ref === after.ref);
230556
+ if (!before2 && !after) continue;
230551
230557
  yield {
230552
230558
  service: "pagerduty",
230553
230559
  kind: "schedule",
230554
230560
  id: id15,
230555
230561
  // The schedule twin seeds no overrides. Entries are the base layer, not the effective on-call schedule.
230556
- before: before ? {
230562
+ before: before2 ? {
230557
230563
  id: id15,
230558
- ref: before.ref,
230559
- name: before.name,
230560
- base_entries: before.entries.map((entry3) => ({ user: userBefore(entry3.user), start: iso24(entry3.start), end: iso24(entry3.end) })),
230564
+ ref: before2.ref,
230565
+ name: before2.name,
230566
+ base_entries: before2.entries.map((entry3) => ({ user: userBefore(entry3.user), start: iso24(entry3.start), end: iso24(entry3.end) })),
230561
230567
  overrides: []
230562
230568
  } : null,
230563
230569
  after: after ? {
@@ -230582,7 +230588,7 @@ function* driveFiles(scene2, capture4, state3) {
230582
230588
  }
230583
230589
  const fields13 = ["id", "name", "mimeType", "owner"];
230584
230590
  const permissionFields = ["type", "role", "emailAddress", "domain", "allowFileDiscovery"];
230585
- const before = (id15) => {
230591
+ const before2 = (id15) => {
230586
230592
  const file3 = beforeById.get(id15);
230587
230593
  if (!file3) return null;
230588
230594
  let trashed = file3.trashed, parent3 = file3.parent;
@@ -230623,7 +230629,7 @@ function* driveFiles(scene2, capture4, state3) {
230623
230629
  const id15 = pending[i];
230624
230630
  if (seen.has(id15)) continue;
230625
230631
  seen.add(id15);
230626
- const initial = before(id15), final = after(id15);
230632
+ const initial = before2(id15), final = after(id15);
230627
230633
  if (!initial && !final) continue;
230628
230634
  yield { service: "google-drive", kind: "file", id: id15, selected_by: targets.has(id15) ? "write" : "parent", before: initial, after: final };
230629
230635
  for (const parent3 of [beforeById.get(id15)?.parent, afterById.get(id15)?.parent]) if (typeof parent3 === "string" && !seen.has(parent3)) pending.push(parent3);
@@ -231337,7 +231343,7 @@ var init_jobs_contract = __esm({
231337
231343
  CLOUD_MODEL_HOSTS = ["openrouter.ai", "api.openai.com", "api.anthropic.com", "generativelanguage.googleapis.com", "api.groq.com", "api.mistral.ai", "api.together.xyz", "api.fireworks.ai", "api.deepseek.com", "api.x.ai", "api.cohere.com"];
231338
231344
  DEFAULT_MODEL_HOSTS = ["openrouter.ai", "api.openai.com", "api.anthropic.com"];
231339
231345
  MODEL_KEY_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "GOOGLE_API_KEY", "OPENROUTER_API_KEY", "AZURE_OPENAI_API_KEY", "MISTRAL_API_KEY", "GROQ_API_KEY", "DEEPSEEK_API_KEY", "XAI_API_KEY", "COHERE_API_KEY", "TOGETHER_API_KEY", "FIREWORKS_API_KEY"];
231340
- PROBE_OUTCOMES = ["answered", "refused", "outside_host", "unserved", "crashed", "idle", "no_answer", "wrong_answer", "model_key", "missing_secret", "route_key"];
231346
+ PROBE_OUTCOMES = ["answered", "answer_refused", "refused", "outside_host", "unserved", "crashed", "idle", "no_answer", "wrong_answer", "model_key", "missing_secret", "route_key"];
231341
231347
  ANSWER_SOURCES = ["done", "reply", "stdout"];
231342
231348
  HEARTBEAT_MS = 1e4;
231343
231349
  AGENT_UID = 10001;
@@ -231904,10 +231910,10 @@ async function startIsolationGateway(options5) {
231904
231910
  roots.set(root3, upstream);
231905
231911
  }
231906
231912
  const sessionRoutes2 = /* @__PURE__ */ new Map();
231907
- if (session2) for (const [field6, path9, method2] of [["eventsUrl", "/_ancha/events", "GET"], ["contextUrl", "/_ancha/context", "GET"], ["doneUrl", "/_ancha/done", "POST"]]) {
231913
+ if (session2) for (const [field6, path9, method2, name5] of [["eventsUrl", "/_ancha/events", "GET", "ANCHA_EVENTS_URL"], ["contextUrl", "/_ancha/context", "GET", "ANCHA_CONTEXT_URL"], ["doneUrl", "/_ancha/done", "POST", "ANCHA_DONE_URL"]]) {
231908
231914
  const upstream = loopbackOrigin(session2[field6]);
231909
231915
  if (upstream.pathname !== path9 || upstream.search || upstream.hash) throw new Error("Invalid trial session route");
231910
- sessionRoutes2.set(path9, { method: method2, upstream });
231916
+ sessionRoutes2.set(path9, { name: name5, method: method2, upstream });
231911
231917
  }
231912
231918
  const socketGrants = /* @__PURE__ */ new Map();
231913
231919
  const modelHosts = new Set((options5.modelHosts ?? []).map(normalizeModelHost));
@@ -232071,7 +232077,15 @@ async function startIsolationGateway(options5) {
232071
232077
  }
232072
232078
  if (!upstream) {
232073
232079
  const route16 = sessionRoutes2.get(path9);
232074
- if (!route16 || req.method !== route16.method || req.headers.authorization !== `Bearer ${session2.token}`) return reject3(res);
232080
+ if (!route16) return reject3(res);
232081
+ const status6 = req.method !== route16.method ? 405 : req.headers.authorization !== `Bearer ${session2.token}` ? 401 : void 0;
232082
+ if (status6 !== void 0) {
232083
+ try {
232084
+ options5.onSessionRefused?.(route16.name, status6);
232085
+ } catch {
232086
+ }
232087
+ return reject3(res, status6, status6 === 405 ? `${route16.name} takes ${route16.method}.` : `${route16.name} takes Authorization: Bearer $ANCHA_TRIAL_TOKEN.`);
232088
+ }
232075
232089
  upstream = route16.upstream;
232076
232090
  if (path9 === "/_ancha/context") transform3 = "context";
232077
232091
  }
@@ -233605,7 +233619,7 @@ function withoutScriptBanners(lines2) {
233605
233619
  function stdoutAnswer(stdout) {
233606
233620
  return withoutScriptBanners(stdout.replace(ANSI, "").replace(/\r\n?/g, "\n").trimEnd().split("\n")).join("\n").trimEnd();
233607
233621
  }
233608
- var ANSWER_MAX_CHARS, STDOUT_MAX_CHARS, OutputTail, ModelReplies, ANSI, NPM_SCRIPT, NPM_COMMAND, YARN_RUN, YARN_COMMAND, YARN_DONE;
233622
+ var ANSWER_MAX_CHARS, STDOUT_MAX_CHARS, OutputTail, ModelReplies, SessionRefusals, ANSI, NPM_SCRIPT, NPM_COMMAND, YARN_RUN, YARN_COMMAND, YARN_DONE;
233609
233623
  var init_agent_output = __esm({
233610
233624
  "backend/src/runner/agent-output.ts"() {
233611
233625
  "use strict";
@@ -233660,6 +233674,17 @@ var init_agent_output = __esm({
233660
233674
  return this.#last !== void 0 && MODEL_REFUSALS.has(this.#last.status) ? { ...this.#last } : void 0;
233661
233675
  }
233662
233676
  };
233677
+ SessionRefusals = class {
233678
+ #counts = /* @__PURE__ */ new Map();
233679
+ add(name5, status6) {
233680
+ const key5 = `${name5} ${status6}`, refusal4 = this.#counts.get(key5);
233681
+ if (refusal4) refusal4.count++;
233682
+ else this.#counts.set(key5, { name: name5, status: status6, count: 1 });
233683
+ }
233684
+ list() {
233685
+ return [...this.#counts.values()].map((refusal4) => ({ ...refusal4 }));
233686
+ }
233687
+ };
233663
233688
  ANSI = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
233664
233689
  NPM_SCRIPT = /^> (?:\S+@\S* )?[\w:.-]+(?: \/\S*)?$/;
233665
233690
  NPM_COMMAND = /^> \S/;
@@ -234444,8 +234469,8 @@ async function startContainedAgent(command, opts) {
234444
234469
  "exec sleep 86400"
234445
234470
  ]);
234446
234471
  await run7(["start", relayName]);
234447
- const replies = new ModelReplies();
234448
- gateway2 = await startIsolationGateway({ env: opts.env, session: opts.session, modelHosts: policy.modelHosts, ...opts.onModelActivity && { onModelActivity: opts.onModelActivity }, onModelReply: (host, status7, message8) => replies.add(host, status7, message8) });
234472
+ const replies = new ModelReplies(), refusals = new SessionRefusals();
234473
+ gateway2 = await startIsolationGateway({ env: opts.env, session: opts.session, modelHosts: policy.modelHosts, ...opts.onModelActivity && { onModelActivity: opts.onModelActivity }, onModelReply: (host, status7, message8) => replies.add(host, status7, message8), onSessionRefused: (name5, status7) => refusals.add(name5, status7) });
234449
234474
  const script2 = isolationRelayScript({ port: RELAY_PORT, ...opts.runtime?.port && { agentPort: opts.runtime.port } });
234450
234475
  relayChild = spawn2("docker", ["--context", context3, "exec", "-i", relayName, "node", "-e", script2], { env: dockerEnvironment(), stdio: ["pipe", "pipe", "pipe"] });
234451
234476
  relayChild.stderr.on("data", () => {
@@ -234537,7 +234562,7 @@ async function startContainedAgent(command, opts) {
234537
234562
  return { pid: child3.pid, exited, async stop() {
234538
234563
  await cleanup();
234539
234564
  await exited;
234540
- }, output: () => ({ stdout: tail.text(), printed: tail.length(), modelReplies: replies.list(), modelRefusal: replies.refusal() }) };
234565
+ }, output: () => ({ stdout: tail.text(), printed: tail.length(), modelReplies: replies.list(), sessionRefusals: refusals.list(), modelRefusal: replies.refusal() }) };
234541
234566
  } catch (error65) {
234542
234567
  opts.signal?.removeEventListener("abort", abort);
234543
234568
  await cleanup();
@@ -234766,7 +234791,7 @@ async function startVmAgent(command, opts, deps = {}) {
234766
234791
  await chmod3(taskFile, 292);
234767
234792
  await chmod3(directory, 457);
234768
234793
  }
234769
- const replies = new ModelReplies();
234794
+ const replies = new ModelReplies(), refusals = new SessionRefusals();
234770
234795
  gateway2 = await (deps.gateway ?? startIsolationGateway)({
234771
234796
  ...composio && { composio },
234772
234797
  env: opts.env,
@@ -234775,7 +234800,8 @@ async function startVmAgent(command, opts, deps = {}) {
234775
234800
  port: unsafe ? 0 : 18991,
234776
234801
  slackSocket: opts.agent.slackTransport === "socket",
234777
234802
  ...opts.onModelActivity && { onModelActivity: opts.onModelActivity },
234778
- onModelReply: (host, status6, message8) => replies.add(host, status6, message8)
234803
+ onModelReply: (host, status6, message8) => replies.add(host, status6, message8),
234804
+ onSessionRefused: (name5, status6) => refusals.add(name5, status6)
234779
234805
  });
234780
234806
  const mapped = gateway2.rewrite(unsafe ? gateway2.url : VM_GATEWAY_ORIGIN);
234781
234807
  const agentRuntime = { ...opts.runtime, ...taskFile !== void 0 && { taskFile }, ...opts.runtime?.attempt && { attempt: { ...opts.runtime.attempt, stateDir: paths3.state, records: records6 } } };
@@ -234903,7 +234929,7 @@ async function startVmAgent(command, opts, deps = {}) {
234903
234929
  return { pid: child3.pid, exited, async stop() {
234904
234930
  await cleanup();
234905
234931
  await exited;
234906
- }, output: () => ({ stdout: tail.text(), printed: tail.length(), modelReplies: replies.list(), modelRefusal: replies.refusal() }) };
234932
+ }, output: () => ({ stdout: tail.text(), printed: tail.length(), modelReplies: replies.list(), sessionRefusals: refusals.list(), modelRefusal: replies.refusal() }) };
234907
234933
  } catch (error65) {
234908
234934
  await cleanup();
234909
234935
  throw error65;
@@ -235598,8 +235624,8 @@ function givenByTwins(name5) {
235598
235624
  function taskVariables(text31) {
235599
235625
  const found = [];
235600
235626
  for (const match3 of text31.matchAll(TASK_NAME)) {
235601
- const name5 = match3[1], before = text31.slice(0, match3.index);
235602
- if (name5.startsWith("ANCHA_") || /--?[A-Za-z][\w-]*[ =]$/.test(before)) continue;
235627
+ const name5 = match3[1], before2 = text31.slice(0, match3.index);
235628
+ if (name5.startsWith("ANCHA_") || /--?[A-Za-z][\w-]*[ =]$/.test(before2)) continue;
235603
235629
  const bare = !name5.includes("_");
235604
235630
  const named5 = escape16(name5);
235605
235631
  if (bare && !new RegExp(`(?:\\$\\{?|process\\.env\\.|process\\.env\\[['"]|environ(?:\\.get)?\\(?\\[?['"]|getenv\\(['"]|\\bset\\s+|\\bexport\\s+)${named5}\\b|\\b${named5}\\s+(?:is\\s+)?(?:not\\s+set|unset|empty|missing|required|undefined)|\\b${named5}\\s+(?:env(?:ironment)?\\s+)?variable|variable\\s+${named5}\\b|KeyError:\\s*['"]${named5}['"]`).test(text31)) continue;
@@ -235839,6 +235865,13 @@ function attemptOutcome(view3, ctx) {
235839
235865
  fix: failure6.fix ?? `ancha secrets set ${modelKeyName(model2.host, ctx.given ?? [])}`
235840
235866
  });
235841
235867
  }
235868
+ if (answer === void 0 && view3.sessionRefusals?.some((refusal4) => refusal4.name === "ANCHA_DONE_URL" && refusal4.status === 401)) return out({
235869
+ code: "answer_refused",
235870
+ kind: "fix",
235871
+ level: "fail",
235872
+ message: "Its answer post to ANCHA_DONE_URL was refused: it had no Authorization: Bearer $ANCHA_TRIAL_TOKEN.",
235873
+ fix: "send Authorization: Bearer $ANCHA_TRIAL_TOKEN with the POST to ANCHA_DONE_URL, or print the answer on stdout"
235874
+ });
235842
235875
  const refused2 = (entry3) => entry3.status === 401 || entry3.status === 403;
235843
235876
  const turnedDown = used.length > 0 && used.every(refused2) ? used : data7.length > 0 && data7.every(refused2) ? data7 : [];
235844
235877
  if (turnedDown.length > 0) {
@@ -236112,6 +236145,7 @@ async function runTrialInner(spec) {
236112
236145
  ...playOut !== void 0 && playOut.toMs > playOut.fromMs && { playOut },
236113
236146
  checks: checks2,
236114
236147
  ...output2?.modelReplies?.length && { modelReplies: output2.modelReplies },
236148
+ ...output2?.sessionRefusals?.length && { sessionRefusals: output2.sessionRefusals },
236115
236149
  logTail: exit === "idle" || exit === "done" || exit === "exited" && exitCode === 0 ? [] : await logTail(join16(dir2, "agent.log")),
236116
236150
  // An agent that exits non-zero or dies by a signal on its own fails its trial whatever the checks say, as a per_event
236117
236151
  // invocation does: an agent that crashed before its first call would otherwise pass every not_called check.
@@ -236381,13 +236415,13 @@ function actionCounts(trials) {
236381
236415
  }
236382
236416
  return { of: counted4.length, made: [...made.values()].sort((a, b) => b.trials - a.trials || a.tool.localeCompare(b.tool)) };
236383
236417
  }
236384
- function actionChanges(before, after) {
236385
- if (!before?.of || !after?.of) return [];
236386
- const was = new Map(before.made.map((a) => [keyOf2(a), a])), now11 = new Map(after.made.map((a) => [keyOf2(a), a]));
236418
+ function actionChanges(before2, after) {
236419
+ if (!before2?.of || !after?.of) return [];
236420
+ const was = new Map(before2.made.map((a) => [keyOf2(a), a])), now11 = new Map(after.made.map((a) => [keyOf2(a), a]));
236387
236421
  const share = (c) => c.trials / c.of;
236388
236422
  return [.../* @__PURE__ */ new Set([...was.keys(), ...now11.keys()])].map((key5) => {
236389
236423
  const action = now11.get(key5) ?? was.get(key5);
236390
- return { tool: action.tool, args: action.args, before: { trials: was.get(key5)?.trials ?? 0, of: before.of }, after: { trials: now11.get(key5)?.trials ?? 0, of: after.of } };
236424
+ return { tool: action.tool, args: action.args, before: { trials: was.get(key5)?.trials ?? 0, of: before2.of }, after: { trials: now11.get(key5)?.trials ?? 0, of: after.of } };
236391
236425
  }).filter((c) => c.before.trials * c.after.of !== c.after.trials * c.before.of).sort((a, b) => Math.abs(share(b.after) - share(b.before)) - Math.abs(share(a.after) - share(a.before)) || a.tool.localeCompare(b.tool));
236392
236426
  }
236393
236427
  function actionLabel(action) {
@@ -237841,8 +237875,8 @@ function jsonTaskInputs(text31, source) {
237841
237875
  for (const match3 of text31.matchAll(/\b(?:json\.loads?|JSON\.parse)\s*\(/g)) {
237842
237876
  const call4 = argument(text31, match3.index + match3[0].length);
237843
237877
  if (!call4) continue;
237844
- const before = text31.slice(0, match3.index).split("\n").at(-1);
237845
- const variable = /\b([A-Za-z_]\w*)\s*=\s*$/.exec(before)?.[1];
237878
+ const before2 = text31.slice(0, match3.index).split("\n").at(-1);
237879
+ const variable = /\b([A-Za-z_]\w*)\s*=\s*$/.exec(before2)?.[1];
237846
237880
  const chain = `(?:\\[\\s*['"][\\w-]+['"]\\s*\\]|\\.get\\(\\s*['"][\\w-]+['"]\\s*\\)|\\.(?!get\\b)[A-Za-z_]\\w*)+`;
237847
237881
  const accesses = variable ? [...text31.slice(call4.end).matchAll(new RegExp(`\\b${escape17(variable)}(${chain})`, "g"))] : [];
237848
237882
  const immediate = new RegExp(`^\\s*(${chain})`).exec(text31.slice(call4.end));
@@ -239165,13 +239199,13 @@ async function bundleSecrets(options5) {
239165
239199
  function redact(data7, secrets2) {
239166
239200
  if (secrets2.length === 0) return data7;
239167
239201
  let text31 = data7.toString("utf8");
239168
- const before = text31;
239202
+ const before2 = text31;
239169
239203
  for (const secret of secrets2) {
239170
239204
  text31 = text31.split(secret).join("[redacted]");
239171
239205
  const escaped = JSON.stringify(secret).slice(1, -1);
239172
239206
  if (escaped !== secret) text31 = text31.split(escaped).join("[redacted]");
239173
239207
  }
239174
- return text31 === before ? data7 : Buffer.from(text31, "utf8");
239208
+ return text31 === before2 ? data7 : Buffer.from(text31, "utf8");
239175
239209
  }
239176
239210
  function logTail2(data7, cap) {
239177
239211
  const note2 = (cut5) => Buffer.from(`[ancha: agent.log was ${data7.length} bytes; the first ${cut5} bytes are left out]
@@ -241235,8 +241269,8 @@ function readNetsuite(cx) {
241235
241269
  for (const a of w2.body?.apply?.items ?? []) touch4(`tx:${int3(a?.doc?.id ?? a?.doc)}`, w2.ms);
241236
241270
  }
241237
241271
  for (const w2 of writes3.filter((w3) => ["create", "transform"].includes(w3.op) && !w3.created && w3.ok)) {
241238
- const space2 = spaceOf(w2.type), before = [...recs.values()].filter((r2) => r2.space === space2 && r2.id && r2.obs.some((o) => o.ms < w2.ms)).map((r2) => r2.id);
241239
- for (const r2 of recs.values()) if (r2.space === space2 && r2.id && !r2.obs.some((o) => o.ms < w2.ms) && r2.obs.some((o) => o.fields.type === w2.type || o.fields.kind === w2.type || o.fields.itemType === w2.type || space2 !== "tx") && r2.id > Math.max(0, ...before)) created4.add(r2.key);
241272
+ const space2 = spaceOf(w2.type), before2 = [...recs.values()].filter((r2) => r2.space === space2 && r2.id && r2.obs.some((o) => o.ms < w2.ms)).map((r2) => r2.id);
241273
+ for (const r2 of recs.values()) if (r2.space === space2 && r2.id && !r2.obs.some((o) => o.ms < w2.ms) && r2.obs.some((o) => o.fields.type === w2.type || o.fields.kind === w2.type || o.fields.itemType === w2.type || space2 !== "tx") && r2.id > Math.max(0, ...before2)) created4.add(r2.key);
241240
241274
  }
241241
241275
  const rewritten = /* @__PURE__ */ new Map();
241242
241276
  for (const w2 of writes3) for (const sub2 of ["item", "expense", "line", "apply"]) if (w2.id && w2.body && typeof w2.body === "object" && sub2 in w2.body) {
@@ -242143,12 +242177,12 @@ function proposeNetsuiteChecks(cx, netsuite, { expect, outcomes = [] } = {}) {
242143
242177
  counts2.set(w2.type, c);
242144
242178
  }
242145
242179
  for (const [type, c] of counts2) {
242146
- const before = seededIds(seed44, type).size, done = c.made + c.removed > 0;
242147
- const count13 = before + (done ? c.made - c.removed : Math.sign(c.refusedMade) - Math.sign(c.refusedRemoved));
242180
+ const before2 = seededIds(seed44, type).size, done = c.made + c.removed > 0;
242181
+ const count13 = before2 + (done ? c.made - c.removed : Math.sign(c.refusedMade) - Math.sign(c.refusedRemoved));
242148
242182
  const what = [c.made + c.refusedMade && `created ${done ? c.made : 1}`, c.removed + c.refusedRemoved && `deleted ${done ? c.removed : 1}`].filter(Boolean).join(" and ");
242149
242183
  add(
242150
242184
  { id: `netsuite-${slug16(type)}-count`, state: { "netsuite.count": { type, count: count13 } } },
242151
- `the agent ${what} ${type} ${count13 - before === 1 || before - count13 === 1 ? "record" : "records"}; the test starts with ${before}${done ? "" : "; NetSuite refused it in production"}`,
242185
+ `the agent ${what} ${type} ${count13 - before2 === 1 || before2 - count13 === 1 ? "record" : "records"}; the test starts with ${before2}${done ? "" : "; NetSuite refused it in production"}`,
242152
242186
  done ? "passed" : "failed",
242153
242187
  c.spans
242154
242188
  );
@@ -242491,19 +242525,19 @@ function rebuildQuickbooks(cx) {
242491
242525
  continue;
242492
242526
  }
242493
242527
  const firstWrite = writes3.find((w2) => w2.type === type && w2.id === id15);
242494
- const before = seen.filter((s3) => !firstWrite || s3.order < firstWrite.order);
242495
- const source = before.at(-1) ?? seen.find((s3) => s3.write === firstWrite) ?? first2;
242496
- if (!before.length && firstWrite?.op === "delete") {
242528
+ const before2 = seen.filter((s3) => !firstWrite || s3.order < firstWrite.order);
242529
+ const source = before2.at(-1) ?? seen.find((s3) => s3.write === firstWrite) ?? first2;
242530
+ if (!before2.length && firstWrite?.op === "delete") {
242497
242531
  note2("missing", pathOf6(type, id15), `${type} ${id15} was deleted without an earlier observation`, [firstWrite.span]);
242498
242532
  continue;
242499
242533
  }
242500
242534
  const row2 = structuredClone(source.row);
242501
- if (!before.length && firstWrite) for (const field6 of Object.keys(writable4(type, firstWrite.body))) {
242535
+ if (!before2.length && firstWrite) for (const field6 of Object.keys(writable4(type, firstWrite.body))) {
242502
242536
  delete row2[field6];
242503
242537
  note2("missing", `${pathOf6(type, id15)}.${field6}`, "the first write supplied this field; its earlier value was not observed", [firstWrite.span]);
242504
242538
  }
242505
242539
  sources.set(key5, { ...source, row: row2 });
242506
- const balance4 = before.find((s3) => typeof s3.row.Balance === "number");
242540
+ const balance4 = before2.find((s3) => typeof s3.row.Balance === "number");
242507
242541
  if (balance4) balanceSources.set(key5, balance4);
242508
242542
  note2("observed", pathOf6(type, id15), `${type} ${id15} observed at ${new Date(source.ms).toISOString()}`, [source.span]);
242509
242543
  }
@@ -242842,9 +242876,9 @@ function proposeQuickbooksChecks(cx, built3, { expect, outcomes = [] } = {}) {
242842
242876
  if (["Payment", "BillPayment"].includes(w2.type)) {
242843
242877
  if (w2.op === "update" && w2.body.Line === void 0) continue;
242844
242878
  const previous = paid.get(`${w2.type}:${w2.id ?? `new-${i}`}`);
242845
- const before = previous?.before ?? (projection2[w2.type] ?? []).find((r2) => r2.Id === w2.id)?.Line ?? [];
242879
+ const before2 = previous?.before ?? (projection2[w2.type] ?? []).find((r2) => r2.Id === w2.id)?.Line ?? [];
242846
242880
  const lines2 = ["delete", "void"].includes(w2.op) ? [] : w2.body.Line ?? [];
242847
- paid.set(`${w2.type}:${w2.id ?? `new-${i}`}`, { before, lines: lines2, ok: w2.ok, span: w2.span });
242881
+ paid.set(`${w2.type}:${w2.id ?? `new-${i}`}`, { before: before2, lines: lines2, ok: w2.ok, span: w2.span });
242848
242882
  }
242849
242883
  }
242850
242884
  const balances3 = /* @__PURE__ */ new Map();
@@ -243365,19 +243399,19 @@ function assertComparableSummaries(current, baseline) {
243365
243399
  throw new AnchaError("USAGE", "comparison requires the same complete set of tests", { hint: "save a fresh baseline after intentional test changes" });
243366
243400
  }
243367
243401
  for (const id15 of currentIds) {
243368
- const before = baseline.sceneFingerprints?.[id15], after = current.sceneFingerprints?.[id15];
243369
- if (!before || !after || !/^[a-f0-9]{64}$/.test(before) || !/^[a-f0-9]{64}$/.test(after)) throw new AnchaError("USAGE", `unverified test fingerprint for ${id15}`, { hint: "legacy summaries can be displayed but need a new run before comparison" });
243370
- if (before !== after) throw new AnchaError("USAGE", `test fingerprint changed for ${id15} (test, criteria or records differ)`, { hint: "save a fresh baseline after intentional test changes" });
243402
+ const before2 = baseline.sceneFingerprints?.[id15], after = current.sceneFingerprints?.[id15];
243403
+ if (!before2 || !after || !/^[a-f0-9]{64}$/.test(before2) || !/^[a-f0-9]{64}$/.test(after)) throw new AnchaError("USAGE", `unverified test fingerprint for ${id15}`, { hint: "legacy summaries can be displayed but need a new run before comparison" });
243404
+ if (before2 !== after) throw new AnchaError("USAGE", `test fingerprint changed for ${id15} (test, criteria or records differ)`, { hint: "save a fresh baseline after intentional test changes" });
243371
243405
  }
243372
243406
  for (const id15 of currentIds) {
243373
- const before = baseline.caseFingerprints?.[id15], after = current.caseFingerprints?.[id15];
243374
- if (before === void 0 && after === void 0) continue;
243375
- if (!before || !after || !/^[a-f0-9]{64}$/.test(before) || !/^[a-f0-9]{64}$/.test(after)) throw new AnchaError("USAGE", `unverified case fingerprint for ${id15}`, { hint: "compare runs prepared with the same explicit cases" });
243376
- if (before !== after) throw new AnchaError("USAGE", `case fingerprint changed for ${id15} (data versions, parameters or seed differ)`, { hint: "save a fresh baseline after intentional test input changes" });
243407
+ const before2 = baseline.caseFingerprints?.[id15], after = current.caseFingerprints?.[id15];
243408
+ if (before2 === void 0 && after === void 0) continue;
243409
+ if (!before2 || !after || !/^[a-f0-9]{64}$/.test(before2) || !/^[a-f0-9]{64}$/.test(after)) throw new AnchaError("USAGE", `unverified case fingerprint for ${id15}`, { hint: "compare runs prepared with the same explicit cases" });
243410
+ if (before2 !== after) throw new AnchaError("USAGE", `case fingerprint changed for ${id15} (data versions, parameters or seed differ)`, { hint: "save a fresh baseline after intentional test input changes" });
243377
243411
  }
243378
243412
  }
243379
- function rateChange(before, beforeTotal, after, afterTotal) {
243380
- return { numerator: BigInt(after) * BigInt(beforeTotal) - BigInt(before) * BigInt(afterTotal), denominator: BigInt(afterTotal) * BigInt(beforeTotal) };
243413
+ function rateChange(before2, beforeTotal, after, afterTotal) {
243414
+ return { numerator: BigInt(after) * BigInt(beforeTotal) - BigInt(before2) * BigInt(afterTotal), denominator: BigInt(afterTotal) * BigInt(beforeTotal) };
243381
243415
  }
243382
243416
  function compareSummaries(current, baseline) {
243383
243417
  assertComparableSummaries(current, baseline);
@@ -243396,12 +243430,12 @@ function compareSummaries(current, baseline) {
243396
243430
  if (numerator < 0n) regressed = true;
243397
243431
  const checks2 = [];
243398
243432
  for (const [check4, after] of Object.entries(scene2.checks)) {
243399
- const before = beforeScene.checks[check4];
243400
- const beforeGraded = before === void 0 ? 0 : before.total - (before.skipped ?? 0), afterGraded = after.total - (after.skipped ?? 0);
243401
- if (before === void 0 || beforeGraded <= 0 || afterGraded <= 0) continue;
243402
- const change4 = rateChange(before.passed, beforeGraded, after.passed, afterGraded);
243433
+ const before2 = beforeScene.checks[check4];
243434
+ const beforeGraded = before2 === void 0 ? 0 : before2.total - (before2.skipped ?? 0), afterGraded = after.total - (after.skipped ?? 0);
243435
+ if (before2 === void 0 || beforeGraded <= 0 || afterGraded <= 0) continue;
243436
+ const change4 = rateChange(before2.passed, beforeGraded, after.passed, afterGraded);
243403
243437
  if (change4.numerator === 0n) continue;
243404
- const delta2 = { sceneId: scene2.sceneId, check: check4, required: after.required, before: { passed: before.passed, total: beforeGraded }, after: { passed: after.passed, total: afterGraded }, delta: Number(change4.numerator) / Number(change4.denominator) };
243438
+ const delta2 = { sceneId: scene2.sceneId, check: check4, required: after.required, before: { passed: before2.passed, total: beforeGraded }, after: { passed: after.passed, total: afterGraded }, delta: Number(change4.numerator) / Number(change4.denominator) };
243405
243439
  checks2.push(delta2);
243406
243440
  if (change4.numerator < 0n && after.required) {
243407
243441
  regressed = true;
@@ -243820,7 +243854,7 @@ async function runWithTask(descriptor3, agent, run7) {
243820
243854
  const own2 = netsuiteMappings(scan2?.variables ?? []).filter((mapping) => !Object.hasOwn(agent.env, mapping.name));
243821
243855
  const suggestedJson = plainTextTaskParseError(tail) ? jsonTaskWiring(scan2, command) : void 0;
243822
243856
  const jsonMapping = suggestedJson && suggestedJson.length <= 430 ? suggestedJson : void 0;
243823
- const outcome4 = attemptOutcome({ exit: trial.exit, exitCode: trial.exitCode, realMs: trial.realMs, trace: trial.trace, log: text31, logTail: tail, modelReplies: trial.modelReplies }, {
243857
+ const outcome4 = attemptOutcome({ exit: trial.exit, exitCode: trial.exitCode, realMs: trial.realMs, trace: trial.trace, log: text31, logTail: tail, modelReplies: trial.modelReplies, sessionRefusals: trial.sessionRefusals }, {
243824
243858
  check: netsuite ? "netsuite" : "start",
243825
243859
  answerChecked: false,
243826
243860
  stdin: agent.taskInput?.kind === "stdin" ? null : scan2?.stdin,
@@ -245405,15 +245439,15 @@ function readPagerDuty(cx) {
245405
245439
  for (const s3 of schedules2.values()) {
245406
245440
  const mine = overrides.filter((o) => o.schedule === s3.id);
245407
245441
  const first2 = Math.min(...mine.map((o) => o.ms));
245408
- const before = s3.read.filter((e) => e.ms < first2), after = s3.read.filter((e) => e.ms >= first2).flatMap((e) => mine.filter((o) => o.ms <= e.ms).reduce((pieces, o) => pieces.flatMap((p2) => cut4(p2, o)), [e]));
245409
- const entries4 = [...before];
245410
- for (const e of after) entries4.push(...before.reduce((pieces, b) => pieces.flatMap((p2) => cut4(p2, b)), [e]));
245442
+ const before2 = s3.read.filter((e) => e.ms < first2), after = s3.read.filter((e) => e.ms >= first2).flatMap((e) => mine.filter((o) => o.ms <= e.ms).reduce((pieces, o) => pieces.flatMap((p2) => cut4(p2, o)), [e]));
245443
+ const entries4 = [...before2];
245444
+ for (const e of after) entries4.push(...before2.reduce((pieces, b) => pieces.flatMap((p2) => cut4(p2, b)), [e]));
245411
245445
  const unique5 = [...new Map(entries4.filter((e) => userRef4.has(e.user) && e.start < e.end).map((e) => [`${e.user}|${e.start}|${e.end}`, e])).values()].sort((a, b) => a.start - b.start);
245412
245446
  if (!unique5.length) continue;
245413
245447
  s3.ref = cx.ref(`schedule_${s3.name ?? s3.id}`);
245414
245448
  seeded.push({ ref: s3.ref, ...PD_ID.test(s3.id) && { id: s3.id }, name: s3.name ?? s3.id, entries: unique5.map((e) => ({ user: `$${userRef4.get(e.user)}`, start: new Date(e.start).toISOString(), end: new Date(e.end).toISOString() })) });
245415
245449
  cx.note("observed", `seed.pagerduty.schedules.${s3.ref}`, `${s3.name ?? s3.id}: ${unique5.length} on-call entries${mine.length ? `, with the agent's ${mine.length} override(s) taken out` : ""}`, [...new Set(unique5.map((e) => e.span))]);
245416
- const covered = mine.filter((o) => !before.some((b) => b.start <= o.start && b.end >= o.end));
245450
+ const covered = mine.filter((o) => !before2.some((b) => b.start <= o.start && b.end >= o.end));
245417
245451
  if (covered.length) cx.note("missing", `seed.pagerduty.schedules.${s3.ref}.entries`, `who was on call before ${covered.length} of the agent's overrides was never read`);
245418
245452
  if (s3.policy && !policies2.has(s3.policy.id)) {
245419
245453
  policies2.set(s3.policy.id, { ref: cx.ref(`policy_${s3.policy.name ?? s3.policy.id}`), id: s3.policy.id, name: s3.policy.name, levels: [{ targets: [`$${s3.ref}`] }] });
@@ -245473,8 +245507,8 @@ function readOkta(cx) {
245473
245507
  for (const u of list19 ? Array.isArray(c.response) ? c.response : [] : c.response?.id ? [c.response] : []) {
245474
245508
  const login2 = typeof u?.profile?.login === "string" ? u.profile.login.toLowerCase() : void 0;
245475
245509
  if (!u?.id || !login2 || !EMAIL22.test(login2)) continue;
245476
- const before = c.ms < Math.min(firstChange.get(u.id.toLowerCase()) ?? Infinity, firstChange.get(login2) ?? Infinity);
245477
- if (!seen.has(u.id) || before && !seen.get(u.id).before) seen.set(u.id, { user: u, login: login2, span: c.id, before });
245510
+ const before2 = c.ms < Math.min(firstChange.get(u.id.toLowerCase()) ?? Infinity, firstChange.get(login2) ?? Infinity);
245511
+ if (!seen.has(u.id) || before2 && !seen.get(u.id).before) seen.set(u.id, { user: u, login: login2, span: c.id, before: before2 });
245478
245512
  if (one7 && decodeURIComponent(one7[1]).toLowerCase() === "me") me4 = u.id;
245479
245513
  }
245480
245514
  }
@@ -245485,15 +245519,15 @@ function readOkta(cx) {
245485
245519
  };
245486
245520
  const loginOf = new Map([...seen.values()].map((s3) => [s3.user.id, s3.login]));
245487
245521
  const name5 = (value6, fallback) => typeof value6 === "string" && value6.trim() ? value6.trim().slice(0, 50) : fallback;
245488
- const users5 = [...seen.values()].map(({ user: u, login: login2, span: span3, before }) => {
245522
+ const users5 = [...seen.values()].map(({ user: u, login: login2, span: span3, before: before2 }) => {
245489
245523
  const p2 = u.profile, [first2, ...rest2] = login2.split("@")[0].split(/[._-]+/).filter(Boolean).map((w2) => w2[0].toUpperCase() + w2.slice(1));
245490
245524
  let status6 = STATUSES4.has(u.status) ? u.status : "ACTIVE";
245491
- if (!before) {
245525
+ if (!before2) {
245492
245526
  const change4 = changes.find((ch) => ch.key === u.id.toLowerCase() || ch.key === login2);
245493
245527
  status6 = BEFORE[change4?.action] ?? status6;
245494
245528
  cx.note("inferred", `seed.okta.users.${login2}.status`, `read only after the agent's ${change4?.action ?? "change"}; ${status6} before it`, [span3]);
245495
245529
  } else cx.note("observed", `seed.okta.users.${login2}`, `${login2}, ${status6}`, [span3]);
245496
- const created4 = offset20(u.created), changed = before ? offset20(u.statusChanged) : void 0, lastLogin = offset20(u.lastLogin);
245530
+ const created4 = offset20(u.created), changed = before2 ? offset20(u.statusChanged) : void 0, lastLogin = offset20(u.lastLogin);
245497
245531
  const manager = p2.managerId ? loginOf.get(p2.managerId) : void 0;
245498
245532
  if (p2.managerId && !manager) cx.note("missing", `seed.okta.users.${login2}.manager`, `the manager's record (${p2.managerId}) was never read`);
245499
245533
  return {
@@ -245566,8 +245600,8 @@ function readGoogleDrive(cx) {
245566
245600
  }
245567
245601
  for (const f2 of c.path === "/drive/v3/files" ? Array.isArray(c.response?.files) ? c.response.files : [] : FILE2.exec(c.path) && c.response?.id ? [c.response] : []) {
245568
245602
  if (!f2?.id) continue;
245569
- const owner6 = person5(f2.owners?.[0]?.emailAddress, f2.owners?.[0]?.displayName), before = c.ms < changedAt(f2.id), had = files2.get(f2.id);
245570
- if (!had || before && !had.before) files2.set(f2.id, { ...had, ...f2, owner: before ? owner6 : had?.owner, before, span: c.id });
245603
+ const owner6 = person5(f2.owners?.[0]?.emailAddress, f2.owners?.[0]?.displayName), before2 = c.ms < changedAt(f2.id), had = files2.get(f2.id);
245604
+ if (!had || before2 && !had.before) files2.set(f2.id, { ...had, ...f2, owner: before2 ? owner6 : had?.owner, before: before2, span: c.id });
245571
245605
  }
245572
245606
  const m = PERMISSIONS.exec(c.path);
245573
245607
  if (!m) continue;
@@ -245728,10 +245762,10 @@ function readGmail(cx) {
245728
245762
  return refs.get(m.id);
245729
245763
  };
245730
245764
  const parentOf3 = (m) => m.inReplyTo ? byRfc822.get(m.inReplyTo) : void 0;
245731
- const before = all9.filter((m) => m.at < cx.start), during = all9.filter((m) => m.at >= cx.start && !sentByApp.has(m.id));
245765
+ const before2 = all9.filter((m) => m.at < cx.start), during = all9.filter((m) => m.at >= cx.start && !sentByApp.has(m.id));
245732
245766
  const name5 = sendAs?.displayName || agent.split("@")[0];
245733
245767
  const seeded = /* @__PURE__ */ new Set();
245734
- cx.seed.gmail = { agent, mailboxes: [{ address: agent, name: name5, messages: before.map((m) => {
245768
+ cx.seed.gmail = { agent, mailboxes: [{ address: agent, name: name5, messages: before2.map((m) => {
245735
245769
  const parent3 = parentOf3(m), entry3 = {
245736
245770
  ref: ref23(m),
245737
245771
  from: m.from,
@@ -245746,7 +245780,7 @@ function readGmail(cx) {
245746
245780
  return entry3;
245747
245781
  }) }] };
245748
245782
  if (profile2 || sendAs) cx.note("observed", "seed.gmail.agent", agent, [profile2?.id].filter(Boolean));
245749
- for (const m of before) cx.note("observed", `seed.gmail.mailboxes.${ref23(m)}`, `${emailOf(m.from)}: "${m.subject}"`, [m.span]);
245783
+ for (const m of before2) cx.note("observed", `seed.gmail.mailboxes.${ref23(m)}`, `${emailOf(m.from)}: "${m.subject}"`, [m.span]);
245750
245784
  if (during.length) {
245751
245785
  (cx.rules.actors ??= []).push(...during.map((m) => {
245752
245786
  const parent3 = parentOf3(m);
@@ -248948,12 +248982,12 @@ function personByRule(transcript3) {
248948
248982
  const facts = [];
248949
248983
  transcript3.forEach((line2, i) => {
248950
248984
  if (line2.role !== "user" || line2 === users5[0]) return;
248951
- const before = transcript3.slice(0, i).reverse().find((l) => l.role === "assistant");
248985
+ const before2 = transcript3.slice(0, i).reverse().find((l) => l.role === "assistant");
248952
248986
  facts.push({
248953
248987
  id: `said_${facts.length + 2}`,
248954
248988
  value: line2.content,
248955
248989
  match: "semantic",
248956
- about: before ? `what to answer when the agent says: ${before.content.replace(/\s+/g, " ").trim().slice(0, 240)}` : "what to say after your first message"
248990
+ about: before2 ? `what to answer when the agent says: ${before2.content.replace(/\s+/g, " ").trim().slice(0, 240)}` : "what to say after your first message"
248957
248991
  });
248958
248992
  });
248959
248993
  const emails = [...new Set(users5.flatMap((line2) => line2.content.match(EMAIL24) ?? []))];
@@ -250184,6 +250218,7 @@ function inCi(env2) {
250184
250218
  const ci = env2.CI?.trim().toLowerCase();
250185
250219
  return ci !== void 0 && !["", "false", "0"].includes(ci) || ["GITHUB_ACTIONS", "GITLAB_CI", "CIRCLECI", "BUILDKITE", "TF_BUILD", "TRAVIS"].some((name5) => ["true", "1"].includes(env2[name5]?.trim().toLowerCase() ?? "")) || ["JENKINS_URL", "TEAMCITY_VERSION", "BUILD_BUILDID"].some((name5) => Boolean(env2[name5]));
250186
250220
  }
250221
+ var cloudRunByDefault = (env2, source) => !env2.ANCHA_API_KEY && !inCi(env2) && source === "login";
250187
250222
  var SERVER_SOURCE_LABEL = { flag: "--server-url", config: "ancha.yaml server.url", env: "ANCHA_SERVER_URL", login: "ancha login", local: "no server configured" };
250188
250223
  async function serverChoice(ctx) {
250189
250224
  const { serverUrl: flag5, local: local2 } = ctx.globals();
@@ -252583,10 +252618,10 @@ function committed2(tool, state3, seed44, calls2) {
252583
252618
  sent2 = writes3.filter((call4) => call4.method === "POST" && call4.path.endsWith(`/${type}`)).slice(n2, n2 + 1);
252584
252619
  } else sent2 = writes3.filter((call4) => call4.path.endsWith(`/${type}/${id15}`));
252585
252620
  const plural7 = isObject5(seed44) ? seed44[`${type}s`] : void 0;
252586
- const before = Array.isArray(plural7) ? plural7.find((record32) => isObject5(record32) && String(record32.id) === id15) : void 0;
252621
+ const before2 = Array.isArray(plural7) ? plural7.find((record32) => isObject5(record32) && String(record32.id) === id15) : void 0;
252587
252622
  const fields13 = /* @__PURE__ */ new Map();
252588
252623
  for (const call4 of sent2) for (const [name5, value6] of Object.entries(call4.request)) {
252589
- fields13.set(name5, { name: name5, before: operation === "create" || before?.[name5] === void 0 ? null : fieldValue2(before[name5]), after: fieldValue2(value6) });
252624
+ fields13.set(name5, { name: name5, before: operation === "create" || before2?.[name5] === void 0 ? null : fieldValue2(before2[name5]), after: fieldValue2(value6) });
252590
252625
  }
252591
252626
  return { tool, record: `${type} ${id15}`, operation, fields: [...fields13.values()] };
252592
252627
  });
@@ -256306,7 +256341,7 @@ function registerRun(program2, ctx) {
256306
256341
  if (opts.dryRun && opts.on === "cloud") throw new AnchaError("USAGE", "--dry-run checks a run on this computer", { hint: "leave out --on cloud" });
256307
256342
  const trialsOption = sameSetting(opts.trials, opts.attempts, "--trials", "--attempts");
256308
256343
  const parallelOption = sameSetting(opts.parallel, opts.concurrency, "--parallel", "--concurrency");
256309
- const defaulted = opts.on === void 0 && !opts.dryRun && !ctx.io.env.ANCHA_API_KEY && !inCi(ctx.io.env) && (ctx.globals().config !== void 0 || await access11(resolve36(cwd, "ancha.yaml")).then(() => true, () => false)) && cloudRunRefusal(ctx, opts, command, config12) === void 0 && (await serverChoice(ctx)).source === "login";
256344
+ const defaulted = opts.on === void 0 && !opts.dryRun && cloudRunByDefault(ctx.io.env, (await serverChoice(ctx)).source) && (ctx.globals().config !== void 0 || await access11(resolve36(cwd, "ancha.yaml")).then(() => true, () => false)) && cloudRunRefusal(ctx, opts, command, config12) === void 0;
256310
256345
  if (opts.on === "cloud" || defaulted) {
256311
256346
  try {
256312
256347
  ctx.exitCode = await cloudRun(ctx, sceneArgs, opts, command, config12, trialsOption, parallelOption, defaulted);
@@ -257002,6 +257037,7 @@ var seconds3 = (ms2) => {
257002
257037
  return `${value6 < 10 ? value6.toFixed(1) : Math.round(value6)}s`;
257003
257038
  };
257004
257039
  var elapsed = (ms2) => ms2 < 1e3 ? `${ms2} ms` : `${(ms2 / 1e3).toFixed(1)} s`;
257040
+ var before = (calls2) => calls2 ? `and ${calls2} tool call${calls2 === 1 ? "" : "s"}` : "before doing anything";
257005
257041
  var human = (command) => command.replace(/\s--json\b/g, "");
257006
257042
  var fixLine = (fix) => fix.via === "env" ? `add to ancha.yaml under agent: ${fix.yaml}` : `in ancha.yaml under agent:, set ${fix.yaml}`;
257007
257043
  async function taskCheck(ctx, agent) {
@@ -257113,7 +257149,7 @@ function connectionReport(detail3, logTail3, readsAnswer = false) {
257113
257149
  const parsedTextTask = ran.reason?.code === "crashed" && ran.reason.message.includes("connection check's plain-text task");
257114
257150
  fix = ran.fix === void 0 ? parsedTextTask ? ran.reason?.fix : void 0 : fixLine(ran.fix);
257115
257151
  const said = (evidence3.message ?? "The agent could not be started.").replace(/\.$/, "");
257116
- const how = parsedTextTask ? ran.reason.message.replace(/^The agent /, "it ") : /(?:ModuleNotFoundError|ImportError):/.test(said) ? said : ran.exitCode !== null && ran.exitCode !== 0 ? `it exited with code ${ran.exitCode} after ${elapsed(ran.durationMs)} before doing anything` : said.startsWith("The agent stopped on a signal") ? `it stopped on a signal after ${elapsed(ran.durationMs)} before doing anything` : said.replace(/^The agent /, "it ").replace(/^The /, "the ");
257152
+ const how = parsedTextTask ? ran.reason.message.replace(/^The agent /, "it ") : /(?:ModuleNotFoundError|ImportError):/.test(said) ? said : ran.exitCode !== null && ran.exitCode !== 0 ? `it exited with code ${ran.exitCode} after ${elapsed(ran.durationMs)} ${before(ran.calls?.total)}` : said.startsWith("The agent stopped on a signal") ? `it stopped on a signal after ${elapsed(ran.durationMs)} ${before(ran.calls?.total)}` : said.replace(/^The agent /, "it ").replace(/^The /, "the ");
257117
257153
  const tail = ran.logTail?.length ? ran.logTail : logTail3;
257118
257154
  checks2.push({
257119
257155
  name: "agent",
@@ -257121,7 +257157,7 @@ function connectionReport(detail3, logTail3, readsAnswer = false) {
257121
257157
  message: how,
257122
257158
  ...tail.length > 0 && { logTail: tail },
257123
257159
  ...fix !== void 0 && { fix },
257124
- ...fix === void 0 && { hint: `${tail.length > 0 ? "the end of its log is above; " : ""}${ran.reason?.fix ?? "a variable it needs goes up with ancha secrets set NAME and agent.pass_env: [NAME] in ancha.yaml"}` }
257160
+ ...fix === void 0 && { hint: `${tail.length > 0 ? "the end of its log is above; " : ""}${ran.reason?.fix ?? (ran.calls?.total ? "it stopped after its tool calls answered, in its own code" : "a variable it needs goes up with ancha secrets set NAME and agent.pass_env: [NAME] in ancha.yaml")}` }
257125
257161
  });
257126
257162
  } else {
257127
257163
  const attempt2 = detail3.attempts.find((item2) => item2.error !== null);
@@ -257837,7 +257873,7 @@ async function toolAnswers(runDir, summary, filter4) {
257837
257873
  }
257838
257874
  return out;
257839
257875
  }
257840
- var NAMED2 = /* @__PURE__ */ new Set(["model_key", "refused", "outside_host", "unserved", "idle", "no_answer"]);
257876
+ var NAMED2 = /* @__PURE__ */ new Set(["answer_refused", "model_key", "refused", "outside_host", "unserved", "idle", "no_answer"]);
257841
257877
  function invalidSetupNext(summary, out, readDirectory) {
257842
257878
  const invalid42 = summary.scenes.filter((scene2) => (scene2.counts?.invalid ?? scene2.invalidTrials ?? 0) > 0 || scene2.trialsDetail.some((trial) => trial.valid === false));
257843
257879
  if (!invalid42.length || summary.source === "pytest") return void 0;
@@ -257872,7 +257908,7 @@ async function trialOutcomes(runDir, summary, filter4) {
257872
257908
  const result = await readFile35(join50(dir2, "result.json"), "utf8").then((text31) => JSON.parse(text31), () => ({}));
257873
257909
  const log3 = (await readFile35(join50(dir2, "agent.log"), "utf8").catch(() => "")).slice(-1e6);
257874
257910
  const { reason: reason2, calls: calls2 } = attemptOutcome(
257875
- { exit: detail3.exit, exitCode: detail3.exitCode, realMs: detail3.realMs, trace: trace2, log: log3, ...result.logTail && { logTail: result.logTail }, modelReplies: result.modelReplies },
257911
+ { exit: detail3.exit, exitCode: detail3.exitCode, realMs: detail3.realMs, trace: trace2, log: log3, ...result.logTail && { logTail: result.logTail }, modelReplies: result.modelReplies, sessionRefusals: result.sessionRefusals },
257876
257912
  { check: "test", answerChecked, target: "local" }
257877
257913
  );
257878
257914
  if (!NAMED2.has(reason2.code) || reason2.level !== "fail") continue;
@@ -259907,14 +259943,18 @@ function readEvalItems(name5, raw3) {
259907
259943
 
259908
259944
  // backend/src/kit/netsuite-data.ts
259909
259945
  function netsuiteData(size2, options5 = {}) {
259910
- const { world: world5, evals, counts: counts2 } = generateNetsuitePe({ size: size2, id: options5.id ?? `netsuite-pe-${size2}`, startTime: NETSUITE_PE_START_TIME, vocab: options5.vocab });
259946
+ const { world: world5, evals: all9, counts: counts2 } = generateNetsuitePe({ size: size2, id: options5.id ?? `netsuite-pe-${size2}`, startTime: NETSUITE_PE_START_TIME, vocab: options5.vocab });
259947
+ const evals = options5.readOnly ? all9.filter((e) => e.read_only) : all9;
259911
259948
  const evalsFile = `${world5.id}.jsonl`;
259912
259949
  const { tests, skipped } = importEvals(evals, { id: world5.id, tools: world5.tools }, { out: options5.testDirectory ?? "ancha/tests", source: evalsFile, judge: "never" });
259913
259950
  if (skipped.length) throw new Error("NetSuite eval compilation failed");
259951
+ const reads2 = evals.filter((e) => e.read_only).length;
259914
259952
  return {
259915
259953
  id: world5.id,
259916
259954
  size: size2,
259917
259955
  counts: counts2,
259956
+ reads: reads2,
259957
+ writes: evals.length - reads2,
259918
259958
  world: `ancha/worlds/${world5.id}.yaml`,
259919
259959
  evals: `ancha/evals/${evalsFile}`,
259920
259960
  tests: tests.map((test3) => test3.path),
@@ -260508,8 +260548,8 @@ async function chooseWorld(ctx, id15, command = 'ancha test new "<sentence>"') {
260508
260548
  throw new AnchaError("SCENE_INVALID", `ancha/worlds/${chosen}.yaml: ${error65 instanceof Error ? error65.message : String(error65)}`, { hint: "run `ancha schema world` for the world file format" });
260509
260549
  }
260510
260550
  }
260511
- function lineDiff2(before, after) {
260512
- const a = before === "" ? [] : before.replace(/\n$/, "").split("\n"), b = after.replace(/\n$/, "").split("\n");
260551
+ function lineDiff2(before2, after) {
260552
+ const a = before2 === "" ? [] : before2.replace(/\n$/, "").split("\n"), b = after.replace(/\n$/, "").split("\n");
260513
260553
  const lcs = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
260514
260554
  for (let i2 = a.length - 1; i2 >= 0; i2--) for (let j2 = b.length - 1; j2 >= 0; j2--) lcs[i2][j2] = a[i2] === b[j2] ? lcs[i2 + 1][j2 + 1] + 1 : Math.max(lcs[i2 + 1][j2], lcs[i2][j2 + 1]);
260515
260555
  const lines2 = [];
@@ -260548,7 +260588,7 @@ async function testNew(ctx, intent, options5) {
260548
260588
  const draft2 = await draftTest({ intent, world: world5, model: client2, ...options5.id && { id: options5.id }, onProgress: (line2) => ctx.out.info(` ${line2}`) });
260549
260589
  const path9 = join57(outDir, `${draft2.test.id}.yaml`), recordPath = join57(outDir, `${draft2.test.id}.gen.json`);
260550
260590
  if (existsSync3(path9) && !options5.force) throw exists5(ctx, path9);
260551
- const before = existsSync3(path9) ? await readFile41(path9, "utf8") : "";
260591
+ const before2 = existsSync3(path9) ? await readFile41(path9, "utf8") : "";
260552
260592
  const at6 = (/* @__PURE__ */ new Date()).toISOString();
260553
260593
  const yaml = testYaml2({ ...draft2.test, generated: { by: "ancha test new", at: at6, from: intent, record: `${draft2.test.id}.gen.json` } }, intent);
260554
260594
  const cost = Math.round(draft2.calls.reduce((sum6, call4) => sum6 + call4.costUsd, 0) * 1e6) / 1e6;
@@ -260567,7 +260607,7 @@ async function testNew(ctx, intent, options5) {
260567
260607
  people: people4,
260568
260608
  calls: draft2.calls.length,
260569
260609
  cost_usd: cost,
260570
- diff: lineDiff2(before, yaml),
260610
+ diff: lineDiff2(before2, yaml),
260571
260611
  reused: false,
260572
260612
  next: [`ancha run ${file3}`],
260573
260613
  ...credit === "workspace" && { modelCredit: "workspace" }
@@ -260817,11 +260857,11 @@ function parseData(value6) {
260817
260857
  return { size: match3[1] ?? "m" };
260818
260858
  }
260819
260859
  var TESTS_GLOB = "ancha/tests/*.yaml";
260820
- var composioStarterNext = (cloud, all9 = false) => [
260860
+ var composioStarterNext = (cloud, all9 = false, onCloud = false) => [
260821
260861
  ...cloud ? [] : ["ancha login"],
260822
260862
  "ancha secrets set COMPOSIO_API_KEY",
260823
260863
  "ancha agent upload",
260824
- all9 ? "ancha run" : "ancha run scenes/starter/scene.yaml"
260864
+ `ancha run${onCloud ? " --on cloud" : ""}${all9 ? "" : " scenes/starter/scene.yaml"}`
260825
260865
  ];
260826
260866
  async function wireComposio(cwd, candidates2) {
260827
260867
  const added = [], pending = [];
@@ -260909,7 +260949,7 @@ async function addExampleSeeds(file3, twins) {
260909
260949
  for (const twin of twins) {
260910
260950
  if (doc.hasIn(["seed", twin])) continue;
260911
260951
  const tools2 = doc.get("tools");
260912
- const before = doc.clone();
260952
+ const before2 = doc.clone();
260913
260953
  doc.setIn(["seed", twin], doc.createNode(exampleSeed(twin)));
260914
260954
  if (!tools2?.items.some((item2) => String(item2.value ?? item2) === twin)) doc.addIn(["tools"], twin);
260915
260955
  try {
@@ -260917,7 +260957,7 @@ async function addExampleSeeds(file3, twins) {
260917
260957
  added.push(twin);
260918
260958
  } catch {
260919
260959
  skipped.push(twin);
260920
- doc.contents = before.contents;
260960
+ doc.contents = before2.contents;
260921
260961
  }
260922
260962
  }
260923
260963
  if (added.length > 0) await writeFile27(file3, doc.toString({ lineWidth: 0 }));
@@ -260943,7 +260983,7 @@ function answerLine(task2) {
260943
260983
  if (configured === "done") return "answer: ancha.yaml sets agent.answer: done; only what your agent posts to ANCHA_DONE_URL is its answer";
260944
260984
  if (from === "done" && done !== null) return done.name === "entry" ? `answer: entry() posts what your agent returns to ANCHA_DONE_URL (${where2(done)}); that is its answer` : `answer: your agent posts its answer to ANCHA_DONE_URL (${where2(done)})`;
260945
260985
  if (from === "reply" && configured !== "stdout") return "answer: your agent's HTTP reply is its answer";
260946
- return 'answer: what your agent prints on stdout is its answer, and its logs go to stderr; to give it exactly, POST {"output": ...} to ANCHA_DONE_URL';
260986
+ return 'answer: what your agent prints on stdout is its answer, and its logs go to stderr; to give it exactly, POST {"output": ...} to ANCHA_DONE_URL with Authorization: Bearer $ANCHA_TRIAL_TOKEN';
260947
260987
  }
260948
260988
  function netsuiteLine(task2, written) {
260949
260989
  if (task2.netsuite.length === 0) return void 0;
@@ -261013,7 +261053,7 @@ async function wireExistingConfig(cwd, fillMissing) {
261013
261053
  return task2;
261014
261054
  }
261015
261055
  function registerKit(program2, ctx) {
261016
- program2.command("init").description("set up agent tests in this project: ancha.yaml, a starter test for the tools it uses, coding-agent instructions; installs and runs nothing").option("--on <target>", "use local setup and starter tests: local").option("--agent <command>", "the command that starts your agent (default: project scripts, README usage, Procfile, Dockerfile, langgraph.json or a single entry file)").option("--template <template>", "starter or incidents", "starter").option("--tools <tools>", "the tools your agent uses, comma-separated (e.g. netsuite,slack), in place of the ones init finds in its dependencies and source").option("--data <data>", "for an agent that uses NetSuite, in a project with no tests: netsuite-pe:s, netsuite-pe:m (the default) or netsuite-pe:l, the NetSuite world init writes with its 25 tests; none leaves them out, and the QuickBooks examples too").option("--intent <description>", "also generate a world (company, people, tool history) from this description and draft a first test with people for it (uses a model)").option("--idempotency-key <key>", "with --intent: return the first world and test for a repeated request instead of generating again").action(async (opts, command) => {
261056
+ program2.command("init").description("set up agent tests in this project: ancha.yaml, a starter test for the tools it uses, coding-agent instructions; installs and runs nothing").option("--on <target>", "use local setup and starter tests: local").option("--agent <command>", "the command that starts your agent (default: project scripts, README usage, Procfile, Dockerfile, langgraph.json or a single entry file)").option("--template <template>", "starter or incidents", "starter").option("--tools <tools>", "the tools your agent uses, comma-separated (e.g. netsuite,slack), in place of the ones init finds in its dependencies and source").option("--data <data>", "for an agent that uses NetSuite, in a project with no tests: netsuite-pe:s, netsuite-pe:m (the default) or netsuite-pe:l, the NetSuite world init writes with its 25 tests (its 10 read tasks for an agent on Composio); none leaves them out, and the QuickBooks examples too").option("--intent <description>", "also generate a world (company, people, tool history) from this description and draft a first test with people for it (uses a model)").option("--idempotency-key <key>", "with --intent: return the first world and test for a repeated request instead of generating again").action(async (opts, command) => {
261017
261057
  if (opts.on !== void 0 && opts.on !== "local") throw new AnchaError("USAGE", "init --on expects local", { hint: "run ancha init --on local for local setup, or ancha init for your linked workspace" });
261018
261058
  if (opts.template !== "starter" && opts.template !== "incidents") throw new AnchaError("USAGE", `unknown template: ${opts.template}`, { hint: "available templates: starter, incidents" });
261019
261059
  const given2 = opts.tools === void 0 ? void 0 : parseTools(opts.tools);
@@ -261047,8 +261087,8 @@ function registerKit(program2, ctx) {
261047
261087
  const noStarter = defaultTemplate && (existing3.length > 0 || cloud && !(routeTools.length > 0 && !traces));
261048
261088
  const starter = opts.template === "starter" && (!noStarter || own2 !== void 0);
261049
261089
  const tests = (await glob3(["scenes/**/scene.yaml", "ancha/tests/**/*.yaml", ...existingConfig?.scenes ?? []], { cwd: ctx.io.cwd, onlyFiles: true, followSymbolicLinks: false })).filter((path9) => own2 === void 0 || path9 !== "scenes/starter/scene.yaml");
261050
- const dataSize = data7 === "none" ? void 0 : data7 !== void 0 ? data7.size : used.includes("netsuite") && !routeTools.includes("netsuite") && opts.intent === void 0 && tests.length === 0 && !traces ? "m" : void 0;
261051
- const pe = dataSize === void 0 ? void 0 : netsuiteData(dataSize);
261090
+ const dataSize = data7 === "none" ? void 0 : data7 !== void 0 ? data7.size : used.includes("netsuite") && opts.intent === void 0 && tests.length === 0 && !traces ? "m" : void 0;
261091
+ const pe = dataSize === void 0 ? void 0 : netsuiteData(dataSize, { readOnly: routeTools.includes("netsuite") });
261052
261092
  const examples2 = data7 !== "none" && used.includes("quickbooks") && opts.intent === void 0 && tests.length === 0 && !traces ? await quickbooksExamples() : void 0;
261053
261093
  const existingTwins = await Promise.all(existing3.map((path9) => loadSceneFile(join58(ctx.io.cwd, path9)).then((scene2) => scene2.twins, () => [])));
261054
261094
  const mapsNetsuite = task2 !== void 0 && task2.netsuite.length > 0 && opts.template === "starter" && existingTwins.every((list19) => list19.includes("netsuite")) && (!starter || twins.includes("netsuite"));
@@ -261076,9 +261116,9 @@ min_pass_rate: 1
261076
261116
  const updated = [];
261077
261117
  const rewritten = own2 === void 0 ? [] : await Promise.all(files2.filter((file3) => file3.relativePath.startsWith("scenes/starter/")).map(async (file3) => await readFile43(join58(ctx.io.cwd, file3.relativePath), "utf8").catch(() => void 0) === file3.content ? void 0 : file3)).then((list19) => list19.filter((file3) => file3 !== void 0));
261078
261118
  if (starterWorld && own2 !== void 0) {
261079
- const before = await readFile43(join58(ctx.io.cwd, starterWorld.relativePath), "utf8").catch(() => void 0);
261119
+ const before2 = await readFile43(join58(ctx.io.cwd, starterWorld.relativePath), "utf8").catch(() => void 0);
261080
261120
  const previous = await loadSceneFile(join58(ctx.io.cwd, "scenes/starter/scene.yaml"));
261081
- if (before === worldFileYaml(sceneWorld(previous)) && before !== starterWorld.content) rewritten.push(starterWorld);
261121
+ if (before2 === worldFileYaml(sceneWorld(previous)) && before2 !== starterWorld.content) rewritten.push(starterWorld);
261082
261122
  }
261083
261123
  for (const file3 of rewritten) {
261084
261124
  await rewrite(ctx.io.cwd, file3.relativePath, file3.content);
@@ -261135,7 +261175,12 @@ min_pass_rate: 1
261135
261175
  const composio = detection.composio ? { tools: detection.composio.tools, routes: routes2, ...routeWiring, ...question && { question } } : void 0;
261136
261176
  const savedLaunch = savedAgent?.mode === "endpoint" ? savedAgent.start : savedAgent?.command;
261137
261177
  const runs = savedLaunch ? { command: savedLaunch, source: "ancha.yaml" } : void 0;
261138
- const next2 = runs === void 0 ? ["set agent.command in ancha.yaml", cloud ? "ancha agent upload" : "ancha run"] : Object.keys(routes2).length > 0 && starter && !traces && existing3.length === 0 ? composioStarterNext(cloud, examples2 !== void 0) : generated ? cloud ? ["ancha agent upload", `ancha run ${generated.test.file}`] : [`ancha run ${generated.test.file}`] : cloud ? ["ancha agent upload", starter || existing3.length > 0 || pe || examples2 ? "ancha run" : "ancha traces upload ./traces"] : ["ancha run"];
261178
+ const source = await serverChoice(ctx).then((choice5) => choice5.source, () => void 0);
261179
+ const onCloud = Object.keys(routes2).length > 0 && (source === void 0 || !cloudRunByDefault(ctx.io.env, source === "local" ? "login" : source));
261180
+ const next2 = runs === void 0 ? ["set agent.command in ancha.yaml", cloud ? "ancha agent upload" : "ancha run"] : Object.keys(routes2).length > 0 && starter && !traces && existing3.length === 0 ? composioStarterNext(cloud, examples2 !== void 0 || pe !== void 0, onCloud) : generated ? cloud ? ["ancha agent upload", `ancha run ${generated.test.file}`] : [`ancha run ${generated.test.file}`] : cloud ? ["ancha agent upload", starter || existing3.length > 0 || pe || examples2 ? "ancha run" : "ancha traces upload ./traces"] : ["ancha run"];
261181
+ if (onCloud) next2.forEach((step3, i) => {
261182
+ if (/^ancha run(?: |$)/.test(step3) && !step3.includes("--on ")) next2[i] = step3.replace(/^ancha run/, "ancha run --on cloud");
261183
+ });
261139
261184
  next2.unshift(...functionToolWiring(detection.functionTools));
261140
261185
  const taskInput = task2 === void 0 ? void 0 : {
261141
261186
  native: task2.scan.native,
@@ -261168,7 +261213,7 @@ min_pass_rate: 1
261168
261213
  ...existing3.length > 0 ? [`scenes: ${existing3.length} already in this project (${existing3.slice(0, 2).join(", ")}${existing3.length > 2 ? ", \u2026" : ""}); ancha init --template starter adds the starter test`] : [],
261169
261214
  ...starter && unchecked.length > 0 ? [` ${names8(unchecked)}: seeded; no access check, since ${unchecked.length === 1 ? "its" : "their"} requests need signing or a token exchange; add checks of your own`] : [],
261170
261215
  ...examples2 ? [`examples: QuickBooks world ${examples2.id} (Pellmont Building Services' 2025 books) and ${examples2.tests.length} tests:`, ...examples2.tests.map((test3) => ` ${test3.file}: ${test3.title}`)] : [],
261171
- ...dataOutput ? [`data: NetSuite world ${pe.id} (${dataOutput.subsidiaries} subsidiaries, ${dataOutput.transactions.toLocaleString("en-US")} transactions) and ${dataOutput.tests} tests (10 read tasks, 15 write workflows)`] : [],
261216
+ ...dataOutput ? [`data: NetSuite world ${pe.id} (${dataOutput.subsidiaries} subsidiaries, ${dataOutput.transactions.toLocaleString("en-US")} transactions) and ${dataOutput.tests} tests (${pe.reads} read tasks${pe.writes ? `, ${pe.writes} write workflows` : ""})`] : [],
261172
261217
  ...generated ? [`world: ${generated.world.file} (people: ${generated.world.people.join(", ") || "none"})`] : [],
261173
261218
  ...notGenerated?.added.length ? [` world gen populates ${gen_exports.GENERATED_TOOLS.join(", ")}; ${names8(notGenerated.added)} got ${notGenerated.added.length === 1 ? "its" : "their"} example data instead (ancha twins seed <tool> shows the fields)`] : [],
261174
261219
  ...notGenerated?.skipped.length ? [` ${names8(notGenerated.skipped)}: not in the world (the example data clashes with it); add a seed by hand (ancha twins seed <tool>)`] : [],
@@ -263228,9 +263273,9 @@ var ConsoleSandboxes = class {
263228
263273
  const entry3 = await this.entry(id15);
263229
263274
  if (input5.tools === void 0 && input5.key === void 0) fail7("choose tools or a scenario to load");
263230
263275
  return this.lock(entry3, async () => {
263231
- const before = await this.backend.observeEnv(entry3.envId);
263232
- if (!Number.isSafeInteger(revision2) || revision2 !== this.observation(entry3, before).revision) conflict3("sandbox changed; refresh before trying again");
263233
- if (!entry3.setupOpen || entry3.key || before.simMs !== 0 || before.revision !== 0 || before.trace.some((t) => !["GET", "HEAD"].includes(t.method))) fail7("Setup is closed for this sandbox. Create a new sandbox to use a different setup; existing data will not be replaced.");
263276
+ const before2 = await this.backend.observeEnv(entry3.envId);
263277
+ if (!Number.isSafeInteger(revision2) || revision2 !== this.observation(entry3, before2).revision) conflict3("sandbox changed; refresh before trying again");
263278
+ if (!entry3.setupOpen || entry3.key || before2.simMs !== 0 || before2.revision !== 0 || before2.trace.some((t) => !["GET", "HEAD"].includes(t.method))) fail7("Setup is closed for this sandbox. Create a new sandbox to use a different setup; existing data will not be replaced.");
263234
263279
  const tools2 = input5.tools === void 0 ? entry3.tools : await this.tools(input5.tools);
263235
263280
  const item2 = input5.key === void 0 ? void 0 : await this.catalog.get(typeof input5.key === "string" ? input5.key : fail7("invalid scenario key"));
263236
263281
  if (item2) this.requireTools(item2.scene, tools2);
@@ -264033,13 +264078,13 @@ async function writePulledTest(cwd, input5, force = false) {
264033
264078
  if (!info2.isFile() || info2.isSymbolicLink()) throw new AnchaError("USAGE", "The test path must be a regular file.");
264034
264079
  return readFile47(target6, "utf8");
264035
264080
  };
264036
- const before = await current();
264037
- if (!force && before !== null && before !== input5.yaml && hash8(before) !== input5.baseSha256 && hash8(before) !== input5.previousSha256)
264081
+ const before2 = await current();
264082
+ if (!force && before2 !== null && before2 !== input5.yaml && hash8(before2) !== input5.baseSha256 && hash8(before2) !== input5.previousSha256)
264038
264083
  throw new AnchaError("SESSION_CONFLICT", `${input5.path} changed since this run's bundle.`, { hint: "Keep your local edits, or repeat ancha test pull with --force to replace the file." });
264039
264084
  const temp = join66(dirname24(target6), `.ancha-pull-${randomUUID22()}`);
264040
264085
  try {
264041
264086
  await writeFile32(temp, input5.yaml, { flag: "wx", mode: 384 });
264042
- if (await current() !== before) throw new AnchaError("SESSION_CONFLICT", `${input5.path} changed during the pull. Retry the command.`);
264087
+ if (await current() !== before2) throw new AnchaError("SESSION_CONFLICT", `${input5.path} changed during the pull. Retry the command.`);
264043
264088
  await rename10(temp, target6);
264044
264089
  } finally {
264045
264090
  await rm20(temp, { force: true });
@@ -264103,9 +264148,9 @@ async function existing2(path9) {
264103
264148
  }
264104
264149
  }
264105
264150
  async function checkBytes(path9, bytes4) {
264106
- const before = await existing2(path9);
264107
- if (before !== void 0 && before !== bytes4) throw conflict4(path9);
264108
- return before !== void 0;
264151
+ const before2 = await existing2(path9);
264152
+ if (before2 !== void 0 && before2 !== bytes4) throw conflict4(path9);
264153
+ return before2 !== void 0;
264109
264154
  }
264110
264155
  async function cleanupPublishedStage(path9) {
264111
264156
  const target6 = await lstat12(path9);
@@ -265948,8 +265993,8 @@ ${skipped.slice(0, 10).map((s3) => `item ${s3.item}: ${s3.reason}`).join("\n")}`
265948
265993
  const tests = [];
265949
265994
  for (const test3 of imported2.tests) {
265950
265995
  const target6 = resolve51(ctx.io.cwd, test3.path);
265951
- const before = existsSync4(target6) ? await readFile52(target6, "utf8") : void 0;
265952
- const status6 = before === void 0 ? "written" : before === test3.yaml ? "unchanged" : !editedSinceImport(before) ? "updated" : options5.force ? "written" : "kept";
265996
+ const before2 = existsSync4(target6) ? await readFile52(target6, "utf8") : void 0;
265997
+ const status6 = before2 === void 0 ? "written" : before2 === test3.yaml ? "unchanged" : !editedSinceImport(before2) ? "updated" : options5.force ? "written" : "kept";
265953
265998
  if (status6 === "written" || status6 === "updated") {
265954
265999
  await mkdir33(dirname27(target6), { recursive: true });
265955
266000
  await writeFile35(target6, test3.yaml);
@@ -266439,17 +266484,17 @@ ${call4.messages.map((message8) => `${message8.speaker}: ${message8.text}`).join
266439
266484
  if (!Number.isSafeInteger(delta2) || delta2 < 0) throw new AnchaError("USAGE", "advance requires a non-negative duration");
266440
266485
  const observation = await withBackend2(ctx, async (backend) => {
266441
266486
  await sandbox(backend, id15);
266442
- const before = await backend.observeEnv(id15);
266443
- if (before.revision === null) throw new AnchaError("USAGE", "sandbox is not manually paced");
266444
- return backend.advanceInspection(id15, before.revision, before.simMs + delta2);
266487
+ const before2 = await backend.observeEnv(id15);
266488
+ if (before2.revision === null) throw new AnchaError("USAGE", "sandbox is not manually paced");
266489
+ return backend.advanceInspection(id15, before2.revision, before2.simMs + delta2);
266445
266490
  });
266446
266491
  ctx.out.result({ id: id15, simMs: observation.simMs }, () => `Advanced ${id15} to ${observation.simMs / 1e3}s.`);
266447
266492
  });
266448
266493
  command.command("reset").argument("<id>").description("restore original tool state; does not reset agent memory").action(async (id15) => {
266449
266494
  await withBackend2(ctx, async (backend) => {
266450
266495
  await sandbox(backend, id15);
266451
- const before = await backend.observeEnv(id15);
266452
- if (before.revision !== null) await backend.resetInspection(id15, before.revision);
266496
+ const before2 = await backend.observeEnv(id15);
266497
+ if (before2.revision !== null) await backend.resetInspection(id15, before2.revision);
266453
266498
  else await backend.resetEnv(id15);
266454
266499
  });
266455
266500
  ctx.out.result({ id: id15, reset: true, evaluation: "ungraded" }, () => `Reset ${id15} to its original tool data.`);
@@ -275446,12 +275491,12 @@ var require_core$32 = /* @__PURE__ */ __commonJSMin2(((exports) => {
275446
275491
  RULES.all[keyword] = rule;
275447
275492
  (_a7 = definition3.implements) === null || _a7 === void 0 || _a7.forEach((kwd) => this.addKeyword(kwd));
275448
275493
  }
275449
- function addBeforeRule(ruleGroup, rule, before) {
275450
- const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
275494
+ function addBeforeRule(ruleGroup, rule, before2) {
275495
+ const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before2);
275451
275496
  if (i >= 0) ruleGroup.rules.splice(i, 0, rule);
275452
275497
  else {
275453
275498
  ruleGroup.rules.push(rule);
275454
- this.logger.warn(`rule ${before} is not defined`);
275499
+ this.logger.warn(`rule ${before2} is not defined`);
275455
275500
  }
275456
275501
  }
275457
275502
  function keywordMetaschema(def) {