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mB;AAClC,IAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,EAAE,CAAA,EAAG;AACrB,IAAA,MAAM,CAAA,GAAI,IAAA,CAAK,GAAA,CAAI,EAAE,CAAA;AACrB,IAAA,IAAI,CAAA,OAAQ,CAAC,CAAA;AAAA,SACR;AACH,MAAA,OAAA,CAAQ,IAAI,EAAE,CAAA;AACd,MAAA,IAAA,CAAK,IAAA,CAAK,EAAE,SAAA,EAAW,EAAA,EAAI,CAAA;AAAA,IAC7B;AAAA,EACF;AACA,EAAA,OAAO,IAAA,CAAK,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM;AAGzB,IAAA,MAAM,KAAK,IAAA,CAAK,GAAA,CAAI,CAAA,CAAE,SAAS,GAAG,SAAA,IAAa,YAAA;AAC/C,IAAA,MAAM,KAAK,IAAA,CAAK,GAAA,CAAI,CAAA,CAAE,SAAS,GAAG,SAAA,IAAa,YAAA;AAC/C,IAAA,OAAO,EAAA,CAAG,cAAc,EAAE,CAAA;AAAA,EAC5B,CAAC,CAAA;AACH","file":"pr-provenance.mjs","sourcesContent":["/**\n * PR provenance footer — daemon/MCP lane.\n *\n * This is the SAME footer the runner-side agentflow scripts stamp on the\n * CI-PR, review, and local-`gh_open_pr` lanes; `scripts/lib/provenance-\n * footer.mjs` re-exports {@link buildFooter}/{@link MARKER}/{@link fmtTokens}\n * from HERE so there is exactly one format, one marker, one renderer. The\n * only reason this canonical copy lives in `@agentproto/runtime` rather than\n * in `scripts/` is direction of dependency: the daemon is a package and\n * cannot import a loose script, but a script can import a package's built\n * `dist/` (it already does for `computeProvenance`).\n *\n * What the DAEMON lane adds over the runner lanes: the footer is built from\n * a live {@link SessionDescriptor} (the executor agent-cli session that ran\n * `gh pr create`) plus its supervisor/parent session, rather than from a\n * `computeProvenance` join over the worktree. So this file also owns the\n * mapping from a session descriptor to the footer's provenance shape\n * ({@link sessionFooterProvenance}) and the small pure helpers the\n * command_execute stamp path needs ({@link parseGhPrCreate},\n * {@link pickExecutorSession}, {@link appendFooterOnce}).\n *\n * Pure by construction — only `node:path`, no daemon imports, no I/O — so it\n * bundles to a standalone `dist/pr-provenance.mjs` the scripts can import\n * without pulling the rest of the runtime in. Keep it that way. The\n * side-effecting orchestration (spawning `gh`, editing the PR body, recording\n * the opened PR) lives in `pr-provenance-stamp.ts`.\n */\n\nimport { basename } from \"node:path\"\n\n/** Deterministic marker the runner owns — a reliable native-vs-legacy\n *  discriminator across every lane (CI-PR, review, local, daemon). */\nexport const MARKER = \"@agentproto-bot\"\n\nexport const fmtTokens = (n: unknown): string | null => {\n  if (typeof n !== \"number\" || !Number.isFinite(n)) return null\n  return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n)\n}\n\n/** The footer's provenance shape — field names are the renderer's, not the\n *  session registry's (see {@link sessionFooterProvenance} for the mapping). */\nexport interface FooterProvenance {\n  sessionId?: string\n  label?: string\n  /** Adapter / harness slug that ran (\"claude-code\", \"codex\", …). */\n  adapter?: string\n  model?: string\n  /** Bound auth-profile IDENTITY — a label or ref, NEVER the credential. */\n  authProfile?: string\n  sandboxId?: string\n  /** Supervisor / parent session that spawned the executor. */\n  parentSessionId?: string\n  tokensIn?: number\n  tokensOut?: number\n  costUsd?: number\n  /** \"adapter\" | \"local\" | \"daemon\" — drives host/cwd vs run-link rendering. */\n  source?: string\n  host?: string\n  cwd?: string\n  /** The session's registered workspace slug (`SessionDescriptor.workspaceSlug`,\n   *  e.g. \"ts\", \"default\"). Rendered alongside `cwd`'s leaf directory name so\n   *  the footer identifies WHICH workspace ran the command, not just an\n   *  arbitrary trailing path segment — a bare `basename(cwd)` reads as\n   *  meaningless (or actively misleading) when the session's cwd is a\n   *  workspace root rather than a per-branch worktree. */\n  workspaceSlug?: string\n  /** The sessions that committed to the PR's branch — every box session\n   *  whose work landed on it (including several over successive rescues),\n   *  plus the trailered ids of sessions the registry no longer tracks. When\n   *  present, each author renders with ITS OWN model/wallet/box provider and\n   *  COST; the `sessionId` provenance's own cumulative cost/tokens (the\n   *  opener's ledger) is then suppressed — an orchestrator that merely runs\n   *  `gh pr create` must never appear as the PR's wallet. */\n  authors?: readonly FooterAuthor[]\n  /** The session that opened the PR (`Opened by`). Normally the same session\n   *  the footer's `session` segment already names; distinct when a daemon\n   *  `pr_open`-style tool opened the PR on behalf of a box session. */\n  openedBy?: string\n}\n\n/** One authoring session a PR footer credits. Field names are the renderer's\n *  (collected from a session descriptor — never the credential). */\nexport interface FooterAuthor {\n  sessionId: string\n  label?: string\n  adapter?: string\n  model?: string\n  /** Bound auth-profile identity — a label or ref, NEVER the credential. */\n  authProfile?: string\n  /** Sandbox provider slug the session wrote in (\"e2b\", \"computer\", …). */\n  sandboxProvider?: string\n  costUsd?: number\n  tokensIn?: number\n  tokensOut?: number\n}\n\n/**\n * Render the footer's `cwd` value. A bare `basename(cwd)` collapses to a\n * meaningless (or actively misleading) fragment whenever the session's cwd IS\n * the workspace root rather than a per-branch worktree dir — e.g. a checkout\n * literally named `ts` renders as the opaque `cwd \\`ts\\`` with no indication\n * that's a workspace name, not a worktree/branch leaf. Prefixing the\n * registered workspace slug disambiguates it, and is dropped when it's\n * identical to the leaf (the common per-worktree case) so the common case\n * stays exactly as compact as before.\n */\nfunction cwdLabel(cwd: string, workspaceSlug?: string): string {\n  const leaf = basename(cwd)\n  if (!workspaceSlug || workspaceSlug === leaf) return workspaceSlug ?? leaf\n  return `${workspaceSlug}/${leaf}`\n}\n\nexport interface BuildFooterInput {\n  prov?: FooterProvenance\n  authMode?: string\n  runId?: string\n  runUrl?: string\n  sha?: string\n  kind?: string\n}\n\nexport const buildFooter = ({\n  prov,\n  authMode,\n  runId,\n  runUrl,\n  sha,\n  kind = \"review\",\n}: BuildFooterInput): string => {\n  const parts = [`🤖 **${MARKER}** — ${kind}`]\n  if (prov?.sessionId) {\n    parts.push(`session \\`${prov.sessionId}\\`${prov.label ? ` (\\`${prov.label}\\`)` : \"\"}`)\n  }\n  // Engine label: \"adapter / authMode\" when an adapter ran; \"legacy fallback\n  // (authMode)\" when no agent session exists at all (the API-key fallback path);\n  // bare authMode only if a session ran without a resolved adapter slug.\n  if (prov?.adapter) parts.push([prov.adapter, authMode].filter(Boolean).join(\" / \"))\n  else if (!prov?.sessionId) parts.push(`legacy fallback${authMode ? ` (${authMode})` : \"\"}`)\n  else if (authMode) parts.push(authMode)\n  // Bound auth profile identity (the \"wallet\") — daemon lane; NEVER the secret.\n  if (prov?.authProfile) parts.push(`auth-profile \\`${prov.authProfile}\\``)\n  if (prov?.model) parts.push(`model \\`${prov.model}\\``)\n  if (prov?.sandboxId) parts.push(`e2b \\`${prov.sandboxId}\\``)\n  if (prov?.parentSessionId) parts.push(`supervisor \\`${prov.parentSessionId}\\``)\n  // Authoring sessions first, each with its OWN wallet + spend. When authors\n  // are present, the opener's cumulative cost/tokens are suppressed: an\n  // orchestrator session's $ledger says nothing about what the PR cost.\n  if (prov?.authors?.length) {\n    for (const author of prov.authors) {\n      const inner: string[] = []\n      if (author.adapter) inner.push(author.adapter)\n      if (author.authProfile) inner.push(`auth-profile \\`${author.authProfile}\\``)\n      if (author.model) inner.push(`model \\`${author.model}\\``)\n      if (author.sandboxProvider) inner.push(author.sandboxProvider)\n      if (typeof author.costUsd === \"number\") inner.push(`$${author.costUsd.toFixed(4)}`)\n      parts.push(`Authored by \\`${author.sessionId}\\`${inner.length ? ` (${inner.join(\" · \")})` : \"\"}`)\n    }\n  }\n  // \"Opened by\" stands on its own: a `pr_open` whose authors didn't resolve\n  // (registry lost the box session, no trailers) must still name the opener.\n  if (prov?.openedBy) parts.push(`Opened by \\`${prov.openedBy}\\``)\n  // The opener's own tokens/spend only when the PR isn't attributed to other\n  // sessions (`authors`, or a distinct `openedBy`) — else it would render the\n  // cumulative opener ledger as the PR's cost.\n  const suppressOpenerSpend = (prov?.authors?.length ?? 0) > 0 || !!prov?.openedBy\n  const tin = fmtTokens(prov?.tokensIn)\n  const tout = fmtTokens(prov?.tokensOut)\n  if (!suppressOpenerSpend && (tin || tout)) parts.push(`${tin ?? \"?\"} in / ${tout ?? \"?\"} out`)\n  if (!suppressOpenerSpend && typeof prov?.costUsd === \"number\") {\n    parts.push(`$${prov.costUsd.toFixed(4)}${prov.source && prov.source !== \"adapter\" ? ` (${prov.source})` : \"\"}`)\n  }\n  const showLocalHostCwd = prov?.source === \"local\" || prov?.source === \"daemon\" || !runId\n  if (runId && !showLocalHostCwd) parts.push(`run [${runId}](${runUrl})`)\n  if (showLocalHostCwd) {\n    if (prov?.host) parts.push(`host \\`${prov.host}\\``)\n    if (prov?.cwd) parts.push(`cwd \\`${cwdLabel(prov.cwd, prov.workspaceSlug)}\\``)\n  }\n  if (sha) parts.push(`sha \\`${sha}\\``)\n  return `\\n\\n---\\n<sub>${parts.join(\" · \")}</sub>`\n}\n\n/** Structural subset of `SessionDescriptor` the footer needs. The runtime's\n *  full descriptor satisfies this; keeping it structural is what lets this\n *  module stay free of a `./sessions.js` import (and thus standalone). */\nexport interface FooterSession {\n  id: string\n  kind?: string\n  status?: string\n  startedAt?: string\n  label?: string\n  cwd?: string\n  workspaceSlug?: string\n  adapterSlug?: string\n  harness?: string\n  model?: string\n  parentSessionId?: string\n  costUsd?: number\n  tokensIn?: number\n  tokensOut?: number\n  auth?: { mode?: string }\n  accessProfile?: { profileRef: string; label?: string }\n  /** Sandbox provider slug (\"e2b\", \"computer\", …) — authorship rendering. */\n  sandboxProvider?: string\n  /** The work branch inside the session's box (`sandboxDeliveryTarget.branch`\n   *  on the full descriptor) — how authorship is tracked per branch. */\n  sandboxDeliveryTarget?: { branch: string }\n  /** The session's own per-spawn checkpoint override, its `refPrefix` is\n   *  the namespace this session's snapshots are pushed under (see\n   *  `checkpointRefPrefixForSession` in `sandbox-delivery.ts`). */\n  sandboxCheckpointOverride?: { refPrefix?: string } | false\n}\n\nexport interface SessionFooterOptions {\n  /** The supervisor/parent session descriptor, when resolvable. */\n  supervisor?: { id: string } | null\n  host?: string\n  /** Provenance source tag; defaults to \"daemon\". */\n  source?: string\n  /** The sessions that authored the PR's branch — see\n   *  {@link FooterProvenance.authors}. */\n  authors?: readonly FooterAuthor[]\n  /** The session that opened the PR, when it is NOT the named session (a\n   *  daemon `pr_open` tool on behalf of a box session). */\n  openedBy?: string\n}\n\n/**\n * Map a live executor session (+ its supervisor) onto the footer's provenance\n * shape and the `authMode` the renderer takes separately. The adapter is the\n * canonical harness slug, falling back to `adapterSlug`. The bound auth\n * profile is the profile's human label (or its ref), never the credential.\n */\nexport function sessionFooterProvenance(\n  session: FooterSession,\n  options: SessionFooterOptions = {},\n): { prov: FooterProvenance; authMode: string | undefined } {\n  const prov: FooterProvenance = {\n    sessionId: session.id,\n    label: session.label,\n    adapter: session.harness ?? session.adapterSlug,\n    model: session.model,\n    authProfile: session.accessProfile?.label ?? session.accessProfile?.profileRef,\n    parentSessionId: options.supervisor?.id,\n    costUsd: session.costUsd,\n    tokensIn: session.tokensIn,\n    tokensOut: session.tokensOut,\n    source: options.source ?? \"daemon\",\n    host: options.host,\n    cwd: session.cwd,\n    workspaceSlug: session.workspaceSlug,\n    ...(options.authors?.length ? { authors: [...options.authors] } : {}),\n    ...(options.openedBy ? { openedBy: options.openedBy } : {}),\n  }\n  return { prov, authMode: session.auth?.mode }\n}\n\n/** Build the daemon-lane PR footer for one executor session directly. */\nexport function buildSessionPrFooter(\n  session: FooterSession,\n  options: SessionFooterOptions & { sha?: string } = {},\n): string {\n  const { prov, authMode } = sessionFooterProvenance(session, options)\n  return buildFooter({ prov, authMode, sha: options.sha, kind: \"PR\" })\n}\n\n/**\n * Append the footer to a PR body exactly once. Idempotent by the marker: a\n * body that already carries a `@agentproto-bot` footer is returned unchanged,\n * so a retried stamp (network reply lost after the edit landed) never stacks\n * a second footer.\n */\nexport function appendFooterOnce(body: string, footer: string): string {\n  if (hasProvenanceFooter(body)) return body\n  return `${body}${footer}`\n}\n\n/**\n * Whether a PR/review body already carries a RENDERED provenance footer — the\n * `<sub>…@agentproto-bot…</sub>` line {@link buildFooter} emits — as opposed\n * to merely MENTIONING the marker in prose. The distinction matters: a PR\n * whose description discusses the provenance machinery itself (they exist —\n * #999 explains a footer bug and quotes the marker) would otherwise read as\n * \"already stamped\" forever and never receive its real footer.\n */\nexport function hasProvenanceFooter(body: string): boolean {\n  return new RegExp(`<sub>[^\\\\n]*${MARKER}`).test(body)\n}\n\n/** The rendered footer block, as {@link buildFooter} emits it (with the\n *  `\\n\\n---\\n` lead-in when present). */\nconst FOOTER_BLOCK_RE = new RegExp(`(?:\\\\n+---)?\\\\n*<sub>[^\\\\n]*${MARKER}[^\\\\n]*</sub>`)\n\n/** Remove a rendered provenance footer (and the `---` separator that leads\n *  it) from a body, trailing whitespace trimmed, the part of the body the\n *  author wrote, as opposed to what the daemon appended. Used to remember\n *  \"the body the daemon last stamped\" so a later rewrite can be told apart\n *  from a deliberate footer-free edit (see the reconciler's footer state). */\nexport function stripProvenanceFooter(body: string): string {\n  return body.replace(FOOTER_BLOCK_RE, \"\").replace(/\\n+$/, \"\")\n}\n\n/** Just the `<sub>…</sub>` span of a rendered footer within `body` (or a\n *  standalone footer string, which is itself `<sub>…</sub>`-shaped) — every\n *  \"read a signal out of an existing footer\" helper below shares this\n *  extraction so they agree on what \"the footer\" means. Undefined when `body`\n *  carries no rendered footer at all. */\nfunction extractFooterBlock(body: string): string | undefined {\n  return new RegExp(`<sub>[^\\\\n]*${MARKER}[^\\\\n]*</sub>`).exec(body)?.[0]\n}\n\n/** True when a body's provenance footer already carries a spend figure. */\nexport function footerHasCost(body: string): boolean {\n  const block = extractFooterBlock(body)\n  return block !== undefined && /\\$\\d/.test(block)\n}\n\n/**\n * The `session \\`<id>\\`` a rendered footer names, or undefined when the body\n * carries no footer or the footer names no session (the legacy-fallback\n * shape, e.g. a bare CI API-key run with no agent session behind it).\n *\n * Used to recognize \"this footer already names ME\" — both the daemon's own\n * `buildSessionPrFooter` render and the `gh` PATH shim's thin one\n * (gh-provenance-shim.ts) render the SAME `session \\`<id>\\`` segment, so a\n * footer this returns OUR session id for is safe to enrich/upgrade: the\n * misattribution risk `hasProvenanceFooter`'s callers guard against is a\n * footer naming a DIFFERENT session, not our own.\n */\nexport function footerSessionId(body: string): string | undefined {\n  const block = extractFooterBlock(body)\n  if (block === undefined) return undefined\n  return /session `([^`]+)`/.exec(block)?.[1]\n}\n\n/**\n * The `Opened by \\`<id>\\`` a rendered footer names, or undefined when the\n * body carries no footer (or no opener).\n *\n * The stamper's REFRESH pass (the reconciler's cost refresh) re-renders the\n * footer from the session alone, and the caller has no idea who opened the\n * PR. Dropping the opener there would silently delete the \"Opened by\" entry\n * from a footer that had it, so reading it back off the existing footer\n * keeps it (the alternative, persisting the opener on the PR record, needs a\n * descriptor change on every record path).\n */\nexport function footerOpenedBy(body: string): string | undefined {\n  const block = extractFooterBlock(body)\n  if (block === undefined) return undefined\n  return /Opened by `([^`]+)`/.exec(block)?.[1]\n}\n\n/** One `Authored by \\`<id>\\`` entry of a rendered footer. `details` is the\n *  parenthetical payload (`codex · model \\`x\\` · $0.01`), empty for an\n *  ID-only author (a session the registry no longer knows). */\nexport interface FooterAuthorEntry {\n  sessionId: string\n  details: string\n}\n\n/**\n * The `Authored by` entries of a rendered footer, in render order. Used to\n * tell \"the fresh render knows an author the posted one doesn't\" (and \"knows\n * it BETTER\") apart from \"the posted one already says everything\", the\n * signal the replacement guard needs before it re-renders a footer.\n */\nexport function footerAuthors(body: string): FooterAuthorEntry[] {\n  const block = extractFooterBlock(body)\n  if (block === undefined) return []\n  const out: FooterAuthorEntry[] = []\n  const re = /Authored by `([^`]+)`(?:\\s*\\(([^)]*)\\))?/g\n  let m: RegExpExecArray | null\n  while ((m = re.exec(block)) !== null) out.push({ sessionId: m[1] ?? \"\", details: m[2] ?? \"\" })\n  return out\n}\n\n/** Whether one author entry carries strictly MORE than another, a detail\n *  token the other lacks. An ID-only author (`Authored by \\`sess_x\\``) is\n *  strictly poorer than the same author rendered with a model/wallet/cost. */\nfunction authorDetailsRicher(candidate: string, existing: string): boolean {\n  if (!candidate) return false\n  if (!existing) return true\n  const tokens = (s: string) => s.split(\"·\").map(t => t.trim()).filter(Boolean)\n  const have = new Set(tokens(existing))\n  return tokens(candidate).some(t => !have.has(t))\n}\n\n/**\n * Whether `candidate` (a standalone footer, as {@link buildFooter} renders\n * it, or a full body containing one) carries a provenance signal — spend,\n * bound auth-profile identity, or token counts — that `existing` doesn't.\n * Used to decide whether replacing an already-posted footer with a fresh\n * daemon render is a genuine UPGRADE rather than a no-op re-render: the `gh`\n * PATH shim's thin footer (gh-provenance-shim.ts) can only ever render\n * session/adapter/model/host/cwd — never cost, auth-profile, or tokens, since\n * those aren't known to a bare `gh` subprocess — so a shim-stamped body\n * always has ROOM for this kind of upgrade once the daemon knows more.\n *\n * AUTHORSHIP counts as an upgrade too: a fresh render that knows an author\n * the posted footer doesn't (a rescue session that landed on the branch\n * afterwards), or knows it BETTER (the posted entry is ID-only while the\n * fresh one carries the author's model/wallet/cost), must replace the posted\n * footer, otherwise the PR keeps crediting an unknown session, or credits\n * it with no wallet at all, forever.\n */\nexport function footerIsRicherThan(candidate: string, existing: string): boolean {\n  const candidateBlock = extractFooterBlock(candidate) ?? \"\"\n  const existingBlock = extractFooterBlock(existing) ?? \"\"\n  const gained = (has: (block: string) => boolean) => has(candidateBlock) && !has(existingBlock)\n  const hasCost = (block: string) => /\\$\\d/.test(block)\n  const hasAuthProfile = (block: string) => /auth-profile `/.test(block)\n  const hasTokens = (block: string) => / in \\/ .{1,20} out\\b/.test(block)\n  if (gained(hasCost) || gained(hasAuthProfile) || gained(hasTokens)) return true\n  // Authorship: a new author, or a richer rendering of a known one.\n  const existingAuthors = new Map(footerAuthors(existing).map(a => [a.sessionId, a]))\n  return footerAuthors(candidate).some(author => {\n    const known = existingAuthors.get(author.sessionId)\n    if (!known) return true\n    return authorDetailsRicher(author.details, known.details)\n  })\n}\n\n/**\n * Replace an existing footer with a fresh one (append when there is none).\n * The daemon stamps a PR the instant `gh pr create` returns — mid-turn, when\n * a claude-code/claude-sdk session has reported no usage yet (cost only\n * arrives on the turn's `result`), so the first footer has no amount. At\n * turn-end the reconciler re-renders it with what the session now knows.\n */\nexport function replaceProvenanceFooter(body: string, footer: string): string {\n  if (!hasProvenanceFooter(body)) return appendFooterOnce(body, footer)\n  return body.replace(FOOTER_BLOCK_RE, footer)\n}\n\n/**\n * Recognise a successful `gh pr create` from its argv + stdout and pull the\n * created PR's URL + number out. Returns null for anything that isn't a\n * PR-creating `gh` invocation, or a create whose stdout carried no PR URL.\n *\n * `gh pr create` prints the PR URL on its own line (often the last line,\n * after any advisory notices) — we take the LAST `…/pull/<n>` match so a\n * \"Warning: …/pull/…\" style notice can't shadow the real one.\n */\nexport function parseGhPrCreate(\n  command: string,\n  args: readonly string[],\n  stdout: string,\n): { url: string; number: number } | null {\n  if (basename(command) !== \"gh\") return null\n  // Skip global flags; the first two non-flag tokens must be `pr` then `create`.\n  const positionals = args.filter(a => !a.startsWith(\"-\"))\n  if (positionals[0] !== \"pr\" || positionals[1] !== \"create\") return null\n  const re = /https?:\\/\\/\\S+?\\/pull\\/(\\d+)/g\n  let match: RegExpExecArray | null\n  let last: { url: string; number: number } | null = null\n  while ((match = re.exec(stdout)) !== null) {\n    last = { url: match[0], number: Number(match[1]) }\n  }\n  return last\n}\n\n/**\n * String-form counterpart of {@link parseGhPrCreate} for the in-agent tool\n * lane: an ACP harness's Bash-style tool reports ONE shell string (possibly\n * compound — `git push && gh pr create … | tail -1`), not an argv, so the\n * argv parser above can't see it. Detects \"this call created a PR\" from the\n * command string plus the call's recorded result text, and returns the\n * created PR (LAST `…/pull/<n>` match in the result, same shadowing rule as\n * {@link parseGhPrCreate} — `gh pr create` prints its URL after any notices).\n *\n * Quoted spans are stripped before matching so a command that merely\n * MENTIONS the phrase — `grep \"gh pr create\" src/` over a result that quotes\n * a PR url — can never read as a create. Best-effort by design: the caller\n * additionally gates on the call's own `isError` (a failed create whose\n * stderr cites an existing PR must not attribute that PR here).\n */\nexport function detectShellPrCreate(\n  command: string | undefined,\n  resultText: string | undefined,\n): { url: string; number: number } | null {\n  if (!command || !resultText) return null\n  const unquoted = command.replace(/'[^']*'/g, \" \").replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, \" \")\n  if (!/(^|[\\s;&|({])gh\\s+pr\\s+create(\\s|$)/.test(unquoted)) return null\n  const re = /https?:\\/\\/\\S+?\\/pull\\/(\\d+)/g\n  let match: RegExpExecArray | null\n  let last: { url: string; number: number } | null = null\n  while ((match = re.exec(resultText)) !== null) {\n    last = { url: match[0], number: Number(match[1]) }\n  }\n  return last\n}\n\n/** `session.cwd == cwd || one contains the other` — the executor's cwd is\n *  usually the worktree root while the command may run in a subdir (or vice\n *  versa), so containment is checked in both directions. */\nfunction cwdRelated(sessionCwd: string, cwd: string): boolean {\n  if (sessionCwd === cwd) return true\n  const sep = \"/\"\n  return cwd.startsWith(sessionCwd + sep) || sessionCwd.startsWith(cwd + sep)\n}\n\n/**\n * Best-effort attribution of a `command_execute` run to the executor agent\n * session that most likely issued it: the newest agent-cli session whose cwd\n * is related to the command's cwd, preferring a still-alive one. Returns\n * undefined when no agent-cli session matches (e.g. a bare shell opened the\n * PR) — the caller then skips stamping rather than emit a misleading \"legacy\n * fallback\" footer.\n */\nexport function pickExecutorSession<T extends FooterSession>(\n  sessions: readonly T[],\n  cwd: string,\n): T | undefined {\n  const candidates = sessions.filter(\n    s => s.kind === \"agent-cli\" && typeof s.cwd === \"string\" && cwdRelated(s.cwd, cwd),\n  )\n  if (candidates.length === 0) return undefined\n  const alive = (s: T) => s.status === \"running\" || s.status === \"starting\"\n  const byRecency = (a: T, b: T) => (b.startedAt ?? \"\").localeCompare(a.startedAt ?? \"\")\n  const live = candidates.filter(alive).sort(byRecency)\n  if (live.length > 0) return live[0]\n  return [...candidates].sort(byRecency)[0]\n}\n\n// ── PR authorship per branch ────────────────────────────────────────────\n\n/** Commit trailer the box-side commit/checkpoint paths stamp onto commits\n *  they make on an agent's behalf, naming the authoring session. Tracked\n *  commits stay attributable even when the session registry no longer\n *  knows the box session (a host restart between rescue sessions, say). */\nexport const AGENTPROTO_SESSION_TRAILER = \"Agentproto-Session\"\n\n/**\n * Append the {@link AGENTPROTO_SESSION_TRAILER} to a commit message the\n * box makes for `sessionId`. Idempotent: a message already carrying the\n * trailer is returned unchanged. `git commit -m` takes the whole value as\n * ONE argv, so multi-line bodies are safe; git renders trailing lines as\n * trailers like `Co-authored-by`.\n */\nexport function commitMessageWithSessionTrailer(message: string, sessionId: string): string {\n  if (!sessionId) return message\n  const re = new RegExp(`^${AGENTPROTO_SESSION_TRAILER}:\\\\s*\\\\S+\\\\s*$`, \"m\")\n  if (re.test(message)) return message\n  return `${message.replace(/\\s*$/, \"\")}\\n\\n${AGENTPROTO_SESSION_TRAILER}: ${sessionId}`\n}\n\n/** Every session id named by {@link AGENTPROTO_SESSION_TRAILER} lines in\n *  `input` (one or many commit messages). Deduped, order preserved. */\nexport function sessionIdsFromTrailers(input: string): string[] {\n  const re = new RegExp(`^${AGENTPROTO_SESSION_TRAILER}:\\\\s*(\\\\S+)`, \"gm\")\n  const ids: string[] = []\n  for (let m: RegExpExecArray | null; (m = re.exec(input)) !== null; ) {\n    const id = m[1] ?? \"\"\n    if (!ids.includes(id)) ids.push(id)\n  }\n  return ids\n}\n\n/**\n * The scope a branch's authors are resolved in.\n *\n *  - `workspaceSlug`, the workspace (repository) the PR belongs to. Branch\n *    names are repository-LOCAL: two workspaces can both use `wt/feat`, and\n *    crediting both would put another repo's session (and its cost) on this\n *    PR. Registry-derived matches are therefore scoped to the PR's own\n *    workspace. EXPLICIT trailer ids stay global, a trailer on the PR's own\n *    commits is proof of authorship whoever the session belongs to.\n *  - `extraSessionIds`, sessions always credited, whatever the branch /\n *    workspace match says (the session a PR is opened FOR).\n */\nexport interface BranchAuthorScope {\n  workspaceSlug?: string\n  extraSessionIds?: readonly string[]\n}\n\n/**\n * The sessions that authored a branch — everything that committed to it,\n * gathered from two complementary sources:\n *\n *  1. REGISTRY — live/registered sandboxed sessions whose\n *     `sandboxDeliveryTarget.branch` is this branch (checkpoint, delivery\n *     and rescue pushes all name their session), narrowed to the PR's own\n *     workspace when the scope names one (branch names are repo-local);\n *  2. TRAILERS — session ids cited by `Agentproto-Session:` commit\n *     trailers, covering a session the registry no longer knows (restarted\n *     daemon, a second rescue session on the same branch). A trailer id\n *     resolves through the registry even when the session is ARCHIVED, so a\n *     archived author still renders with its model, wallet and cost.\n *\n * Deduped by session id (first seen wins: registry descriptors are richer),\n * ordered by `startedAt` (oldest first — how the work happened). Trailers\n * that resolve to no known session still appear, id only — the PR names\n * every author even when its descriptor is gone.\n */\nexport function collectBranchAuthors(\n  sessions: readonly FooterSession[],\n  branch: string,\n  trailerSessionIds: readonly string[] = [],\n  scope: BranchAuthorScope = {},\n): FooterAuthor[] {\n  const byId = new Map(sessions.map(s => [s.id, s]))\n  const authorOf = (s: FooterSession): FooterAuthor => ({\n    sessionId: s.id,\n    ...(s.label ? { label: s.label } : {}),\n    ...(s.harness ?? s.adapterSlug ? { adapter: s.harness ?? s.adapterSlug } : {}),\n    ...(s.model ? { model: s.model } : {}),\n    ...(s.accessProfile ? { authProfile: s.accessProfile.label ?? s.accessProfile.profileRef } : {}),\n    ...(s.sandboxProvider ? { sandboxProvider: s.sandboxProvider } : {}),\n    ...(typeof s.costUsd === \"number\" ? { costUsd: s.costUsd } : {}),\n    ...(s.tokensIn !== undefined ? { tokensIn: s.tokensIn } : {}),\n    ...(s.tokensOut !== undefined ? { tokensOut: s.tokensOut } : {}),\n  })\n  const seen: FooterAuthor[] = []\n  const seenIds = new Set<string>()\n  const push = (s: FooterSession): boolean => {\n    if (seenIds.has(s.id)) return false\n    seenIds.add(s.id)\n    seen.push(authorOf(s))\n    return true\n  }\n  const inScope = (s: FooterSession): boolean =>\n    !scope.workspaceSlug || s.workspaceSlug === scope.workspaceSlug\n  for (const s of sessions) {\n    if (s.sandboxDeliveryTarget?.branch === branch && inScope(s)) push(s)\n  }\n  // The session the PR is opened FOR is always an author, even when its\n  // branch isn't the PR's head branch (a rescue on another branch) and even\n  // when the registry no longer lists it under this branch.\n  for (const id of scope.extraSessionIds ?? []) {\n    const s = byId.get(id)\n    if (s) push(s)\n  }\n  for (const id of trailerSessionIds) {\n    if (seenIds.has(id)) continue\n    const s = byId.get(id)\n    if (s) push(s)\n    else {\n      seenIds.add(id)\n      seen.push({ sessionId: id })\n    }\n  }\n  return seen.sort((a, b) => {\n    // Sessions the registry doesn't know (unknown trailers) sort last — the\n    // descriptor'd authors are the ones with a real timeline.\n    const sa = byId.get(a.sessionId)?.startedAt ?? \"9999-12-31\"\n    const sb = byId.get(b.sessionId)?.startedAt ?? \"9999-12-31\"\n    return sa.localeCompare(sb)\n  })\n}\n"]}