/** * PR provenance footer — daemon/MCP lane. * * This is the SAME footer the runner-side agentflow scripts stamp on the * CI-PR, review, and local-`gh_open_pr` lanes; `scripts/lib/provenance- * footer.mjs` re-exports {@link buildFooter}/{@link MARKER}/{@link fmtTokens} * from HERE so there is exactly one format, one marker, one renderer. The * only reason this canonical copy lives in `@agentproto/runtime` rather than * in `scripts/` is direction of dependency: the daemon is a package and * cannot import a loose script, but a script can import a package's built * `dist/` (it already does for `computeProvenance`). * * What the DAEMON lane adds over the runner lanes: the footer is built from * a live {@link SessionDescriptor} (the executor agent-cli session that ran * `gh pr create`) plus its supervisor/parent session, rather than from a * `computeProvenance` join over the worktree. So this file also owns the * mapping from a session descriptor to the footer's provenance shape * ({@link sessionFooterProvenance}) and the small pure helpers the * command_execute stamp path needs ({@link parseGhPrCreate}, * {@link pickExecutorSession}, {@link appendFooterOnce}). * * Pure by construction — only `node:path`, no daemon imports, no I/O — so it * bundles to a standalone `dist/pr-provenance.mjs` the scripts can import * without pulling the rest of the runtime in. Keep it that way. The * side-effecting orchestration (spawning `gh`, editing the PR body, recording * the opened PR) lives in `pr-provenance-stamp.ts`. */ /** Deterministic marker the runner owns — a reliable native-vs-legacy * discriminator across every lane (CI-PR, review, local, daemon). */ declare const MARKER = "@agentproto-bot"; declare const fmtTokens: (n: unknown) => string | null; /** The footer's provenance shape — field names are the renderer's, not the * session registry's (see {@link sessionFooterProvenance} for the mapping). */ interface FooterProvenance { sessionId?: string; label?: string; /** Adapter / harness slug that ran ("claude-code", "codex", …). */ adapter?: string; model?: string; /** Bound auth-profile IDENTITY — a label or ref, NEVER the credential. */ authProfile?: string; sandboxId?: string; /** Supervisor / parent session that spawned the executor. */ parentSessionId?: string; tokensIn?: number; tokensOut?: number; costUsd?: number; /** "adapter" | "local" | "daemon" — drives host/cwd vs run-link rendering. */ source?: string; host?: string; cwd?: string; /** The session's registered workspace slug (`SessionDescriptor.workspaceSlug`, * e.g. "ts", "default"). Rendered alongside `cwd`'s leaf directory name so * the footer identifies WHICH workspace ran the command, not just an * arbitrary trailing path segment — a bare `basename(cwd)` reads as * meaningless (or actively misleading) when the session's cwd is a * workspace root rather than a per-branch worktree. */ workspaceSlug?: string; /** The sessions that committed to the PR's branch — every box session * whose work landed on it (including several over successive rescues), * plus the trailered ids of sessions the registry no longer tracks. When * present, each author renders with ITS OWN model/wallet/box provider and * COST; the `sessionId` provenance's own cumulative cost/tokens (the * opener's ledger) is then suppressed — an orchestrator that merely runs * `gh pr create` must never appear as the PR's wallet. */ authors?: readonly FooterAuthor[]; /** The session that opened the PR (`Opened by`). Normally the same session * the footer's `session` segment already names; distinct when a daemon * `pr_open`-style tool opened the PR on behalf of a box session. */ openedBy?: string; } /** One authoring session a PR footer credits. Field names are the renderer's * (collected from a session descriptor — never the credential). */ interface FooterAuthor { sessionId: string; label?: string; adapter?: string; model?: string; /** Bound auth-profile identity — a label or ref, NEVER the credential. */ authProfile?: string; /** Sandbox provider slug the session wrote in ("e2b", "computer", …). */ sandboxProvider?: string; costUsd?: number; tokensIn?: number; tokensOut?: number; } interface BuildFooterInput { prov?: FooterProvenance; authMode?: string; runId?: string; runUrl?: string; sha?: string; kind?: string; } declare const buildFooter: ({ prov, authMode, runId, runUrl, sha, kind, }: BuildFooterInput) => string; /** Structural subset of `SessionDescriptor` the footer needs. The runtime's * full descriptor satisfies this; keeping it structural is what lets this * module stay free of a `./sessions.js` import (and thus standalone). */ interface FooterSession { id: string; kind?: string; status?: string; startedAt?: string; label?: string; cwd?: string; workspaceSlug?: string; adapterSlug?: string; harness?: string; model?: string; parentSessionId?: string; costUsd?: number; tokensIn?: number; tokensOut?: number; auth?: { mode?: string; }; accessProfile?: { profileRef: string; label?: string; }; /** Sandbox provider slug ("e2b", "computer", …) — authorship rendering. */ sandboxProvider?: string; /** The work branch inside the session's box (`sandboxDeliveryTarget.branch` * on the full descriptor) — how authorship is tracked per branch. */ sandboxDeliveryTarget?: { branch: string; }; /** The session's own per-spawn checkpoint override, its `refPrefix` is * the namespace this session's snapshots are pushed under (see * `checkpointRefPrefixForSession` in `sandbox-delivery.ts`). */ sandboxCheckpointOverride?: { refPrefix?: string; } | false; } interface SessionFooterOptions { /** The supervisor/parent session descriptor, when resolvable. */ supervisor?: { id: string; } | null; host?: string; /** Provenance source tag; defaults to "daemon". */ source?: string; /** The sessions that authored the PR's branch — see * {@link FooterProvenance.authors}. */ authors?: readonly FooterAuthor[]; /** The session that opened the PR, when it is NOT the named session (a * daemon `pr_open` tool on behalf of a box session). */ openedBy?: string; } /** * Map a live executor session (+ its supervisor) onto the footer's provenance * shape and the `authMode` the renderer takes separately. The adapter is the * canonical harness slug, falling back to `adapterSlug`. The bound auth * profile is the profile's human label (or its ref), never the credential. */ declare function sessionFooterProvenance(session: FooterSession, options?: SessionFooterOptions): { prov: FooterProvenance; authMode: string | undefined; }; /** Build the daemon-lane PR footer for one executor session directly. */ declare function buildSessionPrFooter(session: FooterSession, options?: SessionFooterOptions & { sha?: string; }): string; /** * Append the footer to a PR body exactly once. Idempotent by the marker: a * body that already carries a `@agentproto-bot` footer is returned unchanged, * so a retried stamp (network reply lost after the edit landed) never stacks * a second footer. */ declare function appendFooterOnce(body: string, footer: string): string; /** * Whether a PR/review body already carries a RENDERED provenance footer — the * `…@agentproto-bot…` line {@link buildFooter} emits — as opposed * to merely MENTIONING the marker in prose. The distinction matters: a PR * whose description discusses the provenance machinery itself (they exist — * #999 explains a footer bug and quotes the marker) would otherwise read as * "already stamped" forever and never receive its real footer. */ declare function hasProvenanceFooter(body: string): boolean; /** Remove a rendered provenance footer (and the `---` separator that leads * it) from a body, trailing whitespace trimmed, the part of the body the * author wrote, as opposed to what the daemon appended. Used to remember * "the body the daemon last stamped" so a later rewrite can be told apart * from a deliberate footer-free edit (see the reconciler's footer state). */ declare function stripProvenanceFooter(body: string): string; /** True when a body's provenance footer already carries a spend figure. */ declare function footerHasCost(body: string): boolean; /** * The `session \`\`` a rendered footer names, or undefined when the body * carries no footer or the footer names no session (the legacy-fallback * shape, e.g. a bare CI API-key run with no agent session behind it). * * Used to recognize "this footer already names ME" — both the daemon's own * `buildSessionPrFooter` render and the `gh` PATH shim's thin one * (gh-provenance-shim.ts) render the SAME `session \`\`` segment, so a * footer this returns OUR session id for is safe to enrich/upgrade: the * misattribution risk `hasProvenanceFooter`'s callers guard against is a * footer naming a DIFFERENT session, not our own. */ declare function footerSessionId(body: string): string | undefined; /** * The `Opened by \`\`` a rendered footer names, or undefined when the * body carries no footer (or no opener). * * The stamper's REFRESH pass (the reconciler's cost refresh) re-renders the * footer from the session alone, and the caller has no idea who opened the * PR. Dropping the opener there would silently delete the "Opened by" entry * from a footer that had it, so reading it back off the existing footer * keeps it (the alternative, persisting the opener on the PR record, needs a * descriptor change on every record path). */ declare function footerOpenedBy(body: string): string | undefined; /** One `Authored by \`\`` entry of a rendered footer. `details` is the * parenthetical payload (`codex · model \`x\` · $0.01`), empty for an * ID-only author (a session the registry no longer knows). */ interface FooterAuthorEntry { sessionId: string; details: string; } /** * The `Authored by` entries of a rendered footer, in render order. Used to * tell "the fresh render knows an author the posted one doesn't" (and "knows * it BETTER") apart from "the posted one already says everything", the * signal the replacement guard needs before it re-renders a footer. */ declare function footerAuthors(body: string): FooterAuthorEntry[]; /** * Whether `candidate` (a standalone footer, as {@link buildFooter} renders * it, or a full body containing one) carries a provenance signal — spend, * bound auth-profile identity, or token counts — that `existing` doesn't. * Used to decide whether replacing an already-posted footer with a fresh * daemon render is a genuine UPGRADE rather than a no-op re-render: the `gh` * PATH shim's thin footer (gh-provenance-shim.ts) can only ever render * session/adapter/model/host/cwd — never cost, auth-profile, or tokens, since * those aren't known to a bare `gh` subprocess — so a shim-stamped body * always has ROOM for this kind of upgrade once the daemon knows more. * * AUTHORSHIP counts as an upgrade too: a fresh render that knows an author * the posted footer doesn't (a rescue session that landed on the branch * afterwards), or knows it BETTER (the posted entry is ID-only while the * fresh one carries the author's model/wallet/cost), must replace the posted * footer, otherwise the PR keeps crediting an unknown session, or credits * it with no wallet at all, forever. */ declare function footerIsRicherThan(candidate: string, existing: string): boolean; /** * Replace an existing footer with a fresh one (append when there is none). * The daemon stamps a PR the instant `gh pr create` returns — mid-turn, when * a claude-code/claude-sdk session has reported no usage yet (cost only * arrives on the turn's `result`), so the first footer has no amount. At * turn-end the reconciler re-renders it with what the session now knows. */ declare function replaceProvenanceFooter(body: string, footer: string): string; /** * Recognise a successful `gh pr create` from its argv + stdout and pull the * created PR's URL + number out. Returns null for anything that isn't a * PR-creating `gh` invocation, or a create whose stdout carried no PR URL. * * `gh pr create` prints the PR URL on its own line (often the last line, * after any advisory notices) — we take the LAST `…/pull/` match so a * "Warning: …/pull/…" style notice can't shadow the real one. */ declare function parseGhPrCreate(command: string, args: readonly string[], stdout: string): { url: string; number: number; } | null; /** * String-form counterpart of {@link parseGhPrCreate} for the in-agent tool * lane: an ACP harness's Bash-style tool reports ONE shell string (possibly * compound — `git push && gh pr create … | tail -1`), not an argv, so the * argv parser above can't see it. Detects "this call created a PR" from the * command string plus the call's recorded result text, and returns the * created PR (LAST `…/pull/` match in the result, same shadowing rule as * {@link parseGhPrCreate} — `gh pr create` prints its URL after any notices). * * Quoted spans are stripped before matching so a command that merely * MENTIONS the phrase — `grep "gh pr create" src/` over a result that quotes * a PR url — can never read as a create. Best-effort by design: the caller * additionally gates on the call's own `isError` (a failed create whose * stderr cites an existing PR must not attribute that PR here). */ declare function detectShellPrCreate(command: string | undefined, resultText: string | undefined): { url: string; number: number; } | null; /** * Best-effort attribution of a `command_execute` run to the executor agent * session that most likely issued it: the newest agent-cli session whose cwd * is related to the command's cwd, preferring a still-alive one. Returns * undefined when no agent-cli session matches (e.g. a bare shell opened the * PR) — the caller then skips stamping rather than emit a misleading "legacy * fallback" footer. */ declare function pickExecutorSession(sessions: readonly T[], cwd: string): T | undefined; /** Commit trailer the box-side commit/checkpoint paths stamp onto commits * they make on an agent's behalf, naming the authoring session. Tracked * commits stay attributable even when the session registry no longer * knows the box session (a host restart between rescue sessions, say). */ declare const AGENTPROTO_SESSION_TRAILER = "Agentproto-Session"; /** * Append the {@link AGENTPROTO_SESSION_TRAILER} to a commit message the * box makes for `sessionId`. Idempotent: a message already carrying the * trailer is returned unchanged. `git commit -m` takes the whole value as * ONE argv, so multi-line bodies are safe; git renders trailing lines as * trailers like `Co-authored-by`. */ declare function commitMessageWithSessionTrailer(message: string, sessionId: string): string; /** Every session id named by {@link AGENTPROTO_SESSION_TRAILER} lines in * `input` (one or many commit messages). Deduped, order preserved. */ declare function sessionIdsFromTrailers(input: string): string[]; /** * The scope a branch's authors are resolved in. * * - `workspaceSlug`, the workspace (repository) the PR belongs to. Branch * names are repository-LOCAL: two workspaces can both use `wt/feat`, and * crediting both would put another repo's session (and its cost) on this * PR. Registry-derived matches are therefore scoped to the PR's own * workspace. EXPLICIT trailer ids stay global, a trailer on the PR's own * commits is proof of authorship whoever the session belongs to. * - `extraSessionIds`, sessions always credited, whatever the branch / * workspace match says (the session a PR is opened FOR). */ interface BranchAuthorScope { workspaceSlug?: string; extraSessionIds?: readonly string[]; } /** * The sessions that authored a branch — everything that committed to it, * gathered from two complementary sources: * * 1. REGISTRY — live/registered sandboxed sessions whose * `sandboxDeliveryTarget.branch` is this branch (checkpoint, delivery * and rescue pushes all name their session), narrowed to the PR's own * workspace when the scope names one (branch names are repo-local); * 2. TRAILERS — session ids cited by `Agentproto-Session:` commit * trailers, covering a session the registry no longer knows (restarted * daemon, a second rescue session on the same branch). A trailer id * resolves through the registry even when the session is ARCHIVED, so a * archived author still renders with its model, wallet and cost. * * Deduped by session id (first seen wins: registry descriptors are richer), * ordered by `startedAt` (oldest first — how the work happened). Trailers * that resolve to no known session still appear, id only — the PR names * every author even when its descriptor is gone. */ declare function collectBranchAuthors(sessions: readonly FooterSession[], branch: string, trailerSessionIds?: readonly string[], scope?: BranchAuthorScope): FooterAuthor[]; export { AGENTPROTO_SESSION_TRAILER, type BranchAuthorScope, type BuildFooterInput, type FooterAuthor, type FooterAuthorEntry, type FooterProvenance, type FooterSession, MARKER, type SessionFooterOptions, appendFooterOnce, buildFooter, buildSessionPrFooter, collectBranchAuthors, commitMessageWithSessionTrailer, detectShellPrCreate, fmtTokens, footerAuthors, footerHasCost, footerIsRicherThan, footerOpenedBy, footerSessionId, hasProvenanceFooter, parseGhPrCreate, pickExecutorSession, replaceProvenanceFooter, sessionFooterProvenance, sessionIdsFromTrailers, stripProvenanceFooter };