@ancha-labs/cli 0.4.1 → 0.4.3

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
@@ -42718,8 +42718,8 @@ function parseSceneYaml(text24) {
42718
42718
  if (atError >= 0) issues[atError].hint = "scene refs use $, e.g. $alice \u2014 YAML reserves @";
42719
42719
  throw sceneError(issues, doc.errors[0]);
42720
42720
  }
42721
- const cut = cutProseIssues(doc, text24, lineCounter);
42722
- if (cut.length > 0) throw sceneError(cut);
42721
+ const cut2 = cutProseIssues(doc, text24, lineCounter);
42722
+ if (cut2.length > 0) throw sceneError(cut2);
42723
42723
  return doc.toJS();
42724
42724
  }
42725
42725
  async function loadSceneFile(path6) {
@@ -96979,11 +96979,18 @@ var require_x509_transport_state = __commonJS({
96979
96979
 
96980
96980
  // cloud/rebuild/ir.mjs
96981
96981
  function serviceOf(url3) {
96982
+ let u;
96982
96983
  try {
96983
- return HOSTS.get(new URL(url3).host);
96984
+ u = new URL(url3);
96984
96985
  } catch {
96985
96986
  return void 0;
96986
96987
  }
96988
+ return HOSTS.get(u.host) ?? serviceByRule(u);
96989
+ }
96990
+ function serviceByRule(u) {
96991
+ if (/^[a-z0-9-]+\.(?:okta|oktapreview|okta-emea)\.com$/i.test(u.hostname)) return "okta";
96992
+ if (u.hostname === "www.googleapis.com" && /^\/(?:upload\/)?drive\//.test(u.pathname)) return "google-drive";
96993
+ return void 0;
96987
96994
  }
96988
96995
  function parseIr(text24) {
96989
96996
  const lines = String(text24).split("\n").filter((line2) => line2.trim());
@@ -97032,6 +97039,7 @@ function itemsOf(records3) {
97032
97039
  ms: Date.parse(r.t),
97033
97040
  service,
97034
97041
  method: String(r.method ?? "GET").toUpperCase(),
97042
+ host: url3.host,
97035
97043
  path: url3.pathname,
97036
97044
  query: query11,
97037
97045
  status: r.response?.status,
@@ -97285,6 +97293,7 @@ function readGitHub(cx) {
97285
97293
  return logins.get(login2);
97286
97294
  };
97287
97295
  if (agentLogin) loginRef(agentLogin);
97296
+ const access8 = readAccess(cx, repos, loginRef);
97288
97297
  cx.seed.github = { repos: [] };
97289
97298
  for (const repo4 of repos.values()) {
97290
97299
  const history3 = [...repo4.commits.values()].filter((cm) => cm.date && Date.parse(cm.date) < cx.start).sort((a, b) => a.date.localeCompare(b.date));
@@ -97336,15 +97345,84 @@ function readGitHub(cx) {
97336
97345
  cx.note("inferred", `seed.github.repos.${repo4.ref}.production`, `the head of ${repo4.default_branch} (${head.sha.slice(0, 7)}); no deployment was read before the episode`);
97337
97346
  repo4.history = history3;
97338
97347
  }
97348
+ for (const seeded of cx.seed.github.repos) {
97349
+ const grants = [...access8.grants.get(seeded.name)?.entries() ?? []];
97350
+ if (grants.length) seeded.collaborators = grants.map(([login2, g]) => ({ user: `$${loginRef(login2)}`, permission: g.permission }));
97351
+ }
97352
+ if (access8.orgs.length) cx.seed.github.orgs = access8.orgs;
97339
97353
  cx.seed.github.users = [...logins].map(([login2, ref20]) => ({ ref: ref20, login: login2 }));
97340
97354
  if (agentLogin) cx.seed.github.bot = `$${logins.get(agentLogin)}`;
97341
- return { repos, merged };
97355
+ return { repos, merged, access: access8 };
97356
+ }
97357
+ function readAccess(cx, repos, loginRef) {
97358
+ const grants = /* @__PURE__ */ new Map(), removed = [], members4 = /* @__PURE__ */ new Map(), left = [];
97359
+ const grant = (full2, login2, permission6, how, span2) => {
97360
+ const list16 = grants.get(full2) ?? /* @__PURE__ */ new Map();
97361
+ if (!list16.has(login2)) list16.set(login2, { permission: permission6, how, span: span2 });
97362
+ grants.set(full2, list16);
97363
+ };
97364
+ const membership = (org5, login2, member4, how, span2) => {
97365
+ const list16 = members4.get(org5) ?? /* @__PURE__ */ new Map();
97366
+ if (!list16.has(login2)) list16.set(login2, { member: member4, how, span: span2 });
97367
+ members4.set(org5, list16);
97368
+ };
97369
+ const calls2 = cx.calls("github", (c) => c.status < 300 || c.status === 404);
97370
+ const changedAt = (path6, login2) => Math.min(...calls2.filter((c) => c.method === "DELETE" && c.status < 300 && c.path.startsWith(path6) && c.path.split("/").pop().toLowerCase() === login2.toLowerCase()).map((c) => c.ms));
97371
+ for (const c of calls2) {
97372
+ const repo4 = c.path.match(/^\/repos\/([^/]+\/[^/]+)\/collaborators(?:\/([^/]+))?$/), org5 = c.path.match(/^\/orgs\/([^/]+)\/(members|memberships)(?:\/([^/]+))?$/);
97373
+ if (repo4 && !repo4[2] && c.method === "GET" && c.status < 300 && ["direct", "outside"].includes(c.query.affiliation) && Array.isArray(c.response)) {
97374
+ for (const u of c.response) if (u?.login && permissionOf2(u) && c.ms < changedAt(`/repos/${repo4[1]}/collaborators/`, u.login)) grant(repo4[1], u.login, permissionOf2(u), "observed", c.id);
97375
+ }
97376
+ if (repo4?.[2] && c.method === "DELETE" && c.status < 300) removed.push({ full: repo4[1], login: decodeURIComponent(repo4[2]), ms: c.ms, span: c.id });
97377
+ if (!org5) continue;
97378
+ const login2 = org5[3] && decodeURIComponent(org5[3]);
97379
+ if (c.method === "DELETE" && login2 && c.status < 300) left.push({ org: org5[1], login: login2, ms: c.ms, span: c.id });
97380
+ if (c.method !== "GET" || login2 && c.ms >= changedAt(`/orgs/${org5[1]}/`, login2)) continue;
97381
+ if (login2 && org5[2] === "members") membership(org5[1], login2, c.status < 300, "observed", c.id);
97382
+ if (login2 && org5[2] === "memberships") membership(org5[1], login2, c.status < 300 && c.response?.state !== "pending" ? c.response?.role === "admin" ? "admin" : "member" : false, "observed", c.id);
97383
+ if (!login2 && org5[2] === "members" && Array.isArray(c.response)) {
97384
+ for (const u of c.response) if (u?.login) membership(org5[1], u.login, "member", "observed", c.id);
97385
+ }
97386
+ }
97387
+ for (const r of removed) if (!grants.get(r.full)?.has(r.login)) {
97388
+ grant(r.full, r.login, "write", "inferred", r.span);
97389
+ cx.note("inferred", `seed.github.repos.${r.full}.collaborators.${r.login}`, `the agent removed ${r.login}'s direct access, so it existed; write, as the permission was never read`, [r.span]);
97390
+ }
97391
+ for (const [full2, list16] of grants) for (const [login2, g] of list16) if (g.how === "observed") cx.note("observed", `seed.github.repos.${full2}.collaborators.${login2}`, `direct ${g.permission}`, [g.span]);
97392
+ for (const l of left) membership(l.org, l.login, "member", "inferred", l.span);
97393
+ for (const owner3 of new Set(removed.map((r) => r.full.split("/")[0]))) {
97394
+ const unread = removed.filter((r) => r.full.startsWith(`${owner3}/`) && !members4.get(owner3)?.has(r.login));
97395
+ if (!unread.length) continue;
97396
+ const id12 = `github.members.${owner3}`, answer = cx.answers[id12];
97397
+ const people3 = [...new Set(unread.map((r) => r.login))].join(", "), where2 = [...new Set(unread.map((r) => r.full))].join(", ");
97398
+ cx.ask(id12, `Who were members of the ${owner3} organization when the run started? A member reads every ${owner3} repository, so a member whose direct access the agent removed (${people3} on ${where2}) still reads it. The trace never shows the membership.`, ["none", "their logins, comma-separated"], 0, { type: "text" });
97399
+ if (typeof answer !== "string") continue;
97400
+ const named3 = /^\s*none\s*$/i.test(answer) ? [] : answer.split(/[\s,]+/).filter(Boolean);
97401
+ for (const login2 of named3) membership(owner3, login2, "member", "answered");
97402
+ for (const r of unread) if (!named3.some((n) => n.toLowerCase() === r.login.toLowerCase())) membership(owner3, r.login, false, "answered");
97403
+ cx.note("answered", `seed.github.orgs.${owner3}.members`, `your answer: ${named3.length ? named3.join(", ") : "none"}`);
97404
+ }
97405
+ for (const [org5, list16] of members4) for (const [login2, m] of list16) if (m.how === "observed") cx.note("observed", `seed.github.orgs.${org5}.members.${login2}`, m.member ? `member (${m.member})` : "not a member", [m.span]);
97406
+ const isMember3 = (org5, login2) => {
97407
+ const m = [...members4.get(org5)?.entries() ?? []].find(([l]) => l.toLowerCase() === login2.toLowerCase())?.[1];
97408
+ return m === void 0 ? void 0 : Boolean(m.member);
97409
+ };
97410
+ return {
97411
+ grants,
97412
+ removed,
97413
+ left,
97414
+ isMember: isMember3,
97415
+ refOf: loginRef,
97416
+ orgs: [...members4].map(([login2, list16]) => ({ login: login2, members: [...list16].filter(([, m]) => m.member).map(([user8, m]) => ({ user: `$${loginRef(user8)}`, ...m.member === "admin" && { role: "admin" } })) })).filter((o) => o.members.length)
97417
+ };
97342
97418
  }
97343
- var decode5;
97419
+ var decode5, ROLE, permissionOf2;
97344
97420
  var init_github = __esm({
97345
97421
  "cloud/rebuild/readers/github.mjs"() {
97346
97422
  "use strict";
97347
97423
  decode5 = (b64) => Buffer.from(String(b64).replace(/\n/g, ""), "base64").toString("utf8");
97424
+ ROLE = { read: "read", triage: "read", write: "write", maintain: "write", admin: "admin" };
97425
+ permissionOf2 = (c) => ROLE[c?.role_name] ?? (c?.permissions?.admin ? "admin" : c?.permissions?.push ? "write" : c?.permissions?.pull ? "read" : void 0);
97348
97426
  }
97349
97427
  });
97350
97428
 
@@ -97414,15 +97492,50 @@ var init_datadog = __esm({
97414
97492
 
97415
97493
  // cloud/rebuild/readers/pagerduty.mjs
97416
97494
  function readPagerDuty(cx) {
97417
- const users4 = /* @__PURE__ */ new Map(), services2 = /* @__PURE__ */ new Map(), incidents = /* @__PURE__ */ new Map();
97495
+ const users4 = /* @__PURE__ */ new Map(), services2 = /* @__PURE__ */ new Map(), incidents = /* @__PURE__ */ new Map(), schedules = /* @__PURE__ */ new Map(), refs = /* @__PURE__ */ new Map();
97496
+ const overrides = [];
97418
97497
  let actor2;
97498
+ const schedule3 = (id12, name5) => {
97499
+ if (!schedules.has(id12)) schedules.set(id12, { id: id12, name: name5, read: [] });
97500
+ const s = schedules.get(id12);
97501
+ s.name ??= name5;
97502
+ return s;
97503
+ };
97419
97504
  for (const c of cx.calls("pagerduty")) {
97420
97505
  if (c.method === "GET" && c.path === "/users") for (const u of c.response?.users ?? []) users4.set(u.id, { ...u, span: c.id });
97506
+ if (c.method === "GET" && /^\/users\/\w+$/.test(c.path) && c.response?.user?.id) users4.set(c.response.user.id, { ...c.response.user, span: c.id });
97421
97507
  if (c.method === "GET" && c.path === "/services") for (const s of c.response?.services ?? []) services2.set(s.id, { ...s, span: c.id });
97422
97508
  if (c.method === "GET" && c.path === "/incidents") for (const inc of c.response?.incidents ?? []) incidents.set(inc.id, inc);
97423
97509
  if (c.method === "PUT" && /^\/incidents\/\w+$/.test(c.path)) actor2 ??= c.response?.incident?.acknowledgements?.[0]?.acknowledger?.id;
97510
+ const override = c.method === "POST" && c.status < 300 && OVERRIDES.exec(c.path);
97511
+ if (override) for (const o of c.request?.overrides ?? (c.request?.override ? [c.request.override] : [])) {
97512
+ const start = Date.parse(o?.start), end = Date.parse(o?.end);
97513
+ if (start < end) overrides.push({ schedule: override[1], start, end, user: o.user?.id, ms: c.ms, span: c.id });
97514
+ }
97515
+ const entry3 = (s, e, span2) => ({ user: e.user?.id, start: Date.parse(e.start), end: Date.parse(e.end), ms: c.ms, span: span2 });
97516
+ if (c.method === "GET" && c.path === "/oncalls") for (const o of c.response?.oncalls ?? []) {
97517
+ if (o?.user?.id) refs.set(o.user.id, o.user.summary);
97518
+ if (!o?.schedule?.id || !o.start || !o.end) continue;
97519
+ const s = schedule3(o.schedule.id, o.schedule.summary);
97520
+ s.read.push(entry3(s, o, c.id));
97521
+ if (o.escalation_policy?.id) s.policy ??= { id: o.escalation_policy.id, name: o.escalation_policy.summary };
97522
+ }
97523
+ const one7 = c.method === "GET" && SCHEDULE.exec(c.path), detail2 = one7 && c.response?.schedule;
97524
+ if (detail2?.id) {
97525
+ const s = schedule3(detail2.id, detail2.name ?? detail2.summary);
97526
+ for (const u of detail2.users ?? []) if (u?.id) refs.set(u.id, u.summary);
97527
+ for (const e of detail2.final_schedule?.rendered_schedule_entries ?? []) if (e?.user?.id) {
97528
+ refs.set(e.user.id, e.user.summary);
97529
+ s.read.push(entry3(s, e, c.id));
97530
+ }
97531
+ if (detail2.escalation_policies?.[0]?.id) s.policy ??= { id: detail2.escalation_policies[0].id, name: detail2.escalation_policies[0].summary };
97532
+ }
97533
+ }
97534
+ if (!users4.size || !services2.size && !schedules.size) return void 0;
97535
+ for (const [id12, name5] of refs) if (!users4.has(id12) && name5) {
97536
+ users4.set(id12, { id: id12, name: name5, email: `${String(name5).toLowerCase().replace(/[^a-z0-9]+/g, ".").replace(/^\.|\.$/g, "") || id12.toLowerCase()}@pagerduty.invalid` });
97537
+ cx.note("missing", `seed.pagerduty.users.${id12}.email`, `${name5} was on call but never looked up, so the address is a placeholder`);
97424
97538
  }
97425
- if (!services2.size || !users4.size) return void 0;
97426
97539
  const userRef4 = new Map([...users4.values()].map((u) => [u.id, cx.ref(`pd_${u.name}`)]));
97427
97540
  const policies = /* @__PURE__ */ new Map();
97428
97541
  for (const s of services2.values()) {
@@ -97433,20 +97546,262 @@ function readPagerDuty(cx) {
97433
97546
  }
97434
97547
  s.ref = cx.ref(`service_${s.name}`);
97435
97548
  }
97549
+ const fromIncidents = policies.size;
97550
+ const seeded = [];
97551
+ for (const s of schedules.values()) {
97552
+ const mine = overrides.filter((o) => o.schedule === s.id);
97553
+ const first = Math.min(...mine.map((o) => o.ms));
97554
+ const before = s.read.filter((e) => e.ms < first), after = s.read.filter((e) => e.ms >= first).flatMap((e) => mine.filter((o) => o.ms <= e.ms).reduce((pieces, o) => pieces.flatMap((p2) => cut(p2, o)), [e]));
97555
+ const entries2 = [...before];
97556
+ for (const e of after) entries2.push(...before.reduce((pieces, b) => pieces.flatMap((p2) => cut(p2, b)), [e]));
97557
+ const unique3 = [...new Map(entries2.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);
97558
+ if (!unique3.length) continue;
97559
+ s.ref = cx.ref(`schedule_${s.name ?? s.id}`);
97560
+ seeded.push({ ref: s.ref, ...PD_ID.test(s.id) && { id: s.id }, name: s.name ?? s.id, entries: unique3.map((e) => ({ user: `$${userRef4.get(e.user)}`, start: new Date(e.start).toISOString(), end: new Date(e.end).toISOString() })) });
97561
+ cx.note("observed", `seed.pagerduty.schedules.${s.ref}`, `${s.name ?? s.id}: ${unique3.length} on-call entries${mine.length ? `, with the agent's ${mine.length} override(s) taken out` : ""}`, [...new Set(unique3.map((e) => e.span))]);
97562
+ const covered = mine.filter((o) => !before.some((b) => b.start <= o.start && b.end >= o.end));
97563
+ if (covered.length) cx.note("missing", `seed.pagerduty.schedules.${s.ref}.entries`, `who was on call before ${covered.length} of the agent's overrides was never read`);
97564
+ if (s.policy && !policies.has(s.policy.id)) {
97565
+ policies.set(s.policy.id, { ref: cx.ref(`policy_${s.policy.name ?? s.policy.id}`), id: s.policy.id, name: s.policy.name, levels: [{ targets: [`$${s.ref}`] }] });
97566
+ cx.note("inferred", `seed.pagerduty.escalation_policies.${s.policy.id}`, `one level targeting ${s.name ?? s.id}, the schedule the on-call entries came from (the policy itself was never read)`);
97567
+ }
97568
+ }
97569
+ if (!policies.size) {
97570
+ const target5 = seeded[0]?.ref ?? userRef4.get(actor2 ?? [...users4.keys()][0]);
97571
+ policies.set("stand-in", { ref: cx.ref("policy_stand_in"), name: "Default", levels: [{ targets: [`$${target5}`] }] });
97572
+ cx.note("missing", "seed.pagerduty.escalation_policies", "no escalation policy was read; one stand-in level");
97573
+ }
97574
+ const kept = [...services2.values()].filter((s) => s.escalation_policy);
97575
+ const standIn = !kept.length && [...policies.values()][0];
97576
+ if (standIn) cx.note("missing", "seed.pagerduty.services", `no service was read; one stand-in on ${standIn.name ?? "the policy"}, as PagerDuty needs one`);
97436
97577
  cx.seed.pagerduty = {
97437
- users: [...users4.values()].map((u) => ({ ref: userRef4.get(u.id), id: u.id, name: u.name, email: u.email })),
97578
+ users: [...users4.values()].map((u) => ({ ref: userRef4.get(u.id), ...PD_ID.test(u.id) && { id: u.id }, name: u.name, email: u.email })),
97438
97579
  ...actor2 && userRef4.has(actor2) && { actor: `$${userRef4.get(actor2)}` },
97439
- escalation_policies: [...policies.values()],
97440
- services: [...services2.values()].filter((s) => s.escalation_policy).map((s) => ({ ref: s.ref, id: s.id, name: s.name, escalation_policy: `$${policies.get(s.escalation_policy.id).ref}` }))
97580
+ ...seeded.length && { schedules: seeded },
97581
+ escalation_policies: [...policies.values()].map(({ id: id12, ...p2 }) => ({ ref: p2.ref, ...PD_ID.test(id12 ?? "") && { id: id12 }, ...p2 })),
97582
+ services: standIn ? [{ ref: cx.ref(`service_${standIn.name ?? "stand_in"}`), name: standIn.name ?? "Service", escalation_policy: `$${standIn.ref}` }] : kept.map((s) => ({ ref: s.ref, id: s.id, name: s.name, escalation_policy: `$${policies.get(s.escalation_policy.id).ref}` }))
97441
97583
  };
97442
- for (const u of users4.values()) cx.note("observed", `seed.pagerduty.users.${userRef4.get(u.id)}`, `${u.name} (${u.id})`, [u.span]);
97584
+ for (const u of users4.values()) if (u.span) cx.note("observed", `seed.pagerduty.users.${userRef4.get(u.id)}`, `${u.name} (${u.id})`, [u.span]);
97443
97585
  for (const s of services2.values()) cx.note("observed", `seed.pagerduty.services.${s.ref}`, `${s.name} (${s.id})`, [s.span]);
97444
- if (policies.size) cx.note("inferred", "seed.pagerduty.escalation_policies", "one level targeting whoever the incidents were assigned to (policies were never read)");
97445
- return { users: users4, services: services2, incidents, actor: actor2 };
97586
+ if (fromIncidents) cx.note("inferred", "seed.pagerduty.escalation_policies", "one level targeting whoever the incidents were assigned to (policies were never read)");
97587
+ return { users: users4, services: services2, incidents, actor: actor2, schedules, overrides };
97446
97588
  }
97589
+ var PD_ID, OVERRIDES, SCHEDULE, cut;
97447
97590
  var init_pagerduty = __esm({
97448
97591
  "cloud/rebuild/readers/pagerduty.mjs"() {
97449
97592
  "use strict";
97593
+ PD_ID = /^P[A-Z0-9]{6}$/;
97594
+ OVERRIDES = /^\/schedules\/(\w+)\/overrides$/;
97595
+ SCHEDULE = /^\/schedules\/(\w+)$/;
97596
+ cut = (entry3, window5) => [
97597
+ ...entry3.start < window5.start ? [{ ...entry3, end: Math.min(entry3.end, window5.start) }] : [],
97598
+ ...entry3.end > window5.end ? [{ ...entry3, start: Math.max(entry3.start, window5.end) }] : []
97599
+ ].filter((e) => e.start < e.end);
97600
+ }
97601
+ });
97602
+
97603
+ // cloud/rebuild/readers/okta.mjs
97604
+ function readOkta(cx) {
97605
+ const calls2 = cx.calls("okta", (c) => c.status < 300);
97606
+ const changes = [], firstChange = /* @__PURE__ */ new Map();
97607
+ for (const c of calls2) {
97608
+ const m = c.method === "GET" ? null : CHANGE.exec(c.path);
97609
+ if (!m || c.method === "POST" && m[2] === void 0 && !c.request) continue;
97610
+ const key3 = decodeURIComponent(m[1]).toLowerCase(), action = c.method === "DELETE" ? "delete" : m[2] ?? "update";
97611
+ changes.push({ key: key3, action, call: c });
97612
+ if (!firstChange.has(key3)) firstChange.set(key3, c.ms);
97613
+ }
97614
+ const seen = /* @__PURE__ */ new Map();
97615
+ let me4;
97616
+ for (const c of calls2) {
97617
+ const one7 = c.method === "GET" && USER.exec(c.path), list16 = c.method === "GET" && c.path === "/api/v1/users";
97618
+ if (!one7 && !list16) continue;
97619
+ for (const u of list16 ? Array.isArray(c.response) ? c.response : [] : c.response?.id ? [c.response] : []) {
97620
+ const login2 = typeof u?.profile?.login === "string" ? u.profile.login.toLowerCase() : void 0;
97621
+ if (!u?.id || !login2 || !EMAIL19.test(login2)) continue;
97622
+ const before = c.ms < Math.min(firstChange.get(u.id.toLowerCase()) ?? Infinity, firstChange.get(login2) ?? Infinity);
97623
+ if (!seen.has(u.id) || before && !seen.get(u.id).before) seen.set(u.id, { user: u, login: login2, span: c.id, before });
97624
+ if (one7 && decodeURIComponent(one7[1]).toLowerCase() === "me") me4 = u.id;
97625
+ }
97626
+ }
97627
+ if (!seen.size) return void 0;
97628
+ const offset16 = (t) => {
97629
+ const ms3 = Date.parse(t ?? "");
97630
+ return Number.isFinite(ms3) && ms3 <= cx.start ? cx.dur(ms3 - cx.start) : void 0;
97631
+ };
97632
+ const loginOf = new Map([...seen.values()].map((s) => [s.user.id, s.login]));
97633
+ const name5 = (value5, fallback) => typeof value5 === "string" && value5.trim() ? value5.trim().slice(0, 50) : fallback;
97634
+ const users4 = [...seen.values()].map(({ user: u, login: login2, span: span2, before }) => {
97635
+ const p2 = u.profile, [first, ...rest] = login2.split("@")[0].split(/[._-]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1));
97636
+ let status5 = STATUSES3.has(u.status) ? u.status : "ACTIVE";
97637
+ if (!before) {
97638
+ const change = changes.find((ch) => ch.key === u.id.toLowerCase() || ch.key === login2);
97639
+ status5 = BEFORE[change?.action] ?? status5;
97640
+ cx.note("inferred", `seed.okta.users.${login2}.status`, `read only after the agent's ${change?.action ?? "change"}; ${status5} before it`, [span2]);
97641
+ } else cx.note("observed", `seed.okta.users.${login2}`, `${login2}, ${status5}`, [span2]);
97642
+ const created2 = offset16(u.created), changed = before ? offset16(u.statusChanged) : void 0, lastLogin = offset16(u.lastLogin);
97643
+ const manager = p2.managerId ? loginOf.get(p2.managerId) : void 0;
97644
+ if (p2.managerId && !manager) cx.note("missing", `seed.okta.users.${login2}.manager`, `the manager's record (${p2.managerId}) was never read`);
97645
+ return {
97646
+ login: login2,
97647
+ ...typeof p2.email === "string" && p2.email.toLowerCase() !== login2 && EMAIL19.test(p2.email) && { email: p2.email.toLowerCase() },
97648
+ firstName: name5(p2.firstName, first ?? "Unknown"),
97649
+ lastName: name5(p2.lastName, rest.join(" ") || "Unknown"),
97650
+ status: status5,
97651
+ ...created2 && { created: created2 },
97652
+ ...changed && (!created2 || Date.parse(u.statusChanged) >= Date.parse(u.created)) && { statusChanged: changed },
97653
+ ...lastLogin && { lastLogin },
97654
+ ...typeof p2.title === "string" && p2.title && { title: p2.title.slice(0, 100) },
97655
+ ...typeof p2.department === "string" && p2.department && { department: p2.department.slice(0, 100) },
97656
+ ...manager && manager !== login2 && { manager }
97657
+ };
97658
+ });
97659
+ let admin = me4 && loginOf.get(me4);
97660
+ if (admin && users4.find((u) => u.login === admin)?.status !== "ACTIVE") admin = void 0;
97661
+ const domain2 = users4[0].login.split("@")[1];
97662
+ if (!admin) {
97663
+ admin = `okta-admin@${domain2}`;
97664
+ if (!users4.some((u) => u.login === admin)) users4.unshift({ login: admin, firstName: "Okta", lastName: "Admin", status: "ACTIVE" });
97665
+ cx.note("missing", "seed.okta.admin", `the API token's owner never showed in the trace (the agent never read /users/me); ${admin} stands in`);
97666
+ }
97667
+ const host = calls2.find((c) => c.host)?.host ?? "";
97668
+ const subdomain2 = /^([a-z0-9-]{1,63})\.(?:okta|oktapreview|okta-emea)\.com$/i.exec(host)?.[1]?.toLowerCase() ?? (domain2.split(".")[0].replace(/[^a-z0-9-]/g, "").slice(0, 63) || "okta");
97669
+ if (!/\.okta/i.test(host)) cx.note("inferred", "seed.okta.org", `the agent's Okta host (${host}) names no org; named after ${domain2}`);
97670
+ cx.seed.okta = { org: { subdomain: subdomain2, name: subdomain2[0].toUpperCase() + subdomain2.slice(1) }, admin, users: users4 };
97671
+ return { users: seen, changes };
97672
+ }
97673
+ var USER, CHANGE, BEFORE, STATUSES3, EMAIL19;
97674
+ var init_okta2 = __esm({
97675
+ "cloud/rebuild/readers/okta.mjs"() {
97676
+ "use strict";
97677
+ USER = /^\/api\/v1\/users\/([^/]+)$/;
97678
+ CHANGE = /^\/api\/v1\/users\/([^/]+)(?:\/lifecycle\/([a-z_]+))?$/;
97679
+ BEFORE = { deactivate: "ACTIVE", suspend: "ACTIVE", unsuspend: "SUSPENDED", unlock: "LOCKED_OUT", activate: "STAGED", delete: "ACTIVE" };
97680
+ STATUSES3 = /* @__PURE__ */ new Set(["STAGED", "PROVISIONED", "ACTIVE", "RECOVERY", "PASSWORD_EXPIRED", "LOCKED_OUT", "SUSPENDED", "DEPROVISIONED"]);
97681
+ EMAIL19 = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
97682
+ }
97683
+ });
97684
+
97685
+ // cloud/rebuild/readers/google-drive.mjs
97686
+ function readGoogleDrive(cx) {
97687
+ const calls2 = cx.calls("google-drive", (c) => c.status < 300);
97688
+ const names3 = /* @__PURE__ */ new Map();
97689
+ const person4 = (email10, displayName) => {
97690
+ if (typeof email10 !== "string" || !EMAIL20.test(email10)) return void 0;
97691
+ const key3 = email10.toLowerCase();
97692
+ if (typeof displayName === "string" && displayName.trim() && !names3.get(key3)) names3.set(key3, displayName.trim().slice(0, 200));
97693
+ else if (!names3.has(key3)) names3.set(key3, void 0);
97694
+ return key3;
97695
+ };
97696
+ const transfers = [], shares = [];
97697
+ for (const c of calls2) {
97698
+ const m = c.method === "POST" && PERMISSIONS.exec(c.path);
97699
+ if (!m || !c.request || typeof c.request !== "object") continue;
97700
+ const to = person4(c.request.emailAddress);
97701
+ if (c.request.role === "owner" && String(c.query?.transferOwnership) === "true" && to) transfers.push({ file: m[1], to, ms: c.ms, span: c.id });
97702
+ else shares.push({ file: m[1], type: c.request.type, role: c.request.role, email: to, domain: c.request.domain, ms: c.ms });
97703
+ }
97704
+ const changedAt = (id12) => Math.min(...transfers.filter((t) => t.file === id12).map((t) => t.ms), ...shares.filter((s) => s.file === id12).map((s) => s.ms));
97705
+ const files2 = /* @__PURE__ */ new Map(), grants = /* @__PURE__ */ new Map();
97706
+ let me4, meSpan;
97707
+ for (const c of calls2) {
97708
+ if (c.method !== "GET") continue;
97709
+ if (c.path === "/drive/v3/about" && !me4) {
97710
+ me4 = person4(c.response?.user?.emailAddress, c.response?.user?.displayName);
97711
+ meSpan = c.id;
97712
+ }
97713
+ for (const f of c.path === "/drive/v3/files" ? Array.isArray(c.response?.files) ? c.response.files : [] : FILE2.exec(c.path) && c.response?.id ? [c.response] : []) {
97714
+ if (!f?.id) continue;
97715
+ const owner3 = person4(f.owners?.[0]?.emailAddress, f.owners?.[0]?.displayName), before = c.ms < changedAt(f.id), had = files2.get(f.id);
97716
+ if (!had || before && !had.before) files2.set(f.id, { ...had, ...f, owner: before ? owner3 : had?.owner, before, span: c.id });
97717
+ }
97718
+ const m = PERMISSIONS.exec(c.path);
97719
+ if (!m) continue;
97720
+ const list16 = grants.get(m[1]) ?? [];
97721
+ for (const p2 of Array.isArray(c.response?.permissions) ? c.response.permissions : []) list16.push({ ...p2, email: person4(p2.emailAddress, p2.displayName), ms: c.ms, span: c.id });
97722
+ grants.set(m[1], list16);
97723
+ }
97724
+ if (!files2.size) return void 0;
97725
+ const handed = transfers.map((t) => files2.get(t.file)?.owner).filter(Boolean);
97726
+ if (!me4 && handed.length) {
97727
+ me4 = handed[0];
97728
+ cx.note("inferred", "seed.google-drive.me", `the agent handed ${handed.length} of ${me4}'s files over, which only their owner can do, so it acted as ${me4}`);
97729
+ }
97730
+ if (!me4) {
97731
+ me4 = [...files2.values()].map((f) => f.owner).find(Boolean);
97732
+ cx.note("missing", "seed.google-drive.me", `the account the agent used never showed (it never read /about); ${me4} stands in`);
97733
+ } else if (meSpan) cx.note("observed", "seed.google-drive.me", me4, [meSpan]);
97734
+ if (!me4) return void 0;
97735
+ for (const f of files2.values()) if (!f.owner && transfers.some((t) => t.file === f.id)) {
97736
+ f.owner = me4;
97737
+ cx.note("inferred", `seed.google-drive.files.${f.id}.owner`, `read only after the handover; the agent, acting as ${me4}, owned it before`);
97738
+ }
97739
+ const offset16 = (t) => {
97740
+ const ms3 = Date.parse(t ?? "");
97741
+ return Number.isFinite(ms3) && ms3 <= cx.start ? cx.dur(ms3 - cx.start) : void 0;
97742
+ };
97743
+ const seeded = [...files2.values()].filter((f) => {
97744
+ const ok = ID4.test(f.id) && typeof f.name === "string" && f.name && typeof f.mimeType === "string" && MIME2.test(f.mimeType) && f.owner;
97745
+ if (!ok) cx.note("missing", `seed.google-drive.files.${f.id}`, "listed without its name, type or owner (the fields the agent asked for left them out)", [f.span]);
97746
+ return ok;
97747
+ });
97748
+ const ids2 = new Set(seeded.map((f) => f.id));
97749
+ const ordered2 = [], placed = /* @__PURE__ */ new Set();
97750
+ const place2 = (f) => {
97751
+ if (placed.has(f.id)) return;
97752
+ placed.add(f.id);
97753
+ const parent2 = seeded.find((p2) => p2.id === f.parents?.[0]);
97754
+ if (parent2) place2(parent2);
97755
+ ordered2.push(f);
97756
+ };
97757
+ seeded.forEach(place2);
97758
+ cx.seed["google-drive"] = {
97759
+ domain: me4.split("@")[1],
97760
+ me: me4,
97761
+ users: [.../* @__PURE__ */ new Set([me4, ...names3.keys()])].map((email10) => {
97762
+ const name5 = names3.get(email10) ?? email10.split("@")[0].split(/[._-]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join(" ");
97763
+ if (!names3.get(email10)) cx.note("inferred", `seed.google-drive.users.${email10}`, `no name in the trace; "${name5}" from the address`);
97764
+ return { email: email10, name: name5 };
97765
+ }),
97766
+ files: ordered2.map((f) => {
97767
+ const parent2 = f.parents?.[0], kept = [], dropped = [];
97768
+ for (const g of grants.get(f.id) ?? []) {
97769
+ const transfer = transfers.find((t) => t.file === f.id && t.ms <= g.ms);
97770
+ if (g.role === "owner" || transfer && g.type === "user" && (g.email === transfer.to || g.email === f.owner && g.role === "writer")) continue;
97771
+ if (shares.some((s) => s.file === f.id && s.ms <= g.ms && s.type === g.type && s.role === g.role && (s.email ?? s.domain) === (g.email ?? g.domain))) continue;
97772
+ const grant = g.type === "user" && g.email ? { type: "user", email: g.email, role: g.role } : g.type === "domain" && typeof g.domain === "string" ? { type: "domain", domain: g.domain.toLowerCase(), role: g.role } : g.type === "anyone" ? { type: "anyone", role: g.role } : void 0;
97773
+ if (grant && ROLES.has(g.role) && !kept.some((k) => JSON.stringify(k) === JSON.stringify(grant))) kept.push(grant);
97774
+ else if (!grant || !ROLES.has(g.role)) dropped.push(`${g.type} ${g.role}`);
97775
+ }
97776
+ const created2 = offset16(f.createdTime), modified = offset16(f.modifiedTime);
97777
+ cx.note("observed", `seed.google-drive.files.${f.id}`, `"${f.name}", owned by ${f.owner}${kept.length ? `, ${kept.length} grant(s)` : ""}`, [f.span]);
97778
+ if (parent2 && !ids2.has(parent2)) cx.note("inferred", `seed.google-drive.files.${f.id}.parent`, `its folder (${parent2}) was never listed; the file sits at the top of ${f.owner}'s My Drive`);
97779
+ if (dropped.length) cx.note("missing", `seed.google-drive.files.${f.id}.permissions`, `left out: ${dropped.join(", ")}`);
97780
+ if (transfers.some((t) => t.file === f.id) && !(grants.get(f.id) ?? []).some((g) => g.ms < changedAt(f.id))) cx.note("inferred", `seed.google-drive.files.${f.id}.permissions`, "sharing read only after the agent handed the file over; a grant the new owner held before is not in the trace");
97781
+ return {
97782
+ id: f.id,
97783
+ name: f.name.slice(0, 255),
97784
+ mimeType: f.mimeType,
97785
+ ...parent2 && ids2.has(parent2) && { parent: parent2 },
97786
+ owner: f.owner,
97787
+ ...created2 && { created: created2 },
97788
+ ...modified && (!created2 || Date.parse(f.modifiedTime) >= Date.parse(f.createdTime)) && { modified },
97789
+ ...kept.length && { permissions: kept }
97790
+ };
97791
+ })
97792
+ };
97793
+ return { files: files2, transfers, me: me4 };
97794
+ }
97795
+ var FILE2, PERMISSIONS, ID4, EMAIL20, MIME2, ROLES;
97796
+ var init_google_drive2 = __esm({
97797
+ "cloud/rebuild/readers/google-drive.mjs"() {
97798
+ "use strict";
97799
+ FILE2 = /^\/drive\/v3\/files\/([^/]+)$/;
97800
+ PERMISSIONS = /^\/drive\/v3\/files\/([^/]+)\/permissions$/;
97801
+ ID4 = /^[A-Za-z0-9_-]{20,64}$/;
97802
+ EMAIL20 = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
97803
+ MIME2 = /^[a-z]+\/[A-Za-z0-9.+-]+$/;
97804
+ ROLES = /* @__PURE__ */ new Set(["reader", "commenter", "writer"]);
97450
97805
  }
97451
97806
  });
97452
97807
 
@@ -97789,6 +98144,41 @@ function proposeChecks(cx, { slack: slack2, datadog: datadog2, pagerduty }) {
97789
98144
  if (!cx.checks.length && !cx.seed.slack && cx.seed.gmail) add({ id: "no-trash", trace: { not_called: "POST /gmail/v1/users/*/messages/*/trash" } }, "nothing the trace suggests; a harmless default", verdict(!cx.calls("gmail", (c) => /\/trash$/.test(c.path)).length));
97790
98145
  if (!cx.checks.length && cx.seed.slack) add({ id: "no-deletes", trace: { not_called: "* /api/chat.delete" } }, "nothing the trace suggests; a harmless default", verdict(!cx.calls("slack", (c) => c.path === "/api/chat.delete").length));
97791
98146
  }
98147
+ function proposeAccessChecks(cx, { okta, drive: drive2, pagerduty, github: github2 }) {
98148
+ const add = (check4, detail2, production3) => {
98149
+ if (cx.checks.some((c) => c.id === check4.id)) return;
98150
+ cx.checks.push(check4);
98151
+ cx.production[check4.id] = production3;
98152
+ cx.note("inferred", `checks.${check4.id}`, detail2);
98153
+ };
98154
+ const slug13 = (text24) => String(text24).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
98155
+ for (const { key: key3, action, call: call3 } of okta?.changes ?? []) {
98156
+ if (action !== "deactivate" || call3.status >= 300) continue;
98157
+ const login2 = [...okta.users.values()].find((u) => u.user.id.toLowerCase() === key3 || u.login === key3)?.login;
98158
+ if (login2) add({ id: `okta-deactivated-${slug13(login2.split("@")[0])}`, state: { "okta.user": login2, status: "DEPROVISIONED" } }, `the agent deactivated ${login2} in Okta`, "passed");
98159
+ }
98160
+ const handed = [...new Set((drive2?.transfers ?? []).map((t) => t.file))];
98161
+ if (handed.length) add(
98162
+ { id: "drive-handed-over", trace: { called: handed.map((id12) => `POST /drive/v3/files/${id12}/permissions`) } },
98163
+ `the agent handed ${handed.length} Drive ${handed.length === 1 ? "file" : "files"} over to ${[...new Set(drive2.transfers.map((t) => t.to))].join(", ")}`,
98164
+ "passed"
98165
+ );
98166
+ for (const id12 of new Set((pagerduty?.overrides ?? []).map((o) => o.schedule))) {
98167
+ const name5 = pagerduty.schedules.get(id12)?.name ?? id12;
98168
+ add({ id: `oncall-covered-${slug13(name5)}`, trace: { called: `POST /schedules/${id12}/overrides` } }, `the agent put someone else on call in ${name5}`, "passed");
98169
+ }
98170
+ const removed = github2?.access?.removed ?? [], repos = (login2) => new Set(removed.filter((r) => r.login.toLowerCase() === login2.toLowerCase()).map((r) => r.full)).size;
98171
+ for (const r of removed) {
98172
+ const repo4 = github2.repos.get(r.full)?.ref, owner3 = r.full.split("/")[0];
98173
+ if (!repo4) continue;
98174
+ const member4 = github2.access.isMember(owner3, r.login), left = github2.access.left.some((l) => l.org === owner3 && l.login.toLowerCase() === r.login.toLowerCase());
98175
+ add(
98176
+ { id: `github-access-ended-${slug13(r.login)}${repos(r.login) > 1 ? `-${slug13(r.full.split("/")[1])}` : ""}`, state: { "github.permission": { repo: `$${repo4}`, user: `$${github2.access.refOf(r.login)}` }, is: "none" } },
98177
+ `the agent removed ${r.login}'s direct access to ${r.full}${member4 && !left ? `; still a member of ${owner3}, ${r.login} kept read access in production` : ""}`,
98178
+ left || member4 === false ? "passed" : member4 ? "failed" : "unknown"
98179
+ );
98180
+ }
98181
+ }
97792
98182
  var DEFAULT_TASK, isPayload, seconds3;
97793
98183
  var init_infer = __esm({
97794
98184
  "cloud/rebuild/infer.mjs"() {
@@ -100161,7 +100551,12 @@ function intakeOf(lines) {
100161
100551
  const calls2 = items.filter((i) => i.kind === "call"), inbound = items.filter((i) => i.kind === "inbound"), llm = records3.filter((r) => r.kind === "llm");
100162
100552
  const byService = /* @__PURE__ */ new Map();
100163
100553
  for (const c of calls2) byService.set(c.service, (byService.get(c.service) ?? 0) + 1);
100164
- const tools2 = [...byService].map(([service, n]) => ({ service, calls: n, rebuilt: REBUILT.includes(service) || Boolean(MAPS[service]) })).sort((a, b) => b.calls - a.calls);
100554
+ let seeded;
100555
+ try {
100556
+ seeded = new Set(Object.keys(rebuild(lines).scene.seed ?? {}));
100557
+ } catch {
100558
+ }
100559
+ const tools2 = [...byService].map(([service, n]) => ({ service, calls: n, rebuilt: seeded ? seeded.has(service) : REBUILT.includes(service) || Boolean(MAPS[service]) })).sort((a, b) => b.calls - a.calls);
100165
100560
  const bodies = calls2.filter((c) => c.response !== void 0).length;
100166
100561
  const content2 = llm.some((r) => r.input?.length);
100167
100562
  const toolCalls = records3.filter((r) => r.kind === "tool");
@@ -100184,11 +100579,14 @@ function intakeOf(lines) {
100184
100579
  }
100185
100580
  const unreplayable = toolCalls.filter((t) => t.result === void 0 && t.error === void 0).length;
100186
100581
  if (unreplayable) gaps2.push({ kind: "results", message: `${unreplayable} of ${toolCalls.length} tool calls came without their result, so a test cannot replay them: ${CONTENT_CAPTURE[header4.source] ?? CONTENT_CAPTURE.otlp}.` });
100187
- const cut = toolCalls.filter((t) => t.truncated).length;
100188
- if (cut) gaps2.push({ kind: "truncated", message: `${cut} tool ${cut === 1 ? "call was" : "calls were"} cut by the tracing SDK's length limit; the test replays ${cut === 1 ? "it" : "them"} as cut unless you answer the question about ${cut === 1 ? "it" : "them"}.` });
100582
+ const cut2 = toolCalls.filter((t) => t.truncated).length;
100583
+ if (cut2) gaps2.push({ kind: "truncated", message: `${cut2} tool ${cut2 === 1 ? "call was" : "calls were"} cut by the tracing SDK's length limit; the test replays ${cut2 === 1 ? "it" : "them"} as cut unless you answer the question about ${cut2 === 1 ? "it" : "them"}.` });
100189
100584
  if (calls2.length && bodies < calls2.length / 2) gaps2.push({ kind: "bodies", message: `${calls2.length - bodies} of ${calls2.length} API calls came without a response body, so Ancha can rebuild little more than their shape. Add the Ancha recorder next to your OpenTelemetry setup to send bodies.` });
100190
100585
  const unsupported34 = tools2.filter((t) => !t.rebuilt);
100191
- if (unsupported34.length) gaps2.push({ kind: "tools", message: `Not rebuilt yet: ${unsupported34.map((t) => t.service).join(", ")}. The test still holds the rest; calls to these tools are not part of it yet.` });
100586
+ if (unsupported34.length) {
100587
+ const names3 = unsupported34.map((t) => t.service), one7 = names3.length === 1;
100588
+ gaps2.push({ kind: "tools", message: `The test starts without ${names3.join(", ")}: the agent called ${one7 ? "it" : "them"} in production. Add ${names3.map((n) => `seed.${n}`).join(", ")} to scene.yaml to include ${one7 ? "it" : "them"} (\`ancha twins seed ${names3[0]}\` shows how).` });
100589
+ }
100192
100590
  if (toolCalls.length && !asked) gaps2.push({ kind: "input", message: "The trace doesn't hold what the agent was asked, so the test asks you. Record the invocation's input (the root span's input, or content capture)." });
100193
100591
  if (llm.length && !content2 && !asked) gaps2.push({ kind: "model", message: "Model calls came without their input, so Ancha cannot tell what the agent was told; the test asks you. Turn on GenAI content capture to send it." });
100194
100592
  if (header4.system_named_user && !header4.user) gaps2.push({ kind: "user", message: "The system prompt named someone, but Ancha never keeps prompts. If that is the signed-in user, set the user on the trace (Langfuse userId, LangSmith metadata user_id, or the user.id span attribute) so the test knows whose account it is." });
@@ -100213,7 +100611,8 @@ var init_intake = __esm({
100213
100611
  "use strict";
100214
100612
  init_ir();
100215
100613
  init_maps();
100216
- REBUILT = Object.freeze(["slack", "github", "datadog", "pagerduty"]);
100614
+ init_rebuild();
100615
+ REBUILT = Object.freeze(["slack", "github", "datadog", "pagerduty", "gmail", "okta", "google-drive"]);
100217
100616
  CONTENT_CAPTURE = {
100218
100617
  otlp: "turn on content capture (OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true; TRACELOOP_TRACE_CONTENT=true for OpenLLMetry; recordInputs and recordOutputs for the AI SDK)",
100219
100618
  langfuse: "trace the tools with the Langfuse callback handler, which records their output",
@@ -100270,8 +100669,8 @@ function readTools(cx, header4, records3, { examples: examples2 = [] } = {}) {
100270
100669
  ...definition3?.description && { description: definition3.description },
100271
100670
  ...definition3?.schema && { schema: definition3.schema }
100272
100671
  };
100273
- const errors3 = own2.filter((r) => r.error !== void 0).length, cut2 = own2.filter((r) => r.truncated).length;
100274
- cx.note("observed", `tools.${name5}`, `${own2.length} recorded ${own2.length === 1 ? "call" : "calls"}${errors3 ? `, ${errors3} with an error` : ""}${cut2 ? `, ${cut2} cut by the tracing SDK` : ""}${definition3 ? "; its description and arguments from the trace" : ""}`, own2.map((r) => r.id));
100672
+ const errors3 = own2.filter((r) => r.error !== void 0).length, cut3 = own2.filter((r) => r.truncated).length;
100673
+ cx.note("observed", `tools.${name5}`, `${own2.length} recorded ${own2.length === 1 ? "call" : "calls"}${errors3 ? `, ${errors3} with an error` : ""}${cut3 ? `, ${cut3} cut by the tracing SDK` : ""}${definition3 ? "; its description and arguments from the trace" : ""}`, own2.map((r) => r.id));
100275
100674
  if (write4) cx.note("inferred", `tools.${name5}.write`, "its name says it changes something, so each trial counts its calls");
100276
100675
  }
100277
100676
  const writes2 = names3.filter(isWrite), answer = cx.answers["tools.simulate_writes"], simulated = mcpTools(answer ?? "all", writes2);
@@ -100290,8 +100689,8 @@ function readTools(cx, header4, records3, { examples: examples2 = [] } = {}) {
100290
100689
  cx.ask("tools.mcp", `Which of these tools does your agent reach over MCP: ${names3.join(", ")}? A test serves those at {{tools.mcp_url}}. The others are the agent's own functions: the test answers them when the agent wraps them (wrapTools from @ancha-labs/tools, ancha.wrap_tools in Python).`, ["none", "all", names3.join(",")], 0, { type: "text" });
100291
100690
  if (mcp.size) cx.note("answered", "tools.mcp", `your answer: ${[...mcp].join(", ")} over MCP`);
100292
100691
  }
100293
- const cut = calls2.filter((r) => r.truncated).length;
100294
- if (cut) cx.ask("tools.truncated", `${cut} recorded ${cut === 1 ? "result was" : "results were"} cut by the tracing SDK's length limit. Should the test replay ${cut === 1 ? "it" : "them"} as cut?`, ["replay as cut", "fail those calls"], 0);
100692
+ const cut2 = calls2.filter((r) => r.truncated).length;
100693
+ if (cut2) cx.ask("tools.truncated", `${cut2} recorded ${cut2 === 1 ? "result was" : "results were"} cut by the tracing SDK's length limit. Should the test replay ${cut2 === 1 ? "it" : "them"} as cut?`, ["replay as cut", "fail those calls"], 0);
100295
100694
  const messages4 = header4?.input?.messages ?? (records3.find((r) => r.kind === "llm" && Array.isArray(r.input))?.input ?? []).map((m) => ({ role: m.role, content: m.content ?? m.text ?? null }));
100296
100695
  const task2 = typeof cx.answers.task === "string" && cx.answers.task.trim() ? cx.answers.task.trim() : [...messages4].reverse().find((m) => m.role === "user" && m.content)?.content;
100297
100696
  const trigger = { ...task2 && { task: task2 }, ...(messages4.length || header4?.user) && { input: { messages: messages4, ...header4?.user && { user: header4.user } } } };
@@ -100447,7 +100846,7 @@ function personByRule(transcript3) {
100447
100846
  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"
100448
100847
  });
100449
100848
  });
100450
- const emails = [...new Set(users4.flatMap((line2) => line2.content.match(EMAIL19) ?? []))];
100849
+ const emails = [...new Set(users4.flatMap((line2) => line2.content.match(EMAIL21) ?? []))];
100451
100850
  emails.forEach((email10, i) => facts.push({ id: `email_${i + 1}`, value: email10, about: "an email address you gave", match: "exact" }));
100452
100851
  return {
100453
100852
  goal: `Get the agent to sort out what you asked in your first message: ${users4[0]?.content ?? ""}`,
@@ -100486,11 +100885,11 @@ function placePerson(cx, person4, { agent, opener, userTurns }) {
100486
100885
  ...knows.length && { knows }
100487
100886
  }];
100488
100887
  }
100489
- var EMAIL19, norm, exactLike, tokens2, slug12;
100888
+ var EMAIL21, norm, exactLike, tokens2, slug12;
100490
100889
  var init_person = __esm({
100491
100890
  "cloud/rebuild/person.mjs"() {
100492
100891
  "use strict";
100493
- EMAIL19 = /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g;
100892
+ EMAIL21 = /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g;
100494
100893
  norm = (text24) => String(text24 ?? "").toLowerCase().replace(/\s+/g, " ").trim();
100495
100894
  exactLike = (fact2) => fact2.exact === true || fact2.match === "exact" || /[\d$€£¥]/.test(String(fact2.value ?? ""));
100496
100895
  tokens2 = (text24) => ` ${String(text24 ?? "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()} `;
@@ -100602,7 +101001,7 @@ function conversation2(list16) {
100602
101001
  messages4.push({ role: "tool", content: textOf4(m.output), tool_call_id: m.call_id });
100603
101002
  continue;
100604
101003
  }
100605
- const role3 = ROLES[m.role ?? m.type];
101004
+ const role3 = ROLES2[m.role ?? m.type];
100606
101005
  if (!role3) continue;
100607
101006
  if (role3 === "system") {
100608
101007
  system = true;
@@ -100650,11 +101049,11 @@ function unwrapResult(traced3, { lonelyOutput = false } = {}) {
100650
101049
  }
100651
101050
  return { result: value5 };
100652
101051
  }
100653
- var ROLES, textOf4;
101052
+ var ROLES2, textOf4;
100654
101053
  var init_messages = __esm({
100655
101054
  "cloud/rebuild/adapters/messages.mjs"() {
100656
101055
  "use strict";
100657
- ROLES = { human: "user", user: "user", ai: "assistant", assistant: "assistant", tool: "tool", function: "tool", system: "system", developer: "system" };
101056
+ ROLES2 = { human: "user", user: "user", ai: "assistant", assistant: "assistant", tool: "tool", function: "tool", system: "system", developer: "system" };
100658
101057
  textOf4 = (content2) => typeof content2 === "string" ? content2 : Array.isArray(content2) ? content2.map((p2) => typeof p2 === "string" ? p2 : p2?.type === "text" || p2?.type === "input_text" || p2?.type === "output_text" ? p2.text ?? p2.content ?? "" : "").join("") : content2 == null ? null : JSON.stringify(content2);
100659
101058
  }
100660
101059
  });
@@ -101229,13 +101628,14 @@ function rebuild(ir, { id: id12 = "rebuilt-from-trace", title, task: task2, answ
101229
101628
  const own2 = records3.some((r) => r.kind === "tool") || header4?.input?.messages?.length ? readTools(cx, header4, records3, { examples: examplesOf(examples2, Date.parse(header4?.started_at ?? records3.find((r) => r.t)?.t ?? 0), valuesOf2(records3.filter((r) => r.kind === "tool").map((r) => r.args))) }) : void 0;
101230
101629
  if (!cx.items.length && !own2) throw Object.assign(new Error("the trace has no tool calls, API calls or webhooks Ancha can read, and no input"), { code: "NO_CALLS" });
101231
101630
  task2 ??= own2?.trigger.task ?? inferTask(cx, records3);
101232
- const slack2 = readSlack(cx), github2 = readGitHub(cx), datadog2 = readDatadog(cx), pagerduty = readPagerDuty(cx);
101631
+ const slack2 = readSlack(cx), github2 = readGitHub(cx), datadog2 = readDatadog(cx), pagerduty = readPagerDuty(cx), okta = readOkta(cx), drive2 = readGoogleDrive(cx);
101233
101632
  readGmail(cx);
101234
101633
  readAppCalls(cx);
101235
101634
  inferIntegrations(cx, { slack: slack2, datadog: datadog2, pagerduty });
101236
101635
  inferPipelines(cx, github2);
101237
101636
  inferProblem(cx, { github: github2, datadog: datadog2 });
101238
101637
  proposeChecks(cx, { slack: slack2, datadog: datadog2, pagerduty });
101638
+ proposeAccessChecks(cx, { okta, drive: drive2, pagerduty, github: github2 });
101239
101639
  const read6 = new Set(cx.items.filter((i) => i.kind === "call").map((i) => i.service));
101240
101640
  const refersTo = (value5) => JSON.stringify(value5 ?? null).includes('"$');
101241
101641
  for (const service of read6) if (!cx.seed[service] && MAPS[service]) {
@@ -101338,6 +101738,8 @@ var init_rebuild = __esm({
101338
101738
  init_github();
101339
101739
  init_datadog();
101340
101740
  init_pagerduty();
101741
+ init_okta2();
101742
+ init_google_drive2();
101341
101743
  init_gmail2();
101342
101744
  init_infer();
101343
101745
  init_inverse();
@@ -119385,17 +119787,17 @@ function scheduleEntries(ctx, scheduleId) {
119385
119787
  function resolveEntries(seeded, overrides) {
119386
119788
  let entries2 = seeded.map((entry3) => ({ ...entry3 }));
119387
119789
  for (const override of overrides) {
119388
- const cut = [];
119790
+ const cut2 = [];
119389
119791
  for (const entry3 of entries2) {
119390
119792
  if (entry3.end_ms <= override.start_ms || override.end_ms <= entry3.start_ms) {
119391
- cut.push(entry3);
119793
+ cut2.push(entry3);
119392
119794
  continue;
119393
119795
  }
119394
- if (entry3.start_ms < override.start_ms) cut.push({ ...entry3, end_ms: override.start_ms });
119395
- if (override.end_ms < entry3.end_ms) cut.push({ ...entry3, start_ms: override.end_ms });
119796
+ if (entry3.start_ms < override.start_ms) cut2.push({ ...entry3, end_ms: override.start_ms });
119797
+ if (override.end_ms < entry3.end_ms) cut2.push({ ...entry3, start_ms: override.end_ms });
119396
119798
  }
119397
- cut.push({ schedule_id: override.schedule_id, user_id: override.user_id, start_ms: override.start_ms, end_ms: override.end_ms });
119398
- entries2 = cut;
119799
+ cut2.push({ schedule_id: override.schedule_id, user_id: override.user_id, start_ms: override.start_ms, end_ms: override.end_ms });
119800
+ entries2 = cut2;
119399
119801
  }
119400
119802
  return entries2.sort((a, b) => a.start_ms - b.start_ms);
119401
119803
  }
@@ -127745,10 +128147,10 @@ function quotedPrintable(text24) {
127745
128147
  encoded = encoded.replace(/ $/, "=20");
127746
128148
  const wrapped = [];
127747
128149
  while (encoded.length > 76) {
127748
- let cut = 75;
127749
- while (encoded[cut - 1] === "=" || encoded[cut - 2] === "=") cut--;
127750
- wrapped.push(encoded.slice(0, cut) + "=");
127751
- encoded = encoded.slice(cut);
128150
+ let cut2 = 75;
128151
+ while (encoded[cut2 - 1] === "=" || encoded[cut2 - 2] === "=") cut2--;
128152
+ wrapped.push(encoded.slice(0, cut2) + "=");
128153
+ encoded = encoded.slice(cut2);
127752
128154
  }
127753
128155
  wrapped.push(encoded);
127754
128156
  return wrapped.join("\r\n");
@@ -132840,13 +133242,14 @@ function removeMember(c) {
132840
133242
  });
132841
133243
  }
132842
133244
  var collaboratorRoutes = [
132843
- { method: "GET", path: "/repos/:owner/:repo/collaborators", coverage: partial3("Direct collaborators, members of the owning organization and the owning user (affiliation all); other affiliations and the permission filter are gaps."), handler: (c) => {
133245
+ { method: "GET", path: "/repos/:owner/:repo/collaborators", coverage: partial3("Everyone with access: direct collaborators, members of the owning organization and the owning user (affiliation all, the default); people with a direct grant (direct); people with a direct grant who are not members of the owning organization (outside)."), handler: (c) => {
132844
133246
  query2(c, ["page", "per_page", "affiliation", "permission"]);
132845
- const affiliation = c.req.query("affiliation");
132846
- if (affiliation !== void 0 && affiliation !== "all") unsupported(`affiliation ${affiliation}`);
133247
+ const affiliation = c.req.query("affiliation") ?? "all";
133248
+ if (!["all", "direct", "outside"].includes(affiliation)) throw new GitHubError(422, "Validation Failed", [{ resource: "Collaborator", field: "affiliation", code: "invalid" }]);
132847
133249
  if (c.req.query("permission") !== void 0) unsupported("query parameter permission");
132848
- const ctx = c.env.ctx, repo4 = repository(c);
132849
- return paginate(c, withAccess(ctx, repo4).map((entry3) => collaboratorShape(ctx, entry3.user, entry3.permission)));
133250
+ const ctx = c.env.ctx, repo4 = repository(c), org5 = getOrganization(ctx, repo4.owner);
133251
+ const listed = withAccess(ctx, repo4).filter(({ user: user8 }) => affiliation === "all" || directPermission(ctx, repo4.id, user8.id) !== void 0 && (affiliation === "direct" || org5 === void 0 || orgMembership(ctx, org5.id, user8.id) === void 0));
133252
+ return paginate(c, listed.map((entry3) => collaboratorShape(ctx, entry3.user, entry3.permission)));
132850
133253
  } },
132851
133254
  { method: "GET", path: "/repos/:owner/:repo/collaborators/:username", coverage: partial3("204 when the user has any access, otherwise 404."), handler: (c) => {
132852
133255
  query2(c, []);
@@ -134966,8 +135369,8 @@ function posterOf(ctx, userId) {
134966
135369
  function opening(text24, max = 48) {
134967
135370
  const flat2 = text24.replace(/\s+/g, " ").trim();
134968
135371
  if (flat2.length <= max) return flat2;
134969
- const cut = flat2.slice(0, max), space = cut.lastIndexOf(" ");
134970
- return `${(space > max * 0.6 ? cut.slice(0, space) : cut).replace(/[\s,.;:!?-]+$/, "")}\u2026`;
135372
+ const cut2 = flat2.slice(0, max), space = cut2.lastIndexOf(" ");
135373
+ return `${(space > max * 0.6 ? cut2.slice(0, space) : cut2).replace(/[\s,.;:!?-]+$/, "")}\u2026`;
134971
135374
  }
134972
135375
  function outcome2(passed, expected, actual) {
134973
135376
  return {
@@ -172854,8 +173257,8 @@ var GENERATOR = "ancha world gen";
172854
173257
  function slugify4(text24, max = 48) {
172855
173258
  const slug13 = text24.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "world";
172856
173259
  if (slug13.length <= max) return slug13;
172857
- const cut = slug13.slice(0, max + 1).lastIndexOf("-");
172858
- return slug13.slice(0, cut > 20 ? cut : max);
173260
+ const cut2 = slug13.slice(0, max + 1).lastIndexOf("-");
173261
+ return slug13.slice(0, cut2 > 20 ? cut2 : max);
172859
173262
  }
172860
173263
  var hours = (days, hour2 = 0) => `-${days * 24 + hour2}h`;
172861
173264
  function assembleWorld(input2) {
@@ -177582,7 +177985,7 @@ function redact2(data5, secrets2) {
177582
177985
  return text24 === before ? data5 : Buffer.from(text24, "utf8");
177583
177986
  }
177584
177987
  function logTail(data5, cap) {
177585
- const note2 = (cut) => Buffer.from(`[ancha: agent.log was ${data5.length} bytes; the first ${cut} bytes are left out]
177988
+ const note2 = (cut2) => Buffer.from(`[ancha: agent.log was ${data5.length} bytes; the first ${cut2} bytes are left out]
177586
177989
  `, "utf8");
177587
177990
  let start = data5.length - (cap - note2(data5.length).length);
177588
177991
  const newline = data5.indexOf(10, start);
@@ -177645,9 +178048,9 @@ function header3(path6, size, mtimeMs) {
177645
178048
  const block2 = Buffer.alloc(512);
177646
178049
  let name5 = path6, prefix2 = "";
177647
178050
  if (Buffer.byteLength(path6) > 100) {
177648
- const cut = path6.lastIndexOf("/");
177649
- [prefix2, name5] = [path6.slice(0, cut), path6.slice(cut + 1)];
177650
- if (cut < 0 || Buffer.byteLength(name5) > 100 || Buffer.byteLength(prefix2) > 155) throw new AnchaError("INTERNAL", `bundle path too long for ustar: ${path6}`);
178051
+ const cut2 = path6.lastIndexOf("/");
178052
+ [prefix2, name5] = [path6.slice(0, cut2), path6.slice(cut2 + 1)];
178053
+ if (cut2 < 0 || Buffer.byteLength(name5) > 100 || Buffer.byteLength(prefix2) > 155) throw new AnchaError("INTERNAL", `bundle path too long for ustar: ${path6}`);
177651
178054
  }
177652
178055
  const octal = (value5, width) => `${value5.toString(8).padStart(width - 1, "0")}\0`;
177653
178056
  block2.write(name5, 0, 100, "utf8");
@@ -177730,60 +178133,13 @@ function httpUrl2(value5) {
177730
178133
  }
177731
178134
 
177732
178135
  // packages/cli/src/reproduction.ts
177733
- import { readFile as readFile17 } from "node:fs/promises";
177734
- import { dirname as dirname10, join as join21, resolve as resolve18 } from "node:path";
177735
- async function reproductionOf(summary, scenePaths, cwd, runDir) {
177736
- const out = [];
177737
- const answers = runDir === void 0 ? [] : await toolAnswers(runDir, summary, {});
177738
- for (const scene2 of summary.scenes) {
177739
- const path6 = scenePaths[scene2.sceneId];
177740
- if (path6 === void 0) continue;
177741
- const production3 = await readFile17(join21(dirname10(resolve18(cwd, path6)), "production.json"), "utf8").then((text24) => JSON.parse(text24), () => void 0);
177742
- if (production3?.checks === void 0) continue;
177743
- const checks = Object.entries(production3.checks).flatMap(([check4, result]) => {
177744
- const here = scene2.checks[check4];
177745
- return here === void 0 ? [] : [{ check: check4, production: result, failed: here.total - here.passed, total: here.total }];
177746
- });
177747
- const failedThere = checks.filter((c) => c.production === "failed");
177748
- const verdict = failedThere.length > 0 ? failedThere.every((c) => c.failed * 2 > c.total) ? "reproduced" : failedThere.some((c) => c.failed > 0) ? "partly" : "not-reproduced" : checks.some((c) => c.production === "passed" && c.failed > 0) ? "differs" : checks.some((c) => c.production === "passed") ? "matches" : "unknown";
177749
- const added = Object.keys(scene2.checks).filter((check4) => !(check4 in production3.checks));
177750
- const counts = {};
177751
- for (const a of answers.filter((x) => x.scene === scene2.sceneId)) for (const [source, n] of Object.entries(a.counts)) counts[source] = (counts[source] ?? 0) + n;
177752
- out.push({ sceneId: scene2.sceneId, ...production3.trace !== void 0 && { trace: production3.trace }, verdict, checks, added, ...Object.keys(counts).length && { answers: counts } });
177753
- }
177754
- return out;
177755
- }
177756
- var SAY = {
177757
- reproduced: "production's failure happens here too",
177758
- partly: "production's failure happens here in part",
177759
- "not-reproduced": "production's failure did not happen here: the agent is fixed, or the world differs from production (see questions.json next to the scene)",
177760
- matches: "this run matches production, which passed these checks",
177761
- differs: "checks production passed failed here: a regression, or the world differs from production (see questions.json)",
177762
- unknown: "set OPENROUTER_API_KEY and run again: a model grades these checks on production's record and on this run"
177763
- };
177764
- function renderReproduction(reproductions) {
177765
- return reproductions.map((r) => {
177766
- const width = Math.max(...r.checks.map((c) => c.check.length));
177767
- const rows33 = r.checks.map((c) => ` ${c.check.padEnd(width)} ${c.production} in production \xB7 ${c.total === 0 ? "not run" : `failed ${c.failed}/${c.total} here`}`);
177768
- const also = r.verdict !== "differs" ? r.checks.filter((c) => c.production === "passed" && c.failed > 0).map((c) => c.check) : [];
177769
- return [
177770
- `compared with production${r.trace === void 0 ? "" : ` (trace ${r.trace.slice(0, 12)})`}: ${r.sceneId}`,
177771
- ...rows33,
177772
- `=> ${SAY[r.verdict]}`,
177773
- ...also.length > 0 ? [` also failing here, though production passed: ${also.join(", ")}`] : [],
177774
- // A failure here on a check production is not graded on yet is neither a match nor a regression: say how to grade both.
177775
- ...r.verdict !== "unknown" && r.checks.some((c) => c.production === "unknown" && c.failed > 0) ? [` set OPENROUTER_API_KEY to grade ${r.checks.filter((c) => c.production === "unknown" && c.failed > 0).map((c) => c.check).join(", ")} on production's record and here`] : [],
177776
- ...r.added.length > 0 ? [` checks added after saving, with no production result: ${r.added.join(", ")}`] : [],
177777
- // How much of the run stood on production's own answers (TRACE_PLAN_V2 §8.6).
177778
- ...r.answers ? [` answers to the agent's tools: ${["replayed", "replayed-elsewhere", "twin", "ran", "simulated", "failed"].filter((s) => r.answers[s]).map((s) => `${r.answers[s]} ${s}`).join(", ")}${r.answers.simulated ? "; simulated answers took the agent where production never went (ancha explain lists them)" : ""}`] : []
177779
- ].join("\n");
177780
- }).join("\n\n");
177781
- }
178136
+ import { readFile as readFile18 } from "node:fs/promises";
178137
+ import { dirname as dirname11, join as join22, resolve as resolve18 } from "node:path";
177782
178138
 
177783
178139
  // backend/src/production.ts
177784
178140
  import { createHash as createHash57 } from "node:crypto";
177785
- import { readFile as readFile18, writeFile as writeFile10 } from "node:fs/promises";
177786
- import { dirname as dirname11, join as join22 } from "node:path";
178141
+ import { readFile as readFile17, writeFile as writeFile10 } from "node:fs/promises";
178142
+ import { dirname as dirname10, join as join21 } from "node:path";
177787
178143
 
177788
178144
  // node_modules/.pnpm/openai@7.43.0_@aws-sdk+credential-provider-node@3.972.91_@smithy+signature-v4@5.7.5_undici@8.12.3_ws@8.22.0_zod@4.6.7/node_modules/openai/internal/tslib.mjs
177789
178145
  function __classPrivateFieldSet(receiver, state3, value5, kind, f) {
@@ -201118,12 +201474,12 @@ var agentAction = (entry3) => entry3.service === "tools" && entry3.path.startsWi
201118
201474
  var PRIVATE_KEY = /authorization|cookie|token|secret|password|api[_-]?key|app[_-]?key|routing[_-]?key|credential/i;
201119
201475
  var record21 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
201120
201476
  function judgeEvidence(capture4, secrets2 = [], asked, world5) {
201121
- const cut = /* @__PURE__ */ new Set();
201477
+ const cut2 = /* @__PURE__ */ new Set();
201122
201478
  const scrub = (raw3, part) => {
201123
201479
  let value5 = raw3;
201124
201480
  for (const secret of secrets2) if (secret !== "") value5 = value5.replaceAll(secret, "[redacted]");
201125
201481
  if (value5.length > MAX_STRING) {
201126
- cut.add(part);
201482
+ cut2.add(part);
201127
201483
  return `${value5.slice(0, MAX_STRING)}[truncated]`;
201128
201484
  }
201129
201485
  return value5;
@@ -201132,20 +201488,20 @@ function judgeEvidence(capture4, secrets2 = [], asked, world5) {
201132
201488
  if (typeof value5 === "string") return scrub(value5, part);
201133
201489
  if (value5 === null || typeof value5 === "boolean" || typeof value5 === "number") return value5;
201134
201490
  if (depth >= 5) {
201135
- cut.add(part);
201491
+ cut2.add(part);
201136
201492
  return "[truncated]";
201137
201493
  }
201138
201494
  if (Array.isArray(value5)) {
201139
- if (value5.length > 40) cut.add(part);
201495
+ if (value5.length > 40) cut2.add(part);
201140
201496
  return value5.slice(0, 40).map((v) => clean(v, part, depth + 1));
201141
201497
  }
201142
201498
  if (!record21(value5)) return void 0;
201143
201499
  const entries2 = Object.entries(value5).filter(([key3]) => !PRIVATE_KEY.test(key3));
201144
- if (entries2.length > 40) cut.add(part);
201500
+ if (entries2.length > 40) cut2.add(part);
201145
201501
  return Object.fromEntries(entries2.slice(0, 40).map(([key3, v]) => [scrub(key3, part), clean(v, part, depth + 1)]));
201146
201502
  };
201147
201503
  const native2 = capture4.trace.filter((entry3) => SERVICES.has(entry3.service) && !entry3.path.startsWith("/_ancha") || agentAction(entry3));
201148
- if (native2.length > MAX_ACTIONS) cut.add("calls");
201504
+ if (native2.length > MAX_ACTIONS) cut2.add("calls");
201149
201505
  const actions = native2.slice(-MAX_ACTIONS).map((entry3) => ({
201150
201506
  seq: entry3.seq,
201151
201507
  service: entry3.service,
@@ -201159,38 +201515,38 @@ function judgeEvidence(capture4, secrets2 = [], asked, world5) {
201159
201515
  }));
201160
201516
  const slack2 = record21(capture4.state) && record21(capture4.state.slack) ? capture4.state.slack : {};
201161
201517
  const rows33 = Array.isArray(slack2.messages) ? slack2.messages.filter(record21) : [];
201162
- if (rows33.length > MAX_MESSAGES) cut.add("messages");
201518
+ if (rows33.length > MAX_MESSAGES) cut2.add("messages");
201163
201519
  const messages4 = rows33.slice(-MAX_MESSAGES).map((row) => clean(Object.fromEntries(
201164
201520
  ["channel_id", "user_id", "ts", "thread_ts", "text"].filter((key3) => Object.hasOwn(row, key3)).map((key3) => [key3, row[key3]])
201165
201521
  ), "messages"));
201166
201522
  const channelRows = Array.isArray(slack2.channels) ? slack2.channels.filter(record21) : [];
201167
201523
  const userRows = Array.isArray(slack2.users) ? slack2.users.filter(record21) : [];
201168
201524
  const project11 = (rows34, fields11) => rows34.slice(0, 100).map((row) => clean(Object.fromEntries(fields11.filter((key3) => Object.hasOwn(row, key3)).map((key3) => [key3, row[key3]])), "payloads"));
201169
- if (channelRows.length > 100 || userRows.length > 100) cut.add("payloads");
201525
+ if (channelRows.length > 100 || userRows.length > 100) cut2.add("payloads");
201170
201526
  const channels = project11(channelRows, ["id", "name"]);
201171
201527
  const users4 = project11(userRows, ["id", "name", "is_bot"]);
201172
201528
  const invocation = asked === void 0 ? void 0 : clean(asked, "payloads");
201173
201529
  const facts = (world5 ?? []).slice(-MAX_ACTIONS).map((fact2) => clean(fact2, "payloads"));
201174
- const serialize = () => JSON.stringify({ truncated: cut.size > 0, ...invocation !== void 0 && { the_agent_was_asked: invocation }, ...facts.length && { what_production_read: facts }, actions, messages: messages4, channels, users: users4 });
201530
+ const serialize = () => JSON.stringify({ truncated: cut2.size > 0, ...invocation !== void 0 && { the_agent_was_asked: invocation }, ...facts.length && { what_production_read: facts }, actions, messages: messages4, channels, users: users4 });
201175
201531
  while (serialize().length > MAX_JSON) {
201176
201532
  if (actions.length > 0) {
201177
- cut.add("calls");
201533
+ cut2.add("calls");
201178
201534
  actions.shift();
201179
201535
  } else if (messages4.length > 0) {
201180
- cut.add("messages");
201536
+ cut2.add("messages");
201181
201537
  messages4.shift();
201182
201538
  } else if (facts.length > 0) {
201183
- cut.add("payloads");
201539
+ cut2.add("payloads");
201184
201540
  facts.shift();
201185
201541
  } else if (channels.length > 0) {
201186
- cut.add("payloads");
201542
+ cut2.add("payloads");
201187
201543
  channels.shift();
201188
201544
  } else {
201189
- cut.add("payloads");
201545
+ cut2.add("payloads");
201190
201546
  users4.shift();
201191
201547
  }
201192
201548
  }
201193
- return { json: serialize(), seqs: new Set(actions.map((action) => action.seq)), truncated: cut.size > 0, cut: [...cut].sort() };
201549
+ return { json: serialize(), seqs: new Set(actions.map((action) => action.seq)), truncated: cut2.size > 0, cut: [...cut2].sort() };
201194
201550
  }
201195
201551
 
201196
201552
  // backend/src/judge/index.ts
@@ -201210,7 +201566,7 @@ async function evaluateJudges(scene2, capture4, options3) {
201210
201566
  const evidence = judgeEvidence(capture4, key3 ? [key3] : [], scene2.trigger?.input, world5);
201211
201567
  const issues = [...capture4.harnessIssues];
201212
201568
  const evaluated = /* @__PURE__ */ new Map();
201213
- const cut = evidence.cut.length > 0 ? { evidenceCut: evidence.cut } : {};
201569
+ const cut2 = evidence.cut.length > 0 ? { evidenceCut: evidence.cut } : {};
201214
201570
  const warning = evidence.cut.includes("messages") ? "Judge evidence left out or shortened Slack messages (it keeps the last 100, up to 2048 characters each)." : void 0;
201215
201571
  for (const check4 of judges) {
201216
201572
  const base3 = { id: check4.id, required: required4.has(check4.id), passed: false, expected: check4.judge, evidence: [], judge: { model: model2 } };
@@ -201239,7 +201595,7 @@ async function evaluateJudges(scene2, capture4, options3) {
201239
201595
  explanation: reason2,
201240
201596
  evidence: grade2.evidence,
201241
201597
  ...warning !== void 0 && { warning },
201242
- judge: { model: model2, inputTokens: response5.usage?.prompt_tokens, outputTokens: response5.usage?.completion_tokens, ...cut }
201598
+ judge: { model: model2, inputTokens: response5.usage?.prompt_tokens, outputTokens: response5.usage?.completion_tokens, ...cut2 }
201243
201599
  });
201244
201600
  } catch {
201245
201601
  const error64 = options3.signal?.aborted ? "Judge evaluation cancelled." : "Judge evaluation failed: provider request or structured grade was invalid.";
@@ -201250,7 +201606,7 @@ async function evaluateJudges(scene2, capture4, options3) {
201250
201606
  explanation: error64,
201251
201607
  error: error64,
201252
201608
  ...warning !== void 0 && { warning },
201253
- judge: { model: model2, ...cut }
201609
+ judge: { model: model2, ...cut2 }
201254
201610
  });
201255
201611
  issues.push({ kind: "check", owner: "harness", service: "checks", message: `${check4.id}: ${error64}` });
201256
201612
  }
@@ -201288,13 +201644,17 @@ function productionTrace(lines) {
201288
201644
  if (invocation?.output !== void 0) entries2.push({ seq: ++seq2, tSim: "", tReal: 0, source: "agent", service: "agent", method: "POST", path: "/done", status: 200, request: { output: invocation.output } });
201289
201645
  return entries2;
201290
201646
  }
201647
+ async function productionRecord(dir2) {
201648
+ const text24 = await readFile17(join21(dir2, "production.jsonl"), "utf8").catch(() => void 0);
201649
+ return text24 === void 0 ? void 0 : productionTrace(text24.split("\n").filter(Boolean).map((line2) => JSON.parse(line2)));
201650
+ }
201291
201651
  async function completeProduction(scenePath, scene2, judge) {
201292
- const dir2 = dirname11(scenePath);
201293
- const text24 = await readFile18(join22(dir2, "production.jsonl"), "utf8").catch(() => void 0);
201652
+ const dir2 = dirname10(scenePath);
201653
+ const text24 = await readFile17(join21(dir2, "production.jsonl"), "utf8").catch(() => void 0);
201294
201654
  if (text24 === void 0) return [];
201295
201655
  const lines = text24.split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
201296
- const file3 = join22(dir2, "production.json");
201297
- const known2 = await readFile18(file3, "utf8").then((t) => JSON.parse(t), () => ({}));
201656
+ const file3 = join21(dir2, "production.json");
201657
+ const known2 = await readFile17(file3, "utf8").then((t) => JSON.parse(t), () => ({}));
201298
201658
  const checks = { ...known2.checks }, signatures = { ...known2.signatures };
201299
201659
  const sign2 = (check4) => createHash57("sha256").update(JSON.stringify(check4)).digest("hex").slice(0, 12);
201300
201660
  const missing6 = scene2.checks.filter((check4) => checks[check4.id] === void 0 || checks[check4.id] === "unknown" || signatures[check4.id] !== void 0 && signatures[check4.id] !== sign2(check4));
@@ -201323,6 +201683,80 @@ async function completeProduction(scenePath, scene2, judge) {
201323
201683
  return missing6.map((check4) => check4.id);
201324
201684
  }
201325
201685
 
201686
+ // packages/cli/src/reproduction.ts
201687
+ async function reproductionOf(summary, scenePaths, cwd, runDir, scenes = []) {
201688
+ const out = [];
201689
+ const answers = runDir === void 0 ? [] : await toolAnswers(runDir, summary, {});
201690
+ for (const scene2 of summary.scenes) {
201691
+ const path6 = scenePaths[scene2.sceneId];
201692
+ if (path6 === void 0) continue;
201693
+ const production3 = await readFile18(join22(dirname11(resolve18(cwd, path6)), "production.json"), "utf8").then((text24) => JSON.parse(text24), () => void 0);
201694
+ if (production3?.checks === void 0) continue;
201695
+ const checks = Object.entries(production3.checks).flatMap(([check4, result]) => {
201696
+ const here = scene2.checks[check4];
201697
+ return here === void 0 ? [] : [{ check: check4, production: result, failed: here.total - here.passed, total: here.total }];
201698
+ });
201699
+ const failedThere = checks.filter((c) => c.production === "failed");
201700
+ const verdict = failedThere.length > 0 ? failedThere.every((c) => c.failed * 2 > c.total) ? "reproduced" : failedThere.some((c) => c.failed > 0) ? "partly" : "not-reproduced" : checks.some((c) => c.production === "passed" && c.failed > 0) ? "differs" : checks.some((c) => c.production === "passed") ? "matches" : "unknown";
201701
+ const added = Object.keys(scene2.checks).filter((check4) => !(check4 in production3.checks));
201702
+ const counts = {};
201703
+ for (const a of answers.filter((x) => x.scene === scene2.sceneId)) for (const [source, n] of Object.entries(a.counts)) counts[source] = (counts[source] ?? 0) + n;
201704
+ const defined = scenes.find((s) => s.id === scene2.sceneId);
201705
+ const writes2 = defined === void 0 || runDir === void 0 || !writeTools(defined).size ? void 0 : await writesOf(defined, dirname11(resolve18(cwd, path6)), runDir, scene2);
201706
+ out.push({ sceneId: scene2.sceneId, ...production3.trace !== void 0 && { trace: production3.trace }, verdict, checks, added, ...Object.keys(counts).length && { answers: counts }, ...writes2 !== void 0 && { writes: writes2 } });
201707
+ }
201708
+ return out;
201709
+ }
201710
+ async function writesOf(scene2, dir2, runDir, ran) {
201711
+ const record23 = await productionRecord(dir2);
201712
+ if (record23 === void 0) return void 0;
201713
+ const made = /* @__PURE__ */ new Map(), here = /* @__PURE__ */ new Map();
201714
+ for (const action of actionsOf(scene2, record23)) made.set(action.tool, (made.get(action.tool) ?? 0) + 1);
201715
+ const trials = (ran.trialsDetail ?? []).filter((t) => t.valid !== false);
201716
+ for (const { trial } of trials) {
201717
+ const text24 = await readFile18(join22(runDir, `trial-${ran.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
201718
+ const trace = text24.split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
201719
+ for (const tool of new Set(actionsOf(scene2, trace).map((action) => action.tool))) here.set(tool, (here.get(tool) ?? 0) + 1);
201720
+ }
201721
+ const tools2 = [...made.keys(), ...[...here.keys()].filter((tool) => !made.has(tool)).sort()];
201722
+ return { of: trials.length, tools: tools2.map((tool) => ({ tool, production: made.get(tool) ?? 0, trials: here.get(tool) ?? 0 })) };
201723
+ }
201724
+ function renderWrites(writes2) {
201725
+ const of = `${writes2.of} ${writes2.of === 1 ? "trial" : "trials"}`;
201726
+ if (!writes2.tools.length) return [` writes compared with production: none in production, none in this run's ${of}`];
201727
+ const called = (n) => n === 0 ? "not called" : n === 1 ? "called" : `called ${n} times`;
201728
+ const width = Math.max(...writes2.tools.map((w) => w.tool.length)), said = Math.max(...writes2.tools.map((w) => called(w.production).length));
201729
+ return [" writes compared with production:", ...writes2.tools.map((w) => ` ${w.tool.padEnd(width)} production: ${called(w.production).padEnd(said)} this run: ${w.trials} of ${of}`)];
201730
+ }
201731
+ var SAY = {
201732
+ reproduced: "production's failure happens here too",
201733
+ partly: "production's failure happens here in part",
201734
+ "not-reproduced": "production's failure did not happen here: the agent is fixed, or the world differs from production (see questions.json next to the scene)",
201735
+ matches: "this run matches production, which passed these checks",
201736
+ differs: "checks production passed failed here: a regression, or the world differs from production (see questions.json)",
201737
+ unknown: "set OPENROUTER_API_KEY and run again: a model grades these checks on production's record and on this run"
201738
+ };
201739
+ function renderReproduction(reproductions) {
201740
+ return reproductions.map((r) => {
201741
+ const width = Math.max(...r.checks.map((c) => c.check.length));
201742
+ const rows33 = r.checks.map((c) => ` ${c.check.padEnd(width)} ${c.production} in production \xB7 ${c.total === 0 ? "not run" : `failed ${c.failed}/${c.total} here`}`);
201743
+ const also = r.verdict !== "differs" ? r.checks.filter((c) => c.production === "passed" && c.failed > 0).map((c) => c.check) : [];
201744
+ return [
201745
+ `compared with production${r.trace === void 0 ? "" : ` (trace ${r.trace.slice(0, 12)})`}: ${r.sceneId}`,
201746
+ ...rows33,
201747
+ `=> ${SAY[r.verdict]}`,
201748
+ ...also.length > 0 ? [` also failing here, though production passed: ${also.join(", ")}`] : [],
201749
+ // A failure here on a check production is not graded on yet is neither a match nor a regression: say how to grade both.
201750
+ ...r.verdict !== "unknown" && r.checks.some((c) => c.production === "unknown" && c.failed > 0) ? [` set OPENROUTER_API_KEY to grade ${r.checks.filter((c) => c.production === "unknown" && c.failed > 0).map((c) => c.check).join(", ")} on production's record and here`] : [],
201751
+ ...r.added.length > 0 ? [` checks added after saving, with no production result: ${r.added.join(", ")}`] : [],
201752
+ // How much of the run stood on production's own answers (TRACE_PLAN_V2 §8.6).
201753
+ ...r.answers ? [` answers to the agent's tools: ${["replayed", "replayed-elsewhere", "twin", "ran", "simulated", "failed"].filter((s) => r.answers[s]).map((s) => `${r.answers[s]} ${s}`).join(", ")}${r.answers.simulated ? "; simulated answers took the agent where production never went (ancha explain lists them)" : ""}`] : [],
201754
+ // What the agent changed, next to what production changed: an answer that needs no model (SPEC-020 R1).
201755
+ ...r.writes !== void 0 && r.writes.of > 0 ? renderWrites(r.writes) : []
201756
+ ].join("\n");
201757
+ }).join("\n\n");
201758
+ }
201759
+
201326
201760
  // backend/src/runner/run.ts
201327
201761
  init_src();
201328
201762
  import { randomInt } from "node:crypto";
@@ -203030,7 +203464,7 @@ async function executePreparedRun(ctx, input2, initial, ready2) {
203030
203464
  const upload3 = await uploadFinished(ctx, input2, summary.runId);
203031
203465
  await writer.finish({ state: "finished", exitCode: ctx.exitCode, ...upload3 !== void 0 && { upload: keptUpload(upload3, summary.runId) } });
203032
203466
  if (ctx.exitCode === EXIT_STRICT_GAP) ctx.out.info("--strict: the agent hit an endpoint Ancha does not implement (see coverage gaps)");
203033
- emitFinished(ctx, summary, input2.out, upload3, input2.uploadHint, await reproductionOf(summary, input2.scenePaths, ctx.io.cwd, join31(resolve23(ctx.io.cwd, input2.out ?? DEFAULT_RUNS_DIR), summary.runId)));
203467
+ emitFinished(ctx, summary, input2.out, upload3, input2.uploadHint, await reproductionOf(summary, input2.scenePaths, ctx.io.cwd, join31(resolve23(ctx.io.cwd, input2.out ?? DEFAULT_RUNS_DIR), summary.runId), input2.scenes));
203034
203468
  } catch (error64) {
203035
203469
  const code4 = toErrorJson(error64).code;
203036
203470
  const interrupted2 = error64 instanceof AnchaError && error64.code === "USAGE" && error64.message === "run interrupted";
@@ -203786,12 +204220,12 @@ function registerSimulate(sceneCommand, ctx) {
203786
204220
  }
203787
204221
 
203788
204222
  // packages/cli/src/kit/init.ts
203789
- var import_yaml13 = __toESM(require_dist(), 1);
203790
- init_src();
203791
204223
  import { constants as constants5 } from "node:fs";
203792
204224
  import { lstat as lstat6, mkdir as mkdir18, open as open5, readFile as readFile31, rm as rm9, writeFile as writeFile18 } from "node:fs/promises";
203793
204225
  import { join as join42 } from "node:path";
203794
204226
  import { Writable } from "node:stream";
204227
+ var import_yaml13 = __toESM(require_dist(), 1);
204228
+ init_src();
203795
204229
 
203796
204230
  // packages/cli/src/kit/seeds.ts
203797
204231
  var import_yaml9 = __toESM(require_dist(), 1);
@@ -204295,9 +204729,9 @@ function trim(twin, full2) {
204295
204729
  for (const path6 of lists(seed40)) {
204296
204730
  const list16 = at2(seed40, path6);
204297
204731
  if (!Array.isArray(list16) || list16.length <= KEEP) continue;
204298
- const cut = replaced(seed40, path6, list16.slice(0, KEEP));
204299
- if (valid(twin, cut)) {
204300
- seed40 = cut;
204732
+ const cut2 = replaced(seed40, path6, list16.slice(0, KEEP));
204733
+ if (valid(twin, cut2)) {
204734
+ seed40 = cut2;
204301
204735
  changed = true;
204302
204736
  continue;
204303
204737
  }
@@ -205025,7 +205459,7 @@ function registerTestNew(tests, ctx) {
205025
205459
  init_src();
205026
205460
  init_assets();
205027
205461
  import { readFile as readFile30 } from "node:fs/promises";
205028
- var DOC_TOPICS = ["setup", "apps", "run", "explain", "compare", "scenes", "integrations", "cloud", "playgrounds", "cli-quickstart", "tools"];
205462
+ var DOC_TOPICS = ["setup", "apps", "run", "traces", "explain", "compare", "scenes", "integrations", "cloud", "playgrounds", "cli-quickstart", "tools"];
205029
205463
  async function loadDoc(topic = "setup") {
205030
205464
  if (!DOC_TOPICS.includes(topic)) throw new AnchaError("USAGE", `unknown docs topic: ${topic}`, { hint: `available topics: ${DOC_TOPICS.join(", ")}` });
205031
205465
  return { topics: [...DOC_TOPICS], topic, markdown: await readFile30(new URL(`docs/${topic}.md`, assetRoot()), "utf8") };
@@ -205161,7 +205595,7 @@ async function addExampleSeeds(file3, twins) {
205161
205595
  return { added, skipped };
205162
205596
  }
205163
205597
  function registerKit(program2, ctx) {
205164
- program2.command("init").description("set up agent tests in this project: ancha.yaml, a starter scene for the tools it uses, coding-agent instructions; installs and runs nothing").option("--agent <command>", "the command that starts your agent (default: package.json scripts.start, a Procfile, pyproject.toml [project.scripts] or the Dockerfile CMD)").option("--template <template>", "starter or incidents", "starter").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) => {
205598
+ program2.command("init").description("set up agent tests in this project: ancha.yaml, a starter scene for the tools it uses, coding-agent instructions; installs and runs nothing").option("--agent <command>", "the command that starts your agent (default: package.json scripts.start, a Procfile, pyproject.toml [project.scripts] or the Dockerfile CMD)").option("--template <template>", "starter or incidents", "starter").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) => {
205165
205599
  if (opts.template !== "starter" && opts.template !== "incidents") throw new AnchaError("USAGE", `unknown template: ${opts.template}`, { hint: "available templates: starter, incidents" });
205166
205600
  if (opts.intent !== void 0 && !(ctx.io.env.ANCHA_PEOPLE_BASE_URL && ctx.io.env.ANCHA_PEOPLE_API_KEY) && (await modelAccess(ctx.io.env)).kind === "none") {
205167
205601
  throw new AnchaError("CONFIG_INVALID", "init --intent needs a model key", { hint: "set OPENROUTER_API_KEY, or log in to your workspace with ancha login; or run ancha init without --intent" });
@@ -205170,7 +205604,9 @@ function registerKit(program2, ctx) {
205170
205604
  const used = detection.sdks;
205171
205605
  const twins = used.length > 0 ? [...used] : [...STARTER_TWINS];
205172
205606
  const unchecked = twins.filter((twin) => !hasAccessCheck(twin));
205173
- const templates = opts.template === "starter" ? (await starterPack("starter", `Reach ${twins.map(toolName).join(", ")}`, twins)).filter((file3) => ["scene.yaml", "oracle.mjs", "null.mjs"].includes(file3.relativePath)) : await templateFiles(opts.template);
205607
+ const existing2 = opts.template === "starter" && command.getOptionValueSource("template") !== "cli" ? (await glob3("scenes/**/scene.yaml", { cwd: ctx.io.cwd, onlyFiles: true, followSymbolicLinks: false })).sort() : [];
205608
+ const starter = opts.template === "starter" && existing2.length === 0;
205609
+ const templates = existing2.length > 0 ? [] : opts.template === "starter" ? (await starterPack("starter", `Reach ${twins.map(toolName).join(", ")}`, twins)).filter((file3) => ["scene.yaml", "oracle.mjs", "null.mjs"].includes(file3.relativePath)) : await templateFiles(opts.template);
205174
205610
  const files2 = [
205175
205611
  { relativePath: "ancha.yaml", content: `${detection.agent === null ? "# Set agent.command to the command that starts your agent.\n" : (0, import_yaml13.stringify)({ agent: { command: detection.agent } })}scenes: [scenes/**/scene.yaml${opts.intent !== void 0 ? ", ancha/tests/*.yaml" : ""}]
205176
205612
  trials: 1
@@ -205204,14 +205640,15 @@ min_pass_rate: 1
205204
205640
  result.created.push(...world5.files, test3.file, test3.record);
205205
205641
  }
205206
205642
  const next2 = detection.agent === null ? ["set agent.command in ancha.yaml", "ancha run"] : generated ? [`ancha run ${generated.test.file} --json`] : ["ancha run"];
205207
- const output2 = { ...result, updated, detection, template: opts.template, ...opts.template === "starter" && { tools: twins, ...unchecked.length > 0 && { unchecked } }, ...generated, next: next2 };
205643
+ const output2 = { ...result, updated, detection, template: opts.template, ...starter && { tools: twins, ...unchecked.length > 0 && { unchecked } }, ...existing2.length > 0 && { scenes: existing2 }, ...generated, next: next2 };
205208
205644
  const agent = detection.agent === null ? "no start command found (package.json scripts.start, Procfile, pyproject.toml, Dockerfile)" : `${detection.agent}${detection.agentSource === "explicit" ? "" : ` (from ${detection.agentSource})`}`;
205209
205645
  const names3 = (list16) => list16.map(toolName).join(", ");
205210
205646
  ctx.out.result(output2, () => [
205211
205647
  `Created ${result.created.length} files; updated ${updated.length}; preserved ${result.skipped.length}.`,
205212
205648
  `agent: ${agent}`,
205213
- ...opts.template === "starter" ? [`starter: ${names3(twins)}${used.length > 0 ? "" : " (no tool SDK recognized in the dependencies)"}`] : [],
205214
- ...opts.template === "starter" && unchecked.length > 0 ? [` ${names3(unchecked)}: seeded; no access check, since ${unchecked.length === 1 ? "its" : "their"} requests need signing or a token exchange; add checks of your own`] : [],
205649
+ ...starter ? [`starter: ${names3(twins)}${used.length > 0 ? "" : " (no tool SDK recognized in the dependencies)"}`] : [],
205650
+ ...existing2.length > 0 ? [`scenes: ${existing2.length} already in scenes/ (${existing2.slice(0, 2).join(", ")}${existing2.length > 2 ? ", \u2026" : ""})${result.created.includes("ancha.yaml") ? "; ancha.yaml runs them" : ""}; ancha init --template starter adds the starter scene`] : [],
205651
+ ...starter && unchecked.length > 0 ? [` ${names3(unchecked)}: seeded; no access check, since ${unchecked.length === 1 ? "its" : "their"} requests need signing or a token exchange; add checks of your own`] : [],
205215
205652
  ...generated ? [`world: ${generated.world.file} (people: ${generated.world.people.join(", ") || "none"})`] : [],
205216
205653
  ...notGenerated?.added.length ? [` world gen populates ${gen_exports.GENERATED_TOOLS.join(", ")}; ${names3(notGenerated.added)} got ${notGenerated.added.length === 1 ? "its" : "their"} example data instead (ancha twins seed <tool> shows the fields)`] : [],
205217
205654
  ...notGenerated?.skipped.length ? [` ${names3(notGenerated.skipped)}: not in the world (the example data clashes with it); add a seed by hand (ancha twins seed <tool>)`] : [],
@@ -226710,7 +227147,7 @@ function registerTraces(program2, ctx) {
226710
227147
  lines.push(
226711
227148
  "what arrived:",
226712
227149
  ...agentToolLines(intake),
226713
- ...intake.tools.map((t) => ` ${t.service}: ${plural5(t.calls, "API call")}, ${t.rebuilt ? "rebuilt" : "not rebuilt yet"}`),
227150
+ ...intake.tools.map((t) => ` ${t.service}: ${plural5(t.calls, "API call")}, ${t.rebuilt ? "rebuilt" : "not rebuilt"}`),
226714
227151
  ...intake.inbound ? [` ${plural5(intake.inbound, "webhook")} the agent received`] : [],
226715
227152
  ...intake.llm ? [` ${plural5(intake.llm, "model call")}${intake.modelContent ? ", with what the agent was told" : ", without what the agent was told"}`] : [],
226716
227153
  ...intake.gaps.map((g) => ` note: ${g.message}`)
@@ -226933,6 +227370,8 @@ async function importLocally(ctx, source, options3) {
226933
227370
  if (m.made.production !== void 0 && Object.keys(m.made.production).length) await writeFile27(join55(dir2, "production.json"), `${JSON.stringify({ trace: m.made.summary.trace, checks: m.made.production }, null, 2)}
226934
227371
  `);
226935
227372
  await writeFile27(join55(dir2, "provenance.json"), `${JSON.stringify({ summary: m.made.summary, provenance: m.made.provenance, questions: m.made.questions, ...all8.length > 1 && { conversation: { id: m.conversation.id, traces: m.conversation.traces } } }, null, 2)}
227373
+ `);
227374
+ await writeFile27(join55(dir2, "questions.json"), `${JSON.stringify(m.made.questions, null, 2)}
226936
227375
  `);
226937
227376
  await loadSceneFile(path6);
226938
227377
  }