@ancha-labs/cli 0.4.2 → 0.4.4

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) {
@@ -43959,16 +43959,33 @@ function toolDataView(tool, raw3) {
43959
43959
  add("Channels", state3.channels, (r) => ({ "Channel": text10(r.name), "ID": text10(r.id) }));
43960
43960
  add("Messages", state3.messages, (r) => ({ "Channel": text10(where2(r.channel_id)), "From": text10(who2(r.user_id)), "Message": text10(r.text), "Time": text10(r.ts) }));
43961
43961
  } else if (tool === "github") {
43962
+ const login2 = (id12) => list(state3.users).find((u) => u.id === id12)?.login ?? id12;
43962
43963
  add("Repositories", state3.repos, (r) => ({ "Repository": text10(r.full_name), "Branch": text10(r.default_branch), "ID": text10(r.id) }));
43963
43964
  add("Pull requests", state3.pulls, (r) => ({ "Number": text10(r.number), "State": text10(r.state), "Merged": text10(r.merged), "Title": text10(list(state3.issues).find((i) => i.repo_id === r.repo_id && i.number === r.number)?.title) }));
43964
43965
  add("Commits", state3.commits, (r) => ({ "Message": text10(r.commit?.message), "SHA": text10(r.sha) }));
43966
+ add("People", state3.users, (r) => ({ "Login": text10(r.login), "Name": text10(r.name), "Email": text10(r.email) }));
43967
+ add("Organization members", state3.org_members, (r) => ({ "Organization": text10(list(state3.organizations).find((o) => o.id === r.org_id)?.login ?? r.org_id), "Person": text10(login2(r.user_id)), "Role": text10(r.role) }));
43968
+ add("Repository access", state3.collaborators, (r) => ({ "Repository": text10(list(state3.repos).find((p2) => p2.id === r.repo_id)?.full_name ?? r.repo_id), "Person": text10(login2(r.user_id)), "Permission": text10(r.permission) }));
43965
43969
  } else if (tool === "datadog") {
43966
43970
  add("Monitors", state3.monitors, (r) => ({ "Monitor": text10(r.name), "Status": text10(r.overall_state), "Query": text10(r.query) }));
43967
43971
  add("Logs", state3.logs, (r) => ({ "Time": text10(r.at), "Service": text10(r.service), "Status": text10(r.status), "Message": text10(r.message) }));
43968
43972
  } else if (tool === "pagerduty") {
43973
+ const person4 = (id12) => list(state3.users).find((u) => u.id === id12)?.name ?? id12;
43974
+ const schedule3 = (id12) => list(state3.schedules).find((s) => s.id === id12)?.name ?? id12;
43975
+ const time7 = (ms3) => typeof ms3 === "number" && Number.isFinite(ms3) ? new Date(ms3).toISOString().replace(".000Z", "Z") : "\u2014";
43976
+ const targets = (json32) => {
43977
+ try {
43978
+ return list(JSON.parse(String(json32))).map((t) => t.type === "schedule_reference" ? schedule3(t.id) : person4(t.id)).join(", ") || "\u2014";
43979
+ } catch {
43980
+ return "\u2014";
43981
+ }
43982
+ };
43969
43983
  add("Incidents", state3.incidents, (r) => ({ "Incident": text10(r.title), "Status": text10(r.status), "ID": text10(r.id) }));
43970
43984
  add("Services", state3.services, (r) => ({ "Service": text10(r.name), "ID": text10(r.id) }));
43971
43985
  add("People", state3.users, (r) => ({ "Name": text10(r.name), "Email": text10(r.email) }));
43986
+ add("On-call schedule", state3.schedule_entries, (r) => ({ "Schedule": text10(schedule3(r.schedule_id)), "On call": text10(person4(r.user_id)), "From": time7(r.start_ms), "Until": time7(r.end_ms) }));
43987
+ add("Overrides", state3.overrides, (r) => ({ "Schedule": text10(schedule3(r.schedule_id)), "On call": text10(person4(r.user_id)), "From": time7(r.start_ms), "Until": time7(r.end_ms) }));
43988
+ add("Escalation policies", state3.escalation_rules, (r) => ({ "Policy": text10(list(state3.escalation_policies).find((p2) => p2.id === r.policy_id)?.name ?? r.policy_id), "Level": text10(r.level), "Notifies": targets(r.targets_json) }));
43972
43989
  } else if (tool === "linkedin-ads") {
43973
43990
  add("Campaigns", state3.campaigns, (r) => ({ "Campaign": text10(r.name), "Status": text10(r.status), "Daily budget": money6(r.dailyBudget), "Total budget": money6(r.totalBudget), "ID": text10(r.id) }));
43974
43991
  add("Ad accounts", state3.accounts, (r) => ({ "Account": text10(r.name), "Status": text10(r.status), "Currency": text10(r.currency), "ID": text10(r.id) }));
@@ -96979,11 +96996,18 @@ var require_x509_transport_state = __commonJS({
96979
96996
 
96980
96997
  // cloud/rebuild/ir.mjs
96981
96998
  function serviceOf(url3) {
96999
+ let u;
96982
97000
  try {
96983
- return HOSTS.get(new URL(url3).host);
97001
+ u = new URL(url3);
96984
97002
  } catch {
96985
97003
  return void 0;
96986
97004
  }
97005
+ return HOSTS.get(u.host) ?? serviceByRule(u);
97006
+ }
97007
+ function serviceByRule(u) {
97008
+ if (/^[a-z0-9-]+\.(?:okta|oktapreview|okta-emea)\.com$/i.test(u.hostname)) return "okta";
97009
+ if (u.hostname === "www.googleapis.com" && /^\/(?:upload\/)?drive\//.test(u.pathname)) return "google-drive";
97010
+ return void 0;
96987
97011
  }
96988
97012
  function parseIr(text24) {
96989
97013
  const lines = String(text24).split("\n").filter((line2) => line2.trim());
@@ -97032,6 +97056,7 @@ function itemsOf(records3) {
97032
97056
  ms: Date.parse(r.t),
97033
97057
  service,
97034
97058
  method: String(r.method ?? "GET").toUpperCase(),
97059
+ host: url3.host,
97035
97060
  path: url3.pathname,
97036
97061
  query: query11,
97037
97062
  status: r.response?.status,
@@ -97285,6 +97310,7 @@ function readGitHub(cx) {
97285
97310
  return logins.get(login2);
97286
97311
  };
97287
97312
  if (agentLogin) loginRef(agentLogin);
97313
+ const access8 = readAccess(cx, repos, loginRef);
97288
97314
  cx.seed.github = { repos: [] };
97289
97315
  for (const repo4 of repos.values()) {
97290
97316
  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 +97362,84 @@ function readGitHub(cx) {
97336
97362
  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
97363
  repo4.history = history3;
97338
97364
  }
97365
+ for (const seeded of cx.seed.github.repos) {
97366
+ const grants = [...access8.grants.get(seeded.name)?.entries() ?? []];
97367
+ if (grants.length) seeded.collaborators = grants.map(([login2, g]) => ({ user: `$${loginRef(login2)}`, permission: g.permission }));
97368
+ }
97369
+ if (access8.orgs.length) cx.seed.github.orgs = access8.orgs;
97339
97370
  cx.seed.github.users = [...logins].map(([login2, ref20]) => ({ ref: ref20, login: login2 }));
97340
97371
  if (agentLogin) cx.seed.github.bot = `$${logins.get(agentLogin)}`;
97341
- return { repos, merged };
97372
+ return { repos, merged, access: access8 };
97373
+ }
97374
+ function readAccess(cx, repos, loginRef) {
97375
+ const grants = /* @__PURE__ */ new Map(), removed = [], members4 = /* @__PURE__ */ new Map(), left = [];
97376
+ const grant = (full2, login2, permission6, how, span2) => {
97377
+ const list16 = grants.get(full2) ?? /* @__PURE__ */ new Map();
97378
+ if (!list16.has(login2)) list16.set(login2, { permission: permission6, how, span: span2 });
97379
+ grants.set(full2, list16);
97380
+ };
97381
+ const membership = (org5, login2, member4, how, span2) => {
97382
+ const list16 = members4.get(org5) ?? /* @__PURE__ */ new Map();
97383
+ if (!list16.has(login2)) list16.set(login2, { member: member4, how, span: span2 });
97384
+ members4.set(org5, list16);
97385
+ };
97386
+ const calls2 = cx.calls("github", (c) => c.status < 300 || c.status === 404);
97387
+ 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));
97388
+ for (const c of calls2) {
97389
+ const repo4 = c.path.match(/^\/repos\/([^/]+\/[^/]+)\/collaborators(?:\/([^/]+))?$/), org5 = c.path.match(/^\/orgs\/([^/]+)\/(members|memberships)(?:\/([^/]+))?$/);
97390
+ if (repo4 && !repo4[2] && c.method === "GET" && c.status < 300 && ["direct", "outside"].includes(c.query.affiliation) && Array.isArray(c.response)) {
97391
+ 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);
97392
+ }
97393
+ if (repo4?.[2] && c.method === "DELETE" && c.status < 300) removed.push({ full: repo4[1], login: decodeURIComponent(repo4[2]), ms: c.ms, span: c.id });
97394
+ if (!org5) continue;
97395
+ const login2 = org5[3] && decodeURIComponent(org5[3]);
97396
+ if (c.method === "DELETE" && login2 && c.status < 300) left.push({ org: org5[1], login: login2, ms: c.ms, span: c.id });
97397
+ if (c.method !== "GET" || login2 && c.ms >= changedAt(`/orgs/${org5[1]}/`, login2)) continue;
97398
+ if (login2 && org5[2] === "members") membership(org5[1], login2, c.status < 300, "observed", c.id);
97399
+ 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);
97400
+ if (!login2 && org5[2] === "members" && Array.isArray(c.response)) {
97401
+ for (const u of c.response) if (u?.login) membership(org5[1], u.login, "member", "observed", c.id);
97402
+ }
97403
+ }
97404
+ for (const r of removed) if (!grants.get(r.full)?.has(r.login)) {
97405
+ grant(r.full, r.login, "write", "inferred", r.span);
97406
+ 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]);
97407
+ }
97408
+ 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]);
97409
+ for (const l of left) membership(l.org, l.login, "member", "inferred", l.span);
97410
+ for (const owner3 of new Set(removed.map((r) => r.full.split("/")[0]))) {
97411
+ const unread = removed.filter((r) => r.full.startsWith(`${owner3}/`) && !members4.get(owner3)?.has(r.login));
97412
+ if (!unread.length) continue;
97413
+ const id12 = `github.members.${owner3}`, answer = cx.answers[id12];
97414
+ const people3 = [...new Set(unread.map((r) => r.login))].join(", "), where2 = [...new Set(unread.map((r) => r.full))].join(", ");
97415
+ 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" });
97416
+ if (typeof answer !== "string") continue;
97417
+ const named3 = /^\s*none\s*$/i.test(answer) ? [] : answer.split(/[\s,]+/).filter(Boolean);
97418
+ for (const login2 of named3) membership(owner3, login2, "member", "answered");
97419
+ for (const r of unread) if (!named3.some((n) => n.toLowerCase() === r.login.toLowerCase())) membership(owner3, r.login, false, "answered");
97420
+ cx.note("answered", `seed.github.orgs.${owner3}.members`, `your answer: ${named3.length ? named3.join(", ") : "none"}`);
97421
+ }
97422
+ 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]);
97423
+ const isMember3 = (org5, login2) => {
97424
+ const m = [...members4.get(org5)?.entries() ?? []].find(([l]) => l.toLowerCase() === login2.toLowerCase())?.[1];
97425
+ return m === void 0 ? void 0 : Boolean(m.member);
97426
+ };
97427
+ return {
97428
+ grants,
97429
+ removed,
97430
+ left,
97431
+ isMember: isMember3,
97432
+ refOf: loginRef,
97433
+ 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)
97434
+ };
97342
97435
  }
97343
- var decode5;
97436
+ var decode5, ROLE, permissionOf2;
97344
97437
  var init_github = __esm({
97345
97438
  "cloud/rebuild/readers/github.mjs"() {
97346
97439
  "use strict";
97347
97440
  decode5 = (b64) => Buffer.from(String(b64).replace(/\n/g, ""), "base64").toString("utf8");
97441
+ ROLE = { read: "read", triage: "read", write: "write", maintain: "write", admin: "admin" };
97442
+ permissionOf2 = (c) => ROLE[c?.role_name] ?? (c?.permissions?.admin ? "admin" : c?.permissions?.push ? "write" : c?.permissions?.pull ? "read" : void 0);
97348
97443
  }
97349
97444
  });
97350
97445
 
@@ -97414,15 +97509,50 @@ var init_datadog = __esm({
97414
97509
 
97415
97510
  // cloud/rebuild/readers/pagerduty.mjs
97416
97511
  function readPagerDuty(cx) {
97417
- const users4 = /* @__PURE__ */ new Map(), services2 = /* @__PURE__ */ new Map(), incidents = /* @__PURE__ */ new Map();
97512
+ const users4 = /* @__PURE__ */ new Map(), services2 = /* @__PURE__ */ new Map(), incidents = /* @__PURE__ */ new Map(), schedules = /* @__PURE__ */ new Map(), refs = /* @__PURE__ */ new Map();
97513
+ const overrides = [];
97418
97514
  let actor2;
97515
+ const schedule3 = (id12, name5) => {
97516
+ if (!schedules.has(id12)) schedules.set(id12, { id: id12, name: name5, read: [] });
97517
+ const s = schedules.get(id12);
97518
+ s.name ??= name5;
97519
+ return s;
97520
+ };
97419
97521
  for (const c of cx.calls("pagerduty")) {
97420
97522
  if (c.method === "GET" && c.path === "/users") for (const u of c.response?.users ?? []) users4.set(u.id, { ...u, span: c.id });
97523
+ 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
97524
  if (c.method === "GET" && c.path === "/services") for (const s of c.response?.services ?? []) services2.set(s.id, { ...s, span: c.id });
97422
97525
  if (c.method === "GET" && c.path === "/incidents") for (const inc of c.response?.incidents ?? []) incidents.set(inc.id, inc);
97423
97526
  if (c.method === "PUT" && /^\/incidents\/\w+$/.test(c.path)) actor2 ??= c.response?.incident?.acknowledgements?.[0]?.acknowledger?.id;
97527
+ const override = c.method === "POST" && c.status < 300 && OVERRIDES.exec(c.path);
97528
+ if (override) for (const o of c.request?.overrides ?? (c.request?.override ? [c.request.override] : [])) {
97529
+ const start = Date.parse(o?.start), end = Date.parse(o?.end);
97530
+ if (start < end) overrides.push({ schedule: override[1], start, end, user: o.user?.id, ms: c.ms, span: c.id });
97531
+ }
97532
+ const entry3 = (s, e, span2) => ({ user: e.user?.id, start: Date.parse(e.start), end: Date.parse(e.end), ms: c.ms, span: span2 });
97533
+ if (c.method === "GET" && c.path === "/oncalls") for (const o of c.response?.oncalls ?? []) {
97534
+ if (o?.user?.id) refs.set(o.user.id, o.user.summary);
97535
+ if (!o?.schedule?.id || !o.start || !o.end) continue;
97536
+ const s = schedule3(o.schedule.id, o.schedule.summary);
97537
+ s.read.push(entry3(s, o, c.id));
97538
+ if (o.escalation_policy?.id) s.policy ??= { id: o.escalation_policy.id, name: o.escalation_policy.summary };
97539
+ }
97540
+ const one7 = c.method === "GET" && SCHEDULE.exec(c.path), detail2 = one7 && c.response?.schedule;
97541
+ if (detail2?.id) {
97542
+ const s = schedule3(detail2.id, detail2.name ?? detail2.summary);
97543
+ for (const u of detail2.users ?? []) if (u?.id) refs.set(u.id, u.summary);
97544
+ for (const e of detail2.final_schedule?.rendered_schedule_entries ?? []) if (e?.user?.id) {
97545
+ refs.set(e.user.id, e.user.summary);
97546
+ s.read.push(entry3(s, e, c.id));
97547
+ }
97548
+ if (detail2.escalation_policies?.[0]?.id) s.policy ??= { id: detail2.escalation_policies[0].id, name: detail2.escalation_policies[0].summary };
97549
+ }
97550
+ }
97551
+ if (!users4.size || !services2.size && !schedules.size) return void 0;
97552
+ for (const [id12, name5] of refs) if (!users4.has(id12) && name5) {
97553
+ users4.set(id12, { id: id12, name: name5, email: `${String(name5).toLowerCase().replace(/[^a-z0-9]+/g, ".").replace(/^\.|\.$/g, "") || id12.toLowerCase()}@pagerduty.invalid` });
97554
+ cx.note("missing", `seed.pagerduty.users.${id12}.email`, `${name5} was on call but never looked up, so the address is a placeholder`);
97424
97555
  }
97425
- if (!services2.size || !users4.size) return void 0;
97426
97556
  const userRef4 = new Map([...users4.values()].map((u) => [u.id, cx.ref(`pd_${u.name}`)]));
97427
97557
  const policies = /* @__PURE__ */ new Map();
97428
97558
  for (const s of services2.values()) {
@@ -97433,20 +97563,262 @@ function readPagerDuty(cx) {
97433
97563
  }
97434
97564
  s.ref = cx.ref(`service_${s.name}`);
97435
97565
  }
97566
+ const fromIncidents = policies.size;
97567
+ const seeded = [];
97568
+ for (const s of schedules.values()) {
97569
+ const mine = overrides.filter((o) => o.schedule === s.id);
97570
+ const first = Math.min(...mine.map((o) => o.ms));
97571
+ 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]));
97572
+ const entries2 = [...before];
97573
+ for (const e of after) entries2.push(...before.reduce((pieces, b) => pieces.flatMap((p2) => cut(p2, b)), [e]));
97574
+ 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);
97575
+ if (!unique3.length) continue;
97576
+ s.ref = cx.ref(`schedule_${s.name ?? s.id}`);
97577
+ 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() })) });
97578
+ 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))]);
97579
+ const covered = mine.filter((o) => !before.some((b) => b.start <= o.start && b.end >= o.end));
97580
+ 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`);
97581
+ if (s.policy && !policies.has(s.policy.id)) {
97582
+ 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}`] }] });
97583
+ 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)`);
97584
+ }
97585
+ }
97586
+ if (!policies.size) {
97587
+ const target5 = seeded[0]?.ref ?? userRef4.get(actor2 ?? [...users4.keys()][0]);
97588
+ policies.set("stand-in", { ref: cx.ref("policy_stand_in"), name: "Default", levels: [{ targets: [`$${target5}`] }] });
97589
+ cx.note("missing", "seed.pagerduty.escalation_policies", "no escalation policy was read; one stand-in level");
97590
+ }
97591
+ const kept = [...services2.values()].filter((s) => s.escalation_policy);
97592
+ const standIn = !kept.length && [...policies.values()][0];
97593
+ 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
97594
  cx.seed.pagerduty = {
97437
- users: [...users4.values()].map((u) => ({ ref: userRef4.get(u.id), id: u.id, name: u.name, email: u.email })),
97595
+ 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
97596
  ...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}` }))
97597
+ ...seeded.length && { schedules: seeded },
97598
+ escalation_policies: [...policies.values()].map(({ id: id12, ...p2 }) => ({ ref: p2.ref, ...PD_ID.test(id12 ?? "") && { id: id12 }, ...p2 })),
97599
+ 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
97600
  };
97442
- for (const u of users4.values()) cx.note("observed", `seed.pagerduty.users.${userRef4.get(u.id)}`, `${u.name} (${u.id})`, [u.span]);
97601
+ 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
97602
  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 };
97603
+ if (fromIncidents) cx.note("inferred", "seed.pagerduty.escalation_policies", "one level targeting whoever the incidents were assigned to (policies were never read)");
97604
+ return { users: users4, services: services2, incidents, actor: actor2, schedules, overrides };
97446
97605
  }
97606
+ var PD_ID, OVERRIDES, SCHEDULE, cut;
97447
97607
  var init_pagerduty = __esm({
97448
97608
  "cloud/rebuild/readers/pagerduty.mjs"() {
97449
97609
  "use strict";
97610
+ PD_ID = /^P[A-Z0-9]{6}$/;
97611
+ OVERRIDES = /^\/schedules\/(\w+)\/overrides$/;
97612
+ SCHEDULE = /^\/schedules\/(\w+)$/;
97613
+ cut = (entry3, window5) => [
97614
+ ...entry3.start < window5.start ? [{ ...entry3, end: Math.min(entry3.end, window5.start) }] : [],
97615
+ ...entry3.end > window5.end ? [{ ...entry3, start: Math.max(entry3.start, window5.end) }] : []
97616
+ ].filter((e) => e.start < e.end);
97617
+ }
97618
+ });
97619
+
97620
+ // cloud/rebuild/readers/okta.mjs
97621
+ function readOkta(cx) {
97622
+ const calls2 = cx.calls("okta", (c) => c.status < 300);
97623
+ const changes = [], firstChange = /* @__PURE__ */ new Map();
97624
+ for (const c of calls2) {
97625
+ const m = c.method === "GET" ? null : CHANGE.exec(c.path);
97626
+ if (!m || c.method === "POST" && m[2] === void 0 && !c.request) continue;
97627
+ const key3 = decodeURIComponent(m[1]).toLowerCase(), action = c.method === "DELETE" ? "delete" : m[2] ?? "update";
97628
+ changes.push({ key: key3, action, call: c });
97629
+ if (!firstChange.has(key3)) firstChange.set(key3, c.ms);
97630
+ }
97631
+ const seen = /* @__PURE__ */ new Map();
97632
+ let me4;
97633
+ for (const c of calls2) {
97634
+ const one7 = c.method === "GET" && USER.exec(c.path), list16 = c.method === "GET" && c.path === "/api/v1/users";
97635
+ if (!one7 && !list16) continue;
97636
+ for (const u of list16 ? Array.isArray(c.response) ? c.response : [] : c.response?.id ? [c.response] : []) {
97637
+ const login2 = typeof u?.profile?.login === "string" ? u.profile.login.toLowerCase() : void 0;
97638
+ if (!u?.id || !login2 || !EMAIL19.test(login2)) continue;
97639
+ const before = c.ms < Math.min(firstChange.get(u.id.toLowerCase()) ?? Infinity, firstChange.get(login2) ?? Infinity);
97640
+ if (!seen.has(u.id) || before && !seen.get(u.id).before) seen.set(u.id, { user: u, login: login2, span: c.id, before });
97641
+ if (one7 && decodeURIComponent(one7[1]).toLowerCase() === "me") me4 = u.id;
97642
+ }
97643
+ }
97644
+ if (!seen.size) return void 0;
97645
+ const offset16 = (t) => {
97646
+ const ms3 = Date.parse(t ?? "");
97647
+ return Number.isFinite(ms3) && ms3 <= cx.start ? cx.dur(ms3 - cx.start) : void 0;
97648
+ };
97649
+ const loginOf = new Map([...seen.values()].map((s) => [s.user.id, s.login]));
97650
+ const name5 = (value5, fallback) => typeof value5 === "string" && value5.trim() ? value5.trim().slice(0, 50) : fallback;
97651
+ const users4 = [...seen.values()].map(({ user: u, login: login2, span: span2, before }) => {
97652
+ const p2 = u.profile, [first, ...rest] = login2.split("@")[0].split(/[._-]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1));
97653
+ let status5 = STATUSES3.has(u.status) ? u.status : "ACTIVE";
97654
+ if (!before) {
97655
+ const change = changes.find((ch) => ch.key === u.id.toLowerCase() || ch.key === login2);
97656
+ status5 = BEFORE[change?.action] ?? status5;
97657
+ cx.note("inferred", `seed.okta.users.${login2}.status`, `read only after the agent's ${change?.action ?? "change"}; ${status5} before it`, [span2]);
97658
+ } else cx.note("observed", `seed.okta.users.${login2}`, `${login2}, ${status5}`, [span2]);
97659
+ const created2 = offset16(u.created), changed = before ? offset16(u.statusChanged) : void 0, lastLogin = offset16(u.lastLogin);
97660
+ const manager = p2.managerId ? loginOf.get(p2.managerId) : void 0;
97661
+ if (p2.managerId && !manager) cx.note("missing", `seed.okta.users.${login2}.manager`, `the manager's record (${p2.managerId}) was never read`);
97662
+ return {
97663
+ login: login2,
97664
+ ...typeof p2.email === "string" && p2.email.toLowerCase() !== login2 && EMAIL19.test(p2.email) && { email: p2.email.toLowerCase() },
97665
+ firstName: name5(p2.firstName, first ?? "Unknown"),
97666
+ lastName: name5(p2.lastName, rest.join(" ") || "Unknown"),
97667
+ status: status5,
97668
+ ...created2 && { created: created2 },
97669
+ ...changed && (!created2 || Date.parse(u.statusChanged) >= Date.parse(u.created)) && { statusChanged: changed },
97670
+ ...lastLogin && { lastLogin },
97671
+ ...typeof p2.title === "string" && p2.title && { title: p2.title.slice(0, 100) },
97672
+ ...typeof p2.department === "string" && p2.department && { department: p2.department.slice(0, 100) },
97673
+ ...manager && manager !== login2 && { manager }
97674
+ };
97675
+ });
97676
+ let admin = me4 && loginOf.get(me4);
97677
+ if (admin && users4.find((u) => u.login === admin)?.status !== "ACTIVE") admin = void 0;
97678
+ const domain2 = users4[0].login.split("@")[1];
97679
+ if (!admin) {
97680
+ admin = `okta-admin@${domain2}`;
97681
+ if (!users4.some((u) => u.login === admin)) users4.unshift({ login: admin, firstName: "Okta", lastName: "Admin", status: "ACTIVE" });
97682
+ 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`);
97683
+ }
97684
+ const host = calls2.find((c) => c.host)?.host ?? "";
97685
+ 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");
97686
+ if (!/\.okta/i.test(host)) cx.note("inferred", "seed.okta.org", `the agent's Okta host (${host}) names no org; named after ${domain2}`);
97687
+ cx.seed.okta = { org: { subdomain: subdomain2, name: subdomain2[0].toUpperCase() + subdomain2.slice(1) }, admin, users: users4 };
97688
+ return { users: seen, changes };
97689
+ }
97690
+ var USER, CHANGE, BEFORE, STATUSES3, EMAIL19;
97691
+ var init_okta2 = __esm({
97692
+ "cloud/rebuild/readers/okta.mjs"() {
97693
+ "use strict";
97694
+ USER = /^\/api\/v1\/users\/([^/]+)$/;
97695
+ CHANGE = /^\/api\/v1\/users\/([^/]+)(?:\/lifecycle\/([a-z_]+))?$/;
97696
+ BEFORE = { deactivate: "ACTIVE", suspend: "ACTIVE", unsuspend: "SUSPENDED", unlock: "LOCKED_OUT", activate: "STAGED", delete: "ACTIVE" };
97697
+ STATUSES3 = /* @__PURE__ */ new Set(["STAGED", "PROVISIONED", "ACTIVE", "RECOVERY", "PASSWORD_EXPIRED", "LOCKED_OUT", "SUSPENDED", "DEPROVISIONED"]);
97698
+ EMAIL19 = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
97699
+ }
97700
+ });
97701
+
97702
+ // cloud/rebuild/readers/google-drive.mjs
97703
+ function readGoogleDrive(cx) {
97704
+ const calls2 = cx.calls("google-drive", (c) => c.status < 300);
97705
+ const names3 = /* @__PURE__ */ new Map();
97706
+ const person4 = (email10, displayName) => {
97707
+ if (typeof email10 !== "string" || !EMAIL20.test(email10)) return void 0;
97708
+ const key3 = email10.toLowerCase();
97709
+ if (typeof displayName === "string" && displayName.trim() && !names3.get(key3)) names3.set(key3, displayName.trim().slice(0, 200));
97710
+ else if (!names3.has(key3)) names3.set(key3, void 0);
97711
+ return key3;
97712
+ };
97713
+ const transfers = [], shares = [];
97714
+ for (const c of calls2) {
97715
+ const m = c.method === "POST" && PERMISSIONS.exec(c.path);
97716
+ if (!m || !c.request || typeof c.request !== "object") continue;
97717
+ const to = person4(c.request.emailAddress);
97718
+ if (c.request.role === "owner" && String(c.query?.transferOwnership) === "true" && to) transfers.push({ file: m[1], to, ms: c.ms, span: c.id });
97719
+ else shares.push({ file: m[1], type: c.request.type, role: c.request.role, email: to, domain: c.request.domain, ms: c.ms });
97720
+ }
97721
+ 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));
97722
+ const files2 = /* @__PURE__ */ new Map(), grants = /* @__PURE__ */ new Map();
97723
+ let me4, meSpan;
97724
+ for (const c of calls2) {
97725
+ if (c.method !== "GET") continue;
97726
+ if (c.path === "/drive/v3/about" && !me4) {
97727
+ me4 = person4(c.response?.user?.emailAddress, c.response?.user?.displayName);
97728
+ meSpan = c.id;
97729
+ }
97730
+ 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] : []) {
97731
+ if (!f?.id) continue;
97732
+ const owner3 = person4(f.owners?.[0]?.emailAddress, f.owners?.[0]?.displayName), before = c.ms < changedAt(f.id), had = files2.get(f.id);
97733
+ if (!had || before && !had.before) files2.set(f.id, { ...had, ...f, owner: before ? owner3 : had?.owner, before, span: c.id });
97734
+ }
97735
+ const m = PERMISSIONS.exec(c.path);
97736
+ if (!m) continue;
97737
+ const list16 = grants.get(m[1]) ?? [];
97738
+ 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 });
97739
+ grants.set(m[1], list16);
97740
+ }
97741
+ if (!files2.size) return void 0;
97742
+ const handed = transfers.map((t) => files2.get(t.file)?.owner).filter(Boolean);
97743
+ if (!me4 && handed.length) {
97744
+ me4 = handed[0];
97745
+ 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}`);
97746
+ }
97747
+ if (!me4) {
97748
+ me4 = [...files2.values()].map((f) => f.owner).find(Boolean);
97749
+ cx.note("missing", "seed.google-drive.me", `the account the agent used never showed (it never read /about); ${me4} stands in`);
97750
+ } else if (meSpan) cx.note("observed", "seed.google-drive.me", me4, [meSpan]);
97751
+ if (!me4) return void 0;
97752
+ for (const f of files2.values()) if (!f.owner && transfers.some((t) => t.file === f.id)) {
97753
+ f.owner = me4;
97754
+ cx.note("inferred", `seed.google-drive.files.${f.id}.owner`, `read only after the handover; the agent, acting as ${me4}, owned it before`);
97755
+ }
97756
+ const offset16 = (t) => {
97757
+ const ms3 = Date.parse(t ?? "");
97758
+ return Number.isFinite(ms3) && ms3 <= cx.start ? cx.dur(ms3 - cx.start) : void 0;
97759
+ };
97760
+ const seeded = [...files2.values()].filter((f) => {
97761
+ const ok = ID4.test(f.id) && typeof f.name === "string" && f.name && typeof f.mimeType === "string" && MIME2.test(f.mimeType) && f.owner;
97762
+ 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]);
97763
+ return ok;
97764
+ });
97765
+ const ids2 = new Set(seeded.map((f) => f.id));
97766
+ const ordered2 = [], placed = /* @__PURE__ */ new Set();
97767
+ const place2 = (f) => {
97768
+ if (placed.has(f.id)) return;
97769
+ placed.add(f.id);
97770
+ const parent2 = seeded.find((p2) => p2.id === f.parents?.[0]);
97771
+ if (parent2) place2(parent2);
97772
+ ordered2.push(f);
97773
+ };
97774
+ seeded.forEach(place2);
97775
+ cx.seed["google-drive"] = {
97776
+ domain: me4.split("@")[1],
97777
+ me: me4,
97778
+ users: [.../* @__PURE__ */ new Set([me4, ...names3.keys()])].map((email10) => {
97779
+ const name5 = names3.get(email10) ?? email10.split("@")[0].split(/[._-]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join(" ");
97780
+ if (!names3.get(email10)) cx.note("inferred", `seed.google-drive.users.${email10}`, `no name in the trace; "${name5}" from the address`);
97781
+ return { email: email10, name: name5 };
97782
+ }),
97783
+ files: ordered2.map((f) => {
97784
+ const parent2 = f.parents?.[0], kept = [], dropped = [];
97785
+ for (const g of grants.get(f.id) ?? []) {
97786
+ const transfer = transfers.find((t) => t.file === f.id && t.ms <= g.ms);
97787
+ if (g.role === "owner" || transfer && g.type === "user" && (g.email === transfer.to || g.email === f.owner && g.role === "writer")) continue;
97788
+ 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;
97789
+ 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;
97790
+ if (grant && ROLES.has(g.role) && !kept.some((k) => JSON.stringify(k) === JSON.stringify(grant))) kept.push(grant);
97791
+ else if (!grant || !ROLES.has(g.role)) dropped.push(`${g.type} ${g.role}`);
97792
+ }
97793
+ const created2 = offset16(f.createdTime), modified = offset16(f.modifiedTime);
97794
+ cx.note("observed", `seed.google-drive.files.${f.id}`, `"${f.name}", owned by ${f.owner}${kept.length ? `, ${kept.length} grant(s)` : ""}`, [f.span]);
97795
+ 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`);
97796
+ if (dropped.length) cx.note("missing", `seed.google-drive.files.${f.id}.permissions`, `left out: ${dropped.join(", ")}`);
97797
+ 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");
97798
+ return {
97799
+ id: f.id,
97800
+ name: f.name.slice(0, 255),
97801
+ mimeType: f.mimeType,
97802
+ ...parent2 && ids2.has(parent2) && { parent: parent2 },
97803
+ owner: f.owner,
97804
+ ...created2 && { created: created2 },
97805
+ ...modified && (!created2 || Date.parse(f.modifiedTime) >= Date.parse(f.createdTime)) && { modified },
97806
+ ...kept.length && { permissions: kept }
97807
+ };
97808
+ })
97809
+ };
97810
+ return { files: files2, transfers, me: me4 };
97811
+ }
97812
+ var FILE2, PERMISSIONS, ID4, EMAIL20, MIME2, ROLES;
97813
+ var init_google_drive2 = __esm({
97814
+ "cloud/rebuild/readers/google-drive.mjs"() {
97815
+ "use strict";
97816
+ FILE2 = /^\/drive\/v3\/files\/([^/]+)$/;
97817
+ PERMISSIONS = /^\/drive\/v3\/files\/([^/]+)\/permissions$/;
97818
+ ID4 = /^[A-Za-z0-9_-]{20,64}$/;
97819
+ EMAIL20 = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
97820
+ MIME2 = /^[a-z]+\/[A-Za-z0-9.+-]+$/;
97821
+ ROLES = /* @__PURE__ */ new Set(["reader", "commenter", "writer"]);
97450
97822
  }
97451
97823
  });
97452
97824
 
@@ -97789,6 +98161,41 @@ function proposeChecks(cx, { slack: slack2, datadog: datadog2, pagerduty }) {
97789
98161
  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
98162
  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
98163
  }
98164
+ function proposeAccessChecks(cx, { okta, drive: drive2, pagerduty, github: github2 }) {
98165
+ const add = (check4, detail2, production3) => {
98166
+ if (cx.checks.some((c) => c.id === check4.id)) return;
98167
+ cx.checks.push(check4);
98168
+ cx.production[check4.id] = production3;
98169
+ cx.note("inferred", `checks.${check4.id}`, detail2);
98170
+ };
98171
+ const slug13 = (text24) => String(text24).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
98172
+ for (const { key: key3, action, call: call3 } of okta?.changes ?? []) {
98173
+ if (action !== "deactivate" || call3.status >= 300) continue;
98174
+ const login2 = [...okta.users.values()].find((u) => u.user.id.toLowerCase() === key3 || u.login === key3)?.login;
98175
+ if (login2) add({ id: `okta-deactivated-${slug13(login2.split("@")[0])}`, state: { "okta.user": login2, status: "DEPROVISIONED" } }, `the agent deactivated ${login2} in Okta`, "passed");
98176
+ }
98177
+ const handed = [...new Set((drive2?.transfers ?? []).map((t) => t.file))];
98178
+ if (handed.length) add(
98179
+ { id: "drive-handed-over", trace: { called: handed.map((id12) => `POST /drive/v3/files/${id12}/permissions`) } },
98180
+ `the agent handed ${handed.length} Drive ${handed.length === 1 ? "file" : "files"} over to ${[...new Set(drive2.transfers.map((t) => t.to))].join(", ")}`,
98181
+ "passed"
98182
+ );
98183
+ for (const id12 of new Set((pagerduty?.overrides ?? []).map((o) => o.schedule))) {
98184
+ const name5 = pagerduty.schedules.get(id12)?.name ?? id12;
98185
+ add({ id: `oncall-covered-${slug13(name5)}`, trace: { called: `POST /schedules/${id12}/overrides` } }, `the agent put someone else on call in ${name5}`, "passed");
98186
+ }
98187
+ const removed = github2?.access?.removed ?? [], repos = (login2) => new Set(removed.filter((r) => r.login.toLowerCase() === login2.toLowerCase()).map((r) => r.full)).size;
98188
+ for (const r of removed) {
98189
+ const repo4 = github2.repos.get(r.full)?.ref, owner3 = r.full.split("/")[0];
98190
+ if (!repo4) continue;
98191
+ const member4 = github2.access.isMember(owner3, r.login), left = github2.access.left.some((l) => l.org === owner3 && l.login.toLowerCase() === r.login.toLowerCase());
98192
+ add(
98193
+ { 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" } },
98194
+ `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` : ""}`,
98195
+ left || member4 === false ? "passed" : member4 ? "failed" : "unknown"
98196
+ );
98197
+ }
98198
+ }
97792
98199
  var DEFAULT_TASK, isPayload, seconds3;
97793
98200
  var init_infer = __esm({
97794
98201
  "cloud/rebuild/infer.mjs"() {
@@ -100161,7 +100568,12 @@ function intakeOf(lines) {
100161
100568
  const calls2 = items.filter((i) => i.kind === "call"), inbound = items.filter((i) => i.kind === "inbound"), llm = records3.filter((r) => r.kind === "llm");
100162
100569
  const byService = /* @__PURE__ */ new Map();
100163
100570
  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);
100571
+ let seeded;
100572
+ try {
100573
+ seeded = new Set(Object.keys(rebuild(lines).scene.seed ?? {}));
100574
+ } catch {
100575
+ }
100576
+ 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
100577
  const bodies = calls2.filter((c) => c.response !== void 0).length;
100166
100578
  const content2 = llm.some((r) => r.input?.length);
100167
100579
  const toolCalls = records3.filter((r) => r.kind === "tool");
@@ -100184,11 +100596,14 @@ function intakeOf(lines) {
100184
100596
  }
100185
100597
  const unreplayable = toolCalls.filter((t) => t.result === void 0 && t.error === void 0).length;
100186
100598
  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"}.` });
100599
+ const cut2 = toolCalls.filter((t) => t.truncated).length;
100600
+ 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
100601
  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
100602
  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.` });
100603
+ if (unsupported34.length) {
100604
+ const names3 = unsupported34.map((t) => t.service), one7 = names3.length === 1;
100605
+ 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).` });
100606
+ }
100192
100607
  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
100608
  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
100609
  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 +100628,8 @@ var init_intake = __esm({
100213
100628
  "use strict";
100214
100629
  init_ir();
100215
100630
  init_maps();
100216
- REBUILT = Object.freeze(["slack", "github", "datadog", "pagerduty"]);
100631
+ init_rebuild();
100632
+ REBUILT = Object.freeze(["slack", "github", "datadog", "pagerduty", "gmail", "okta", "google-drive"]);
100217
100633
  CONTENT_CAPTURE = {
100218
100634
  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
100635
  langfuse: "trace the tools with the Langfuse callback handler, which records their output",
@@ -100270,8 +100686,8 @@ function readTools(cx, header4, records3, { examples: examples2 = [] } = {}) {
100270
100686
  ...definition3?.description && { description: definition3.description },
100271
100687
  ...definition3?.schema && { schema: definition3.schema }
100272
100688
  };
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));
100689
+ const errors3 = own2.filter((r) => r.error !== void 0).length, cut3 = own2.filter((r) => r.truncated).length;
100690
+ 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
100691
  if (write4) cx.note("inferred", `tools.${name5}.write`, "its name says it changes something, so each trial counts its calls");
100276
100692
  }
100277
100693
  const writes2 = names3.filter(isWrite), answer = cx.answers["tools.simulate_writes"], simulated = mcpTools(answer ?? "all", writes2);
@@ -100290,8 +100706,8 @@ function readTools(cx, header4, records3, { examples: examples2 = [] } = {}) {
100290
100706
  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
100707
  if (mcp.size) cx.note("answered", "tools.mcp", `your answer: ${[...mcp].join(", ")} over MCP`);
100292
100708
  }
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);
100709
+ const cut2 = calls2.filter((r) => r.truncated).length;
100710
+ 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
100711
  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
100712
  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
100713
  const trigger = { ...task2 && { task: task2 }, ...(messages4.length || header4?.user) && { input: { messages: messages4, ...header4?.user && { user: header4.user } } } };
@@ -100447,7 +100863,7 @@ function personByRule(transcript3) {
100447
100863
  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
100864
  });
100449
100865
  });
100450
- const emails = [...new Set(users4.flatMap((line2) => line2.content.match(EMAIL19) ?? []))];
100866
+ const emails = [...new Set(users4.flatMap((line2) => line2.content.match(EMAIL21) ?? []))];
100451
100867
  emails.forEach((email10, i) => facts.push({ id: `email_${i + 1}`, value: email10, about: "an email address you gave", match: "exact" }));
100452
100868
  return {
100453
100869
  goal: `Get the agent to sort out what you asked in your first message: ${users4[0]?.content ?? ""}`,
@@ -100486,11 +100902,11 @@ function placePerson(cx, person4, { agent, opener, userTurns }) {
100486
100902
  ...knows.length && { knows }
100487
100903
  }];
100488
100904
  }
100489
- var EMAIL19, norm, exactLike, tokens2, slug12;
100905
+ var EMAIL21, norm, exactLike, tokens2, slug12;
100490
100906
  var init_person = __esm({
100491
100907
  "cloud/rebuild/person.mjs"() {
100492
100908
  "use strict";
100493
- EMAIL19 = /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g;
100909
+ EMAIL21 = /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g;
100494
100910
  norm = (text24) => String(text24 ?? "").toLowerCase().replace(/\s+/g, " ").trim();
100495
100911
  exactLike = (fact2) => fact2.exact === true || fact2.match === "exact" || /[\d$€£¥]/.test(String(fact2.value ?? ""));
100496
100912
  tokens2 = (text24) => ` ${String(text24 ?? "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()} `;
@@ -100602,7 +101018,7 @@ function conversation2(list16) {
100602
101018
  messages4.push({ role: "tool", content: textOf4(m.output), tool_call_id: m.call_id });
100603
101019
  continue;
100604
101020
  }
100605
- const role3 = ROLES[m.role ?? m.type];
101021
+ const role3 = ROLES2[m.role ?? m.type];
100606
101022
  if (!role3) continue;
100607
101023
  if (role3 === "system") {
100608
101024
  system = true;
@@ -100650,11 +101066,11 @@ function unwrapResult(traced3, { lonelyOutput = false } = {}) {
100650
101066
  }
100651
101067
  return { result: value5 };
100652
101068
  }
100653
- var ROLES, textOf4;
101069
+ var ROLES2, textOf4;
100654
101070
  var init_messages = __esm({
100655
101071
  "cloud/rebuild/adapters/messages.mjs"() {
100656
101072
  "use strict";
100657
- ROLES = { human: "user", user: "user", ai: "assistant", assistant: "assistant", tool: "tool", function: "tool", system: "system", developer: "system" };
101073
+ ROLES2 = { human: "user", user: "user", ai: "assistant", assistant: "assistant", tool: "tool", function: "tool", system: "system", developer: "system" };
100658
101074
  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
101075
  }
100660
101076
  });
@@ -101229,13 +101645,14 @@ function rebuild(ir, { id: id12 = "rebuilt-from-trace", title, task: task2, answ
101229
101645
  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
101646
  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
101647
  task2 ??= own2?.trigger.task ?? inferTask(cx, records3);
101232
- const slack2 = readSlack(cx), github2 = readGitHub(cx), datadog2 = readDatadog(cx), pagerduty = readPagerDuty(cx);
101648
+ const slack2 = readSlack(cx), github2 = readGitHub(cx), datadog2 = readDatadog(cx), pagerduty = readPagerDuty(cx), okta = readOkta(cx), drive2 = readGoogleDrive(cx);
101233
101649
  readGmail(cx);
101234
101650
  readAppCalls(cx);
101235
101651
  inferIntegrations(cx, { slack: slack2, datadog: datadog2, pagerduty });
101236
101652
  inferPipelines(cx, github2);
101237
101653
  inferProblem(cx, { github: github2, datadog: datadog2 });
101238
101654
  proposeChecks(cx, { slack: slack2, datadog: datadog2, pagerduty });
101655
+ proposeAccessChecks(cx, { okta, drive: drive2, pagerduty, github: github2 });
101239
101656
  const read6 = new Set(cx.items.filter((i) => i.kind === "call").map((i) => i.service));
101240
101657
  const refersTo = (value5) => JSON.stringify(value5 ?? null).includes('"$');
101241
101658
  for (const service of read6) if (!cx.seed[service] && MAPS[service]) {
@@ -101338,6 +101755,8 @@ var init_rebuild = __esm({
101338
101755
  init_github();
101339
101756
  init_datadog();
101340
101757
  init_pagerduty();
101758
+ init_okta2();
101759
+ init_google_drive2();
101341
101760
  init_gmail2();
101342
101761
  init_infer();
101343
101762
  init_inverse();
@@ -119385,17 +119804,17 @@ function scheduleEntries(ctx, scheduleId) {
119385
119804
  function resolveEntries(seeded, overrides) {
119386
119805
  let entries2 = seeded.map((entry3) => ({ ...entry3 }));
119387
119806
  for (const override of overrides) {
119388
- const cut = [];
119807
+ const cut2 = [];
119389
119808
  for (const entry3 of entries2) {
119390
119809
  if (entry3.end_ms <= override.start_ms || override.end_ms <= entry3.start_ms) {
119391
- cut.push(entry3);
119810
+ cut2.push(entry3);
119392
119811
  continue;
119393
119812
  }
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 });
119813
+ if (entry3.start_ms < override.start_ms) cut2.push({ ...entry3, end_ms: override.start_ms });
119814
+ if (override.end_ms < entry3.end_ms) cut2.push({ ...entry3, start_ms: override.end_ms });
119396
119815
  }
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;
119816
+ cut2.push({ schedule_id: override.schedule_id, user_id: override.user_id, start_ms: override.start_ms, end_ms: override.end_ms });
119817
+ entries2 = cut2;
119399
119818
  }
119400
119819
  return entries2.sort((a, b) => a.start_ms - b.start_ms);
119401
119820
  }
@@ -127745,10 +128164,10 @@ function quotedPrintable(text24) {
127745
128164
  encoded = encoded.replace(/ $/, "=20");
127746
128165
  const wrapped = [];
127747
128166
  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);
128167
+ let cut2 = 75;
128168
+ while (encoded[cut2 - 1] === "=" || encoded[cut2 - 2] === "=") cut2--;
128169
+ wrapped.push(encoded.slice(0, cut2) + "=");
128170
+ encoded = encoded.slice(cut2);
127752
128171
  }
127753
128172
  wrapped.push(encoded);
127754
128173
  return wrapped.join("\r\n");
@@ -132840,13 +133259,14 @@ function removeMember(c) {
132840
133259
  });
132841
133260
  }
132842
133261
  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) => {
133262
+ { 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
133263
  query2(c, ["page", "per_page", "affiliation", "permission"]);
132845
- const affiliation = c.req.query("affiliation");
132846
- if (affiliation !== void 0 && affiliation !== "all") unsupported(`affiliation ${affiliation}`);
133264
+ const affiliation = c.req.query("affiliation") ?? "all";
133265
+ if (!["all", "direct", "outside"].includes(affiliation)) throw new GitHubError(422, "Validation Failed", [{ resource: "Collaborator", field: "affiliation", code: "invalid" }]);
132847
133266
  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)));
133267
+ const ctx = c.env.ctx, repo4 = repository(c), org5 = getOrganization(ctx, repo4.owner);
133268
+ 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));
133269
+ return paginate(c, listed.map((entry3) => collaboratorShape(ctx, entry3.user, entry3.permission)));
132850
133270
  } },
132851
133271
  { method: "GET", path: "/repos/:owner/:repo/collaborators/:username", coverage: partial3("204 when the user has any access, otherwise 404."), handler: (c) => {
132852
133272
  query2(c, []);
@@ -134966,8 +135386,8 @@ function posterOf(ctx, userId) {
134966
135386
  function opening(text24, max = 48) {
134967
135387
  const flat2 = text24.replace(/\s+/g, " ").trim();
134968
135388
  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`;
135389
+ const cut2 = flat2.slice(0, max), space = cut2.lastIndexOf(" ");
135390
+ return `${(space > max * 0.6 ? cut2.slice(0, space) : cut2).replace(/[\s,.;:!?-]+$/, "")}\u2026`;
134971
135391
  }
134972
135392
  function outcome2(passed, expected, actual) {
134973
135393
  return {
@@ -172854,8 +173274,8 @@ var GENERATOR = "ancha world gen";
172854
173274
  function slugify4(text24, max = 48) {
172855
173275
  const slug13 = text24.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "world";
172856
173276
  if (slug13.length <= max) return slug13;
172857
- const cut = slug13.slice(0, max + 1).lastIndexOf("-");
172858
- return slug13.slice(0, cut > 20 ? cut : max);
173277
+ const cut2 = slug13.slice(0, max + 1).lastIndexOf("-");
173278
+ return slug13.slice(0, cut2 > 20 ? cut2 : max);
172859
173279
  }
172860
173280
  var hours = (days, hour2 = 0) => `-${days * 24 + hour2}h`;
172861
173281
  function assembleWorld(input2) {
@@ -174312,6 +174732,7 @@ function trialDuration(ms3) {
174312
174732
  }
174313
174733
  var plural4 = (n, one7, many = `${one7}s`) => `${n} ${n === 1 ? one7 : many}`;
174314
174734
  function progressLine(e, scenes) {
174735
+ if (e.event === "trace_skipped" && typeof e.trace === "string" && typeof e.reason === "string") return `skipped trace ${e.trace.slice(0, 8)}: ${e.reason}`;
174315
174736
  if (e.event === "run_started" && typeof e.runId === "string" && Array.isArray(e.scenes) && typeof e.trials === "number" && typeof e.parallel === "number") {
174316
174737
  if (typeof e.replayOf === "string") return `${e.runId}: replay of ${e.replayOf}`;
174317
174738
  const what = e.scenes.length === 1 ? `${plural4(e.trials, "trial")} of ${String(e.scenes[0])}` : `${plural4(e.trials, "trial")} each of ${e.scenes.length} scenes`;
@@ -175685,7 +176106,8 @@ var ScenarioCatalog = class {
175685
176106
  this.workspace = workspace3;
175686
176107
  this.configPath = configPath;
175687
176108
  }
175688
- async list() {
176109
+ /** `workspaceOnly`: this folder's scene files alone (the configured globs and drafts), without the bundled library. */
176110
+ async list(options3 = {}) {
175689
176111
  const scenes = [], errors3 = [];
175690
176112
  const bundled = await builtinRoot();
175691
176113
  const seen = /* @__PURE__ */ new Set();
@@ -175701,10 +176123,10 @@ var ScenarioCatalog = class {
175701
176123
  errors3.push({ path: path6, message: error64 instanceof Error ? error64.message : String(error64) });
175702
176124
  }
175703
176125
  };
175704
- for (const path6 of (await glob3("*/scene.yaml", { cwd: bundled, followSymbolicLinks: false })).sort()) await add(bundled, path6, "bundled");
176126
+ if (!options3.workspaceOnly) for (const path6 of (await glob3("*/scene.yaml", { cwd: bundled, followSymbolicLinks: false })).sort()) await add(bundled, path6, "bundled");
175705
176127
  const packagedData = fileURLToPath3(new URL("test-data/", assetRoot()));
175706
176128
  const dataRoot = await stat4(packagedData).then((s) => s.isDirectory(), () => false) ? packagedData : fileURLToPath3(new URL("../../../scenes/library/", import.meta.url));
175707
- for (const file3 of (await glob3("*.json", { cwd: dataRoot, followSymbolicLinks: false })).sort()) {
176129
+ if (!options3.workspaceOnly) for (const file3 of (await glob3("*.json", { cwd: dataRoot, followSymbolicLinks: false })).sort()) {
175708
176130
  try {
175709
176131
  const library = parseTestDataLibrary(JSON.parse(await safeRead(dataRoot, file3)));
175710
176132
  for (const scenario of library.scenarios) {
@@ -177582,7 +178004,7 @@ function redact2(data5, secrets2) {
177582
178004
  return text24 === before ? data5 : Buffer.from(text24, "utf8");
177583
178005
  }
177584
178006
  function logTail(data5, cap) {
177585
- const note2 = (cut) => Buffer.from(`[ancha: agent.log was ${data5.length} bytes; the first ${cut} bytes are left out]
178007
+ const note2 = (cut2) => Buffer.from(`[ancha: agent.log was ${data5.length} bytes; the first ${cut2} bytes are left out]
177586
178008
  `, "utf8");
177587
178009
  let start = data5.length - (cap - note2(data5.length).length);
177588
178010
  const newline = data5.indexOf(10, start);
@@ -177645,9 +178067,9 @@ function header3(path6, size, mtimeMs) {
177645
178067
  const block2 = Buffer.alloc(512);
177646
178068
  let name5 = path6, prefix2 = "";
177647
178069
  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}`);
178070
+ const cut2 = path6.lastIndexOf("/");
178071
+ [prefix2, name5] = [path6.slice(0, cut2), path6.slice(cut2 + 1)];
178072
+ if (cut2 < 0 || Buffer.byteLength(name5) > 100 || Buffer.byteLength(prefix2) > 155) throw new AnchaError("INTERNAL", `bundle path too long for ustar: ${path6}`);
177651
178073
  }
177652
178074
  const octal = (value5, width) => `${value5.toString(8).padStart(width - 1, "0")}\0`;
177653
178075
  block2.write(name5, 0, 100, "utf8");
@@ -201071,12 +201493,12 @@ var agentAction = (entry3) => entry3.service === "tools" && entry3.path.startsWi
201071
201493
  var PRIVATE_KEY = /authorization|cookie|token|secret|password|api[_-]?key|app[_-]?key|routing[_-]?key|credential/i;
201072
201494
  var record21 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
201073
201495
  function judgeEvidence(capture4, secrets2 = [], asked, world5) {
201074
- const cut = /* @__PURE__ */ new Set();
201496
+ const cut2 = /* @__PURE__ */ new Set();
201075
201497
  const scrub = (raw3, part) => {
201076
201498
  let value5 = raw3;
201077
201499
  for (const secret of secrets2) if (secret !== "") value5 = value5.replaceAll(secret, "[redacted]");
201078
201500
  if (value5.length > MAX_STRING) {
201079
- cut.add(part);
201501
+ cut2.add(part);
201080
201502
  return `${value5.slice(0, MAX_STRING)}[truncated]`;
201081
201503
  }
201082
201504
  return value5;
@@ -201085,20 +201507,20 @@ function judgeEvidence(capture4, secrets2 = [], asked, world5) {
201085
201507
  if (typeof value5 === "string") return scrub(value5, part);
201086
201508
  if (value5 === null || typeof value5 === "boolean" || typeof value5 === "number") return value5;
201087
201509
  if (depth >= 5) {
201088
- cut.add(part);
201510
+ cut2.add(part);
201089
201511
  return "[truncated]";
201090
201512
  }
201091
201513
  if (Array.isArray(value5)) {
201092
- if (value5.length > 40) cut.add(part);
201514
+ if (value5.length > 40) cut2.add(part);
201093
201515
  return value5.slice(0, 40).map((v) => clean(v, part, depth + 1));
201094
201516
  }
201095
201517
  if (!record21(value5)) return void 0;
201096
201518
  const entries2 = Object.entries(value5).filter(([key3]) => !PRIVATE_KEY.test(key3));
201097
- if (entries2.length > 40) cut.add(part);
201519
+ if (entries2.length > 40) cut2.add(part);
201098
201520
  return Object.fromEntries(entries2.slice(0, 40).map(([key3, v]) => [scrub(key3, part), clean(v, part, depth + 1)]));
201099
201521
  };
201100
201522
  const native2 = capture4.trace.filter((entry3) => SERVICES.has(entry3.service) && !entry3.path.startsWith("/_ancha") || agentAction(entry3));
201101
- if (native2.length > MAX_ACTIONS) cut.add("calls");
201523
+ if (native2.length > MAX_ACTIONS) cut2.add("calls");
201102
201524
  const actions = native2.slice(-MAX_ACTIONS).map((entry3) => ({
201103
201525
  seq: entry3.seq,
201104
201526
  service: entry3.service,
@@ -201112,38 +201534,38 @@ function judgeEvidence(capture4, secrets2 = [], asked, world5) {
201112
201534
  }));
201113
201535
  const slack2 = record21(capture4.state) && record21(capture4.state.slack) ? capture4.state.slack : {};
201114
201536
  const rows33 = Array.isArray(slack2.messages) ? slack2.messages.filter(record21) : [];
201115
- if (rows33.length > MAX_MESSAGES) cut.add("messages");
201537
+ if (rows33.length > MAX_MESSAGES) cut2.add("messages");
201116
201538
  const messages4 = rows33.slice(-MAX_MESSAGES).map((row) => clean(Object.fromEntries(
201117
201539
  ["channel_id", "user_id", "ts", "thread_ts", "text"].filter((key3) => Object.hasOwn(row, key3)).map((key3) => [key3, row[key3]])
201118
201540
  ), "messages"));
201119
201541
  const channelRows = Array.isArray(slack2.channels) ? slack2.channels.filter(record21) : [];
201120
201542
  const userRows = Array.isArray(slack2.users) ? slack2.users.filter(record21) : [];
201121
201543
  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"));
201122
- if (channelRows.length > 100 || userRows.length > 100) cut.add("payloads");
201544
+ if (channelRows.length > 100 || userRows.length > 100) cut2.add("payloads");
201123
201545
  const channels = project11(channelRows, ["id", "name"]);
201124
201546
  const users4 = project11(userRows, ["id", "name", "is_bot"]);
201125
201547
  const invocation = asked === void 0 ? void 0 : clean(asked, "payloads");
201126
201548
  const facts = (world5 ?? []).slice(-MAX_ACTIONS).map((fact2) => clean(fact2, "payloads"));
201127
- 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 });
201549
+ 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 });
201128
201550
  while (serialize().length > MAX_JSON) {
201129
201551
  if (actions.length > 0) {
201130
- cut.add("calls");
201552
+ cut2.add("calls");
201131
201553
  actions.shift();
201132
201554
  } else if (messages4.length > 0) {
201133
- cut.add("messages");
201555
+ cut2.add("messages");
201134
201556
  messages4.shift();
201135
201557
  } else if (facts.length > 0) {
201136
- cut.add("payloads");
201558
+ cut2.add("payloads");
201137
201559
  facts.shift();
201138
201560
  } else if (channels.length > 0) {
201139
- cut.add("payloads");
201561
+ cut2.add("payloads");
201140
201562
  channels.shift();
201141
201563
  } else {
201142
- cut.add("payloads");
201564
+ cut2.add("payloads");
201143
201565
  users4.shift();
201144
201566
  }
201145
201567
  }
201146
- return { json: serialize(), seqs: new Set(actions.map((action) => action.seq)), truncated: cut.size > 0, cut: [...cut].sort() };
201568
+ return { json: serialize(), seqs: new Set(actions.map((action) => action.seq)), truncated: cut2.size > 0, cut: [...cut2].sort() };
201147
201569
  }
201148
201570
 
201149
201571
  // backend/src/judge/index.ts
@@ -201163,7 +201585,7 @@ async function evaluateJudges(scene2, capture4, options3) {
201163
201585
  const evidence = judgeEvidence(capture4, key3 ? [key3] : [], scene2.trigger?.input, world5);
201164
201586
  const issues = [...capture4.harnessIssues];
201165
201587
  const evaluated = /* @__PURE__ */ new Map();
201166
- const cut = evidence.cut.length > 0 ? { evidenceCut: evidence.cut } : {};
201588
+ const cut2 = evidence.cut.length > 0 ? { evidenceCut: evidence.cut } : {};
201167
201589
  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;
201168
201590
  for (const check4 of judges) {
201169
201591
  const base3 = { id: check4.id, required: required4.has(check4.id), passed: false, expected: check4.judge, evidence: [], judge: { model: model2 } };
@@ -201192,7 +201614,7 @@ async function evaluateJudges(scene2, capture4, options3) {
201192
201614
  explanation: reason2,
201193
201615
  evidence: grade2.evidence,
201194
201616
  ...warning !== void 0 && { warning },
201195
- judge: { model: model2, inputTokens: response5.usage?.prompt_tokens, outputTokens: response5.usage?.completion_tokens, ...cut }
201617
+ judge: { model: model2, inputTokens: response5.usage?.prompt_tokens, outputTokens: response5.usage?.completion_tokens, ...cut2 }
201196
201618
  });
201197
201619
  } catch {
201198
201620
  const error64 = options3.signal?.aborted ? "Judge evaluation cancelled." : "Judge evaluation failed: provider request or structured grade was invalid.";
@@ -201203,7 +201625,7 @@ async function evaluateJudges(scene2, capture4, options3) {
201203
201625
  explanation: error64,
201204
201626
  error: error64,
201205
201627
  ...warning !== void 0 && { warning },
201206
- judge: { model: model2, ...cut }
201628
+ judge: { model: model2, ...cut2 }
201207
201629
  });
201208
201630
  issues.push({ kind: "check", owner: "harness", service: "checks", message: `${check4.id}: ${error64}` });
201209
201631
  }
@@ -204326,9 +204748,9 @@ function trim(twin, full2) {
204326
204748
  for (const path6 of lists(seed40)) {
204327
204749
  const list16 = at2(seed40, path6);
204328
204750
  if (!Array.isArray(list16) || list16.length <= KEEP) continue;
204329
- const cut = replaced(seed40, path6, list16.slice(0, KEEP));
204330
- if (valid(twin, cut)) {
204331
- seed40 = cut;
204751
+ const cut2 = replaced(seed40, path6, list16.slice(0, KEEP));
204752
+ if (valid(twin, cut2)) {
204753
+ seed40 = cut2;
204332
204754
  changed = true;
204333
204755
  continue;
204334
204756
  }
@@ -207283,6 +207705,21 @@ var ConsoleSandboxes = class {
207283
207705
  }
207284
207706
  };
207285
207707
 
207708
+ // backend/src/console/world-data.ts
207709
+ init_src();
207710
+ async function startingData(backend, world5, seed40) {
207711
+ const options3 = { paused: true, execution: "manual", ttlMs: 6e4 };
207712
+ const env2 = "scene" in world5 ? await backend.createEnv(world5.scene, seed40, options3) : await backend.createSandbox(world5.configuration, seed40, options3);
207713
+ try {
207714
+ await backend.beginInspection(env2.id);
207715
+ const state3 = (await backend.observeEnv(env2.id)).state ?? {};
207716
+ const tools2 = Object.keys(state3);
207717
+ return { state: state3, trace: [], simMs: 0, seedPreview: true, seed: seed40, tools: tools2, toolViews: Object.fromEntries(tools2.map((tool) => [tool, toolDataView(tool, state3[tool])])) };
207718
+ } finally {
207719
+ await backend.destroyEnv(env2.id);
207720
+ }
207721
+ }
207722
+
207286
207723
  // backend/src/console/setups.ts
207287
207724
  init_src();
207288
207725
  init_assets();
@@ -207645,6 +208082,10 @@ async function startConsole(opts) {
207645
208082
  const q = query10(url3, ["revision"]);
207646
208083
  return send2(res, await playgrounds.world(id12, q.revision ? integer12(q.revision, "revision") : void 0));
207647
208084
  }
208085
+ if (method2 === "GET" && parts3.length === 4 && parts3[3] === "data") {
208086
+ const q = query10(url3, ["revision"]), world5 = await playgrounds.world(id12, q.revision ? integer12(q.revision, "revision") : void 0);
208087
+ return send2(res, { world: { id: world5.id, name: world5.name, revision: world5.revision }, ...await startingData(backend, { configuration: world5.configuration }, "playground-1") });
208088
+ }
207648
208089
  if (method2 === "POST" && parts3.length === 4 && parts3[3] === "update") {
207649
208090
  shape5(data5, ["name", "tools", "configuration", "revision"]);
207650
208091
  const { revision: revision2, ...patch } = data5;
@@ -207728,6 +208169,15 @@ async function startConsole(opts) {
207728
208169
  }
207729
208170
  }
207730
208171
  if (parts3[1] === "scenarios") {
208172
+ if (method2 === "GET" && parts3.length === 3 && parts3[2] === "folder") {
208173
+ const { scenes, errors: errors3 } = await catalog.list({ workspaceOnly: true });
208174
+ return send2(res, { scenes: scenes.filter((s) => s.origin === "workspace").map((s) => ({ key: s.key, path: s.path, id: s.scene.id, title: s.scene.title, tools: s.scene.twins })), errors: errors3 });
208175
+ }
208176
+ if (method2 === "GET" && parts3.length === 3 && parts3[2] === "data") {
208177
+ const found = await catalog.get(query10(url3, ["key"]).key ?? "");
208178
+ if (found.origin !== "workspace") throw new AnchaError("USAGE", "only scenes in this folder have starting data here");
208179
+ return send2(res, { scene: { key: found.key, path: found.path, id: found.scene.id, title: found.scene.title }, ...await startingData(backend, { scene: found.scene }, `${found.scene.id}:1`) });
208180
+ }
207731
208181
  if (method2 === "GET") return send2(res, await catalog.list());
207732
208182
  if (parts3[2] === "validate") {
207733
208183
  shape5(data5, ["yaml"]);
@@ -226685,6 +227135,39 @@ async function report6(ctx, world5, written) {
226685
227135
  ].join("\n")
226686
227136
  );
226687
227137
  }
227138
+ var OFF = "turned off in the workspace";
227139
+ async function pullAll(ctx, options3) {
227140
+ const api3 = await workspaceApi(ctx);
227141
+ const query11 = new URLSearchParams({ limit: "1000", ...options3.agent !== void 0 && { agent: options3.agent } });
227142
+ const { tests } = await api3(`/v1/tests?${query11}`);
227143
+ const written = [], skipped = [], paths2 = [];
227144
+ for (const test3 of tests) {
227145
+ if (test3.turned_off) {
227146
+ skipped.push({ id: test3.id, name: test3.name, reason: OFF });
227147
+ continue;
227148
+ }
227149
+ let changes;
227150
+ try {
227151
+ changes = await guard(ctx, resolve40(ctx.io.cwd, options3.dest, test3.name), options3.force);
227152
+ } catch (error64) {
227153
+ if (!(error64 instanceof AnchaError)) throw error64;
227154
+ skipped.push({ id: test3.id, name: test3.name, reason: error64.message });
227155
+ continue;
227156
+ }
227157
+ const { world: world5 } = await api3(`/v1/worlds/${encodeURIComponent(test3.id)}`);
227158
+ const done = await writeWorld(ctx, world5, options3.dest, changes);
227159
+ written.push({ id: world5.id, name: world5.name, version: world5.version ?? test3.version, scene: relative12(ctx.io.cwd, done.scene) || done.scene });
227160
+ paths2.push(done.scene);
227161
+ }
227162
+ const next2 = paths2.length ? await nextLines(ctx, paths2, options3.dest) : [];
227163
+ const from = options3.agent === void 0 ? "" : ` from ${options3.agent}`;
227164
+ ctx.out.result({ written, skipped, ...options3.agent !== void 0 && { agent: options3.agent } }, () => [
227165
+ written.length ? `wrote ${plural5(written.length, "test")}${from} to ${relative12(ctx.io.cwd, resolve40(ctx.io.cwd, options3.dest)) || "."}/` : tests.length ? `wrote no tests${from}` : `the workspace has no tests${from}; ancha traces lists what it received`,
227166
+ ...skipped.map((s) => ` skipped ${s.name}: ${s.reason}`),
227167
+ ...skipped.some((s) => s.reason !== OFF) ? [" move those changes into checks of your own, or pass --force to overwrite the files"] : [],
227168
+ ...next2
227169
+ ].join("\n"));
227170
+ }
226688
227171
  async function nextLines(ctx, paths2, dest) {
226689
227172
  const folder = relative12(ctx.io.cwd, resolve40(ctx.io.cwd, dest)) || ".", where2 = paths2.length === 1 ? relative12(ctx.io.cwd, paths2[0]) : `${folder}/*/scene.yaml`;
226690
227173
  const configured = ctx.globals().config !== void 0 || await access7(resolve40(ctx.io.cwd, "ancha.yaml")).then(() => true, () => false);
@@ -226744,7 +227227,7 @@ function registerTraces(program2, ctx) {
226744
227227
  lines.push(
226745
227228
  "what arrived:",
226746
227229
  ...agentToolLines(intake),
226747
- ...intake.tools.map((t) => ` ${t.service}: ${plural5(t.calls, "API call")}, ${t.rebuilt ? "rebuilt" : "not rebuilt yet"}`),
227230
+ ...intake.tools.map((t) => ` ${t.service}: ${plural5(t.calls, "API call")}, ${t.rebuilt ? "rebuilt" : "not rebuilt"}`),
226748
227231
  ...intake.inbound ? [` ${plural5(intake.inbound, "webhook")} the agent received`] : [],
226749
227232
  ...intake.llm ? [` ${plural5(intake.llm, "model call")}${intake.modelContent ? ", with what the agent was told" : ", without what the agent was told"}`] : [],
226750
227233
  ...intake.gaps.map((g) => ` note: ${g.message}`)
@@ -226806,13 +227289,29 @@ function registerTraces(program2, ctx) {
226806
227289
  }
226807
227290
  const api3 = await workspaceApi(ctx, `ancha import --offline ${options3.from ? `--from ${options3.from} ` : ""}${trace} makes the tests on this computer; ancha login sends traces to your workspace`);
226808
227291
  const { traces: imported } = await api3(`/v1/imports?name=${encodeURIComponent(source.name)}`, { method: "POST", headers: { "content-type": options3.from ? "application/json" : "application/x-ndjson" }, body: source.text });
227292
+ let saved = 0, first;
226809
227293
  for (const { id: id12 } of imported) {
226810
227294
  const changes = await guard(ctx, resolve40(ctx.io.cwd, options3.dest, `trace-${id12.slice(0, 8)}`), options3.force);
226811
- const { world: world5 } = await api3(`/v1/traces/${id12}/tests`, { method: "POST" });
226812
- await report6(ctx, world5, await writeWorld(ctx, world5, options3.dest, changes));
227295
+ const made = await api3(`/v1/traces/${id12}/tests`, { method: "POST" }).catch((error64) => {
227296
+ if (!(error64 instanceof WorkspaceError) || ![409, 422].includes(error64.status)) throw error64;
227297
+ first ??= error64;
227298
+ ctx.out.event({ event: "trace_skipped", trace: id12, reason: error64.message });
227299
+ return void 0;
227300
+ });
227301
+ if (made === void 0) continue;
227302
+ await report6(ctx, made.world, await writeWorld(ctx, made.world, options3.dest, changes));
227303
+ saved++;
226813
227304
  }
227305
+ if (saved === 0 && first !== void 0) throw first;
226814
227306
  });
226815
- program2.command("pull").argument("<id>", "a test or a trace: its id, its first 8 characters, or the trace id your tracing tool shows").option("--dest <dir>", "where the tests go", "scenes/from-traces").option("--answer <question=value>", "answer one of the test's questions, saving a new version first; repeat for more (`ancha traces show <id>` lists them)", (value5, all8) => [...all8, value5], []).option("--force", "overwrite scene.yaml even if it has changes besides checks you added").option("--expect <what went wrong>", "say in a sentence what the agent did wrong in production; the new version gets a check for it").description("write a test saved from a production trace into this project; a trace with no saved test gets one").action(async (id12, options3) => {
227307
+ program2.command("pull").argument("[id]", "a test or a trace: its id, its first 8 characters, or the trace id your tracing tool shows").option("--all", "write every test in the workspace that is turned on, each its latest version").option("--agent <name>", "with --all: only the tests made from this agent's traces").option("--dest <dir>", "where the tests go", "scenes/from-traces").option("--answer <question=value>", "answer one of the test's questions, saving a new version first; repeat for more (`ancha traces show <id>` lists them)", (value5, all8) => [...all8, value5], []).option("--force", "overwrite scene.yaml even if it has changes besides checks you added").option("--expect <what went wrong>", "say in a sentence what the agent did wrong in production; the new version gets a check for it").description("write tests made from production traces into this project: one test, or every test with --all; a trace with no saved test gets one").action(async (id12, options3) => {
227308
+ if (options3.all) {
227309
+ if (id12 !== void 0 || options3.answer.length || options3.expect !== void 0) throw new AnchaError("USAGE", "--all writes each test as the workspace saved it", { hint: "leave out the id, --answer and --expect, or pull one test: ancha pull <id>" });
227310
+ await pullAll(ctx, options3);
227311
+ return;
227312
+ }
227313
+ if (options3.agent !== void 0) throw new AnchaError("USAGE", "--agent goes with --all", { hint: "ancha pull --all --agent <name>" });
227314
+ if (id12 === void 0) throw new AnchaError("USAGE", "name a test or a trace to pull, or pass --all", { hint: "ancha traces lists the traces; ancha pull --all writes every test" });
226816
227315
  const api3 = await workspaceApi(ctx);
226817
227316
  const found = (path6) => api3(path6).catch((error64) => {
226818
227317
  if (notInWorkspace(error64)) return null;
@@ -226967,6 +227466,8 @@ async function importLocally(ctx, source, options3) {
226967
227466
  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)}
226968
227467
  `);
226969
227468
  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)}
227469
+ `);
227470
+ await writeFile27(join55(dir2, "questions.json"), `${JSON.stringify(m.made.questions, null, 2)}
226970
227471
  `);
226971
227472
  await loadSceneFile(path6);
226972
227473
  }