Receipt agent transport lifecycle in Bifrost

This commit is contained in:
Meta Vens 2026-06-17 04:49:22 +01:00
commit 118a3efc74
16 changed files with 2476 additions and 3 deletions

View file

@ -74,6 +74,7 @@ For the full staged roadmap, including contribution points, revenue share, patro
- set `Bridge:LocalBridgeToken` to allow the transitional local bridge actuator to register and receipt governed actions through `/bridge/actions/*`
- set `BIFROST_BRIDGE_BASE_URL` and `BIFROST_BRIDGE_TOKEN` when `tools/bifrost-bridge.mjs` should round-trip every action through the app ledger before mutating GitHub, Discord, or Reddit
- the same bridge URL/token pair lets `tools/dispatch-agent-requests.mjs` record `/dispatch/runs/*` receipts for launched Codex work, so Bifrost keeps a live run trail even when a turn fails
- `tools/agent-transport.mjs` also uses that bridge configuration to record `/transport/receipts` entries for queue, claim, release, and close events on the request lane
- GitHub bridge mutations now fail closed without those values; `--allow-ungated-github true` is reserved for explicit operator recovery
- set `BIFROST_REDDIT_CLIENT_ID`, `BIFROST_REDDIT_REFRESH_TOKEN`, and optionally `BIFROST_REDDIT_CLIENT_SECRET` before posting Reddit organizing threads
- set `Heimdall:PatronSupportIntakeSecret` before enabling Heimdall patron support intake in production

View file

@ -126,6 +126,7 @@ node .\tools\agent-transport.mjs apply-snapshot --in E:\tmp\bifrost-agent-transp
Dispatch receipts should use Bifrost's own public persona in the Bifrost governance channel. `tools/dispatch-agent-requests.mjs` reads `BIFROST_DISCORD_CHANNEL_ID` or `DISCORD_BIFROST_CHANNEL_ID` for the receipt target, uses persona name `Bifrost`, and defaults the persona avatar to the public `src/Bifrost.Web/wwwroot/img/bifrost-profile.png` raw GitHub URL unless `BIFROST_DISCORD_PERSONA_AVATAR_URL` or `DISCORD_PERSONA_AVATAR_URL_BIFROST` overrides it. Receipt text must lead with the concrete repo and work title, not a generic "recent consensus" summary, and must not expose request ids, workspace paths, log paths, or other debugging debris in Discord.
The dispatcher now tags those Discord receipts with the Bifrost request id as bridge provenance, and dispatched Codex turns inherit default bridge provenance environment variables so any explicit `tools/bifrost-bridge.mjs` crossing inside the turn can land on the same request trail without hand-carried flags. When `BIFROST_BRIDGE_BASE_URL` and `BIFROST_BRIDGE_TOKEN` are configured, the dispatcher also records `/dispatch/runs/*` receipts in the hosted app so Bifrost keeps a first-class run ledger for launch, completion, cancellation, and failure.
When that same bridge configuration is present, `tools/agent-transport.mjs` records `/transport/receipts` entries for queue, claim, release, and close operations on the request lane. The packet still lives in CultCache. The hosted receipt row is the Bifrost-side witness that an agent or dispatcher touched it.
The `snapshot` command writes a MessagePack-encoded `cultnet.snapshot_response_raw.v0` message. This keeps CultCache payload bytes intact for peers that share the document binding.

View file

@ -65,6 +65,12 @@ The hosted app also exposes a dispatch-run ledger for launched agent work:
This is the companion trail to bridge actions. A bridge action says "this crossing into GitHub/Discord/Reddit was requested and receipted." A dispatch run says "this specific Codex worker actually launched, ran, and ended this way." One guards governed mutation. The other proves agent activity.
The hosted app also exposes a request-lane receipt ledger for transport lifecycle events:
- `POST /transport/receipts`
This covers the activity that happens before or around a visible Codex turn: queueing a request, claiming it, releasing it, and closing it. The `.cc` packet is still the transport document. The hosted receipt row is the operator-facing witness that the activity happened.
Current gate behavior:
- active Bifrost members may request bridge actions from an authenticated app session
@ -81,6 +87,7 @@ Current CLI wiring:
- pass `--source-kind`, `--source-id`, `--authority-ref`, `--work-item-id`, or `--motion-id` so agent actions satisfy policy
- the dispatcher now preloads `BIFROST_BRIDGE_SOURCE_KIND`, `BIFROST_BRIDGE_SOURCE_ID`, and `BIFROST_BRIDGE_AUTHORITY_REF` into Codex turns launched from Bifrost update requests, so normal bridge use inside a dispatched turn carries request provenance by default
- the dispatcher also uses that same bridge configuration to post dispatch-run start/complete/fail receipts, including the worker pid, thread/turn ids when available, and result/log paths for the local operator trail
- the agent transport CLI uses that same bridge configuration to post request-lane receipts for queue, claim, release, and close events, so Bifrost does not go blind between intake and dispatch
If the app bridge configuration is absent, `tools/bifrost-bridge.mjs` keeps working as a local actuator. When configured, it asks Bifrost for authorization before acting and reports success or failure back to the same bridge action row.

View file

@ -57,6 +57,8 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
public DbSet<AgentDispatchRun> AgentDispatchRuns => Set<AgentDispatchRun>();
public DbSet<AgentTransportReceipt> AgentTransportReceipts => Set<AgentTransportReceipt>();
public DbSet<AuditEvent> AuditEvents => Set<AuditEvent>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
@ -454,6 +456,25 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
.OnDelete(DeleteBehavior.SetNull);
});
modelBuilder.Entity<AgentTransportReceipt>(entity =>
{
entity.Property(x => x.RequestId).HasMaxLength(240);
entity.Property(x => x.Title).HasMaxLength(240);
entity.Property(x => x.TargetRepoName).HasMaxLength(120);
entity.Property(x => x.TargetRepositoryFullName).HasMaxLength(240);
entity.Property(x => x.TargetAgentIdentity).HasMaxLength(160);
entity.Property(x => x.ActivityKind).HasConversion<string>();
entity.Property(x => x.Status).HasMaxLength(40);
entity.Property(x => x.ActorName).HasMaxLength(160);
entity.HasIndex(x => x.RequestId);
entity.HasIndex(x => x.OccurredAtUtc);
entity.HasIndex(x => new { x.TargetRepoName, x.TargetAgentIdentity, x.ActivityKind });
entity.HasOne(x => x.ActorUserAccount)
.WithMany(x => x.AgentTransportReceipts)
.HasForeignKey(x => x.ActorUserAccountId)
.OnDelete(DeleteBehavior.SetNull);
});
modelBuilder.Entity<AuditEvent>(entity =>
{
entity.Property(x => x.EntityType).HasMaxLength(120);

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,70 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bifrost.Web.Data.Migrations
{
/// <inheritdoc />
public partial class AddAgentTransportReceipts : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AgentTransportReceipts",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
RequestId = table.Column<string>(type: "character varying(240)", maxLength: 240, nullable: false),
Title = table.Column<string>(type: "character varying(240)", maxLength: 240, nullable: false),
TargetRepoName = table.Column<string>(type: "character varying(120)", maxLength: 120, nullable: false),
TargetRepositoryFullName = table.Column<string>(type: "character varying(240)", maxLength: 240, nullable: false),
TargetAgentIdentity = table.Column<string>(type: "character varying(160)", maxLength: 160, nullable: false),
ActivityKind = table.Column<string>(type: "text", nullable: false),
Status = table.Column<string>(type: "character varying(40)", maxLength: 40, nullable: false),
ActorUserAccountId = table.Column<Guid>(type: "uuid", nullable: true),
ActorName = table.Column<string>(type: "character varying(160)", maxLength: 160, nullable: false),
Note = table.Column<string>(type: "text", nullable: false),
OccurredAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AgentTransportReceipts", x => x.Id);
table.ForeignKey(
name: "FK_AgentTransportReceipts_UserAccounts_ActorUserAccountId",
column: x => x.ActorUserAccountId,
principalTable: "UserAccounts",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateIndex(
name: "IX_AgentTransportReceipts_ActorUserAccountId",
table: "AgentTransportReceipts",
column: "ActorUserAccountId");
migrationBuilder.CreateIndex(
name: "IX_AgentTransportReceipts_OccurredAtUtc",
table: "AgentTransportReceipts",
column: "OccurredAtUtc");
migrationBuilder.CreateIndex(
name: "IX_AgentTransportReceipts_RequestId",
table: "AgentTransportReceipts",
column: "RequestId");
migrationBuilder.CreateIndex(
name: "IX_AgentTransportReceipts_TargetRepoName_TargetAgentIdentity_A~",
table: "AgentTransportReceipts",
columns: new[] { "TargetRepoName", "TargetAgentIdentity", "ActivityKind" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AgentTransportReceipts");
}
}
}

View file

@ -113,6 +113,74 @@ namespace Bifrost.Web.Data.Migrations
b.ToTable("AgentDispatchRuns");
});
modelBuilder.Entity("Bifrost.Web.Domain.AgentTransportReceipt", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ActivityKind")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ActorName")
.IsRequired()
.HasMaxLength(160)
.HasColumnType("character varying(160)");
b.Property<Guid?>("ActorUserAccountId")
.HasColumnType("uuid");
b.Property<string>("Note")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("OccurredAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("RequestId")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("character varying(40)");
b.Property<string>("TargetAgentIdentity")
.IsRequired()
.HasMaxLength(160)
.HasColumnType("character varying(160)");
b.Property<string>("TargetRepoName")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<string>("TargetRepositoryFullName")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.HasKey("Id");
b.HasIndex("ActorUserAccountId");
b.HasIndex("OccurredAtUtc");
b.HasIndex("RequestId");
b.HasIndex("TargetRepoName", "TargetAgentIdentity", "ActivityKind");
b.ToTable("AgentTransportReceipts");
});
modelBuilder.Entity("Bifrost.Web.Domain.Assignment", b =>
{
b.Property<Guid>("Id")
@ -1348,6 +1416,16 @@ namespace Bifrost.Web.Data.Migrations
b.Navigation("StartedByUserAccount");
});
modelBuilder.Entity("Bifrost.Web.Domain.AgentTransportReceipt", b =>
{
b.HasOne("Bifrost.Web.Domain.UserAccount", "ActorUserAccount")
.WithMany("AgentTransportReceipts")
.HasForeignKey("ActorUserAccountId")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("ActorUserAccount");
});
modelBuilder.Entity("Bifrost.Web.Domain.Assignment", b =>
{
b.HasOne("Bifrost.Web.Domain.UserAccount", "AssignedByUserAccount")
@ -1810,6 +1888,8 @@ namespace Bifrost.Web.Data.Migrations
{
b.Navigation("AgentDispatchRuns");
b.Navigation("AgentTransportReceipts");
b.Navigation("AssignedWorkItems");
b.Navigation("Assignments");

View file

@ -223,6 +223,14 @@ public enum AgentDispatchRunStatus
Failed
}
public enum AgentTransportReceiptKind
{
Queued,
Claimed,
Released,
Closed
}
public sealed class UserAccount
{
public Guid Id { get; set; } = Guid.NewGuid();
@ -275,6 +283,8 @@ public sealed class UserAccount
public ICollection<AgentDispatchRun> AgentDispatchRuns { get; set; } = [];
public ICollection<AgentTransportReceipt> AgentTransportReceipts { get; set; } = [];
public ICollection<AuditEvent> AuditEvents { get; set; } = [];
}
@ -975,6 +985,35 @@ public sealed class AgentDispatchRun
public UserAccount? StartedByUserAccount { get; set; }
}
public sealed class AgentTransportReceipt
{
public Guid Id { get; set; } = Guid.NewGuid();
public string RequestId { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public string TargetRepoName { get; set; } = string.Empty;
public string TargetRepositoryFullName { get; set; } = string.Empty;
public string TargetAgentIdentity { get; set; } = string.Empty;
public AgentTransportReceiptKind ActivityKind { get; set; } = AgentTransportReceiptKind.Queued;
public string Status { get; set; } = string.Empty;
public Guid? ActorUserAccountId { get; set; }
public string ActorName { get; set; } = string.Empty;
public string Note { get; set; } = string.Empty;
public DateTimeOffset OccurredAtUtc { get; set; }
public UserAccount? ActorUserAccount { get; set; }
}
public sealed class AuditEvent
{
public Guid Id { get; set; } = Guid.NewGuid();

View file

@ -0,0 +1,91 @@
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Shared;
namespace Bifrost.Web.Features.Bridge;
public sealed class AgentTransportReceiptService(
BifrostDbContext dbContext,
AuditTrailService auditTrailService,
TimeProvider timeProvider)
{
public async Task<AgentTransportReceiptResult> RecordAsync(
AgentTransportReceiptRequest request,
Guid? actorUserAccountId,
CancellationToken cancellationToken)
{
var receipt = new AgentTransportReceipt
{
RequestId = NormalizeText(request.RequestId),
Title = NormalizeText(request.Title),
TargetRepoName = NormalizeText(request.TargetRepoName),
TargetRepositoryFullName = NormalizeText(request.TargetRepositoryFullName),
TargetAgentIdentity = NormalizeText(request.TargetAgentIdentity),
ActivityKind = request.ActivityKind,
Status = NormalizeText(request.Status),
ActorUserAccountId = actorUserAccountId,
ActorName = NormalizeText(request.ActorName),
Note = NormalizeText(request.Note),
OccurredAtUtc = timeProvider.GetUtcNow()
};
dbContext.AgentTransportReceipts.Add(receipt);
await dbContext.SaveChangesAsync(cancellationToken);
await auditTrailService.RecordAsync(
actorUserAccountId,
nameof(AgentTransportReceipt),
receipt.Id,
$"agent-transport.{receipt.ActivityKind.ToString().ToLowerInvariant()}",
BuildAuditDetail(receipt),
cancellationToken);
return AgentTransportReceiptResult.From(receipt);
}
private static string BuildAuditDetail(AgentTransportReceipt receipt)
{
var actorName = string.IsNullOrWhiteSpace(receipt.ActorName) ? "unknown actor" : receipt.ActorName;
var repoName = string.IsNullOrWhiteSpace(receipt.TargetRepoName) ? "unknown repo" : receipt.TargetRepoName;
return $"{actorName} recorded {receipt.ActivityKind} for request {receipt.RequestId} in {repoName} as {receipt.Status}.";
}
private static string NormalizeText(string? value) => value?.Trim() ?? string.Empty;
}
public sealed record AgentTransportReceiptRequest(
string RequestId,
string Title,
string TargetRepoName,
string TargetRepositoryFullName,
string TargetAgentIdentity,
AgentTransportReceiptKind ActivityKind,
string Status,
string ActorName,
string Note);
public sealed record AgentTransportReceiptResult(
Guid Id,
string RequestId,
string Title,
string TargetRepoName,
string TargetRepositoryFullName,
string TargetAgentIdentity,
AgentTransportReceiptKind ActivityKind,
string Status,
string ActorName,
string Note,
DateTimeOffset OccurredAtUtc)
{
public static AgentTransportReceiptResult From(AgentTransportReceipt receipt) => new(
receipt.Id,
receipt.RequestId,
receipt.Title,
receipt.TargetRepoName,
receipt.TargetRepositoryFullName,
receipt.TargetAgentIdentity,
receipt.ActivityKind,
receipt.Status,
receipt.ActorName,
receipt.Note,
receipt.OccurredAtUtc);
}

View file

@ -134,6 +134,23 @@ public sealed class DashboardSnapshotService(BifrostDbContext dbContext, TimePro
x.UpdatedAtUtc))
.ToListAsync(cancellationToken);
var recentTransportReceipts = await dbContext.AgentTransportReceipts
.AsNoTracking()
.OrderByDescending(x => x.OccurredAtUtc)
.Take(6)
.Select(x => new DashboardTransportReceipt(
x.Id,
x.RequestId,
x.Title,
x.TargetRepoName,
x.TargetAgentIdentity,
x.ActivityKind.ToString(),
x.Status,
x.ActorName,
x.Note,
x.OccurredAtUtc))
.ToListAsync(cancellationToken);
var payoutPreviewNominal = await dbContext.LedgerEntries
.AsNoTracking()
.Where(x => x.Status == LedgerEntryStatus.Approved)
@ -162,7 +179,8 @@ public sealed class DashboardSnapshotService(BifrostDbContext dbContext, TimePro
MySubmittedWork: submittedByMe,
RecentActivity: recentActivity,
RecentBridgeActions: recentBridgeActions,
RecentDispatchRuns: recentDispatchRuns);
RecentDispatchRuns: recentDispatchRuns,
RecentTransportReceipts: recentTransportReceipts);
}
}
@ -183,7 +201,8 @@ public sealed record DashboardSnapshot(
IReadOnlyList<DashboardLaneItem> MySubmittedWork,
IReadOnlyList<DashboardActivity> RecentActivity,
IReadOnlyList<DashboardBridgeAction> RecentBridgeActions,
IReadOnlyList<DashboardDispatchRun> RecentDispatchRuns);
IReadOnlyList<DashboardDispatchRun> RecentDispatchRuns,
IReadOnlyList<DashboardTransportReceipt> RecentTransportReceipts);
public sealed record DashboardWorkItem(
Guid WorkItemId,
@ -240,3 +259,15 @@ public sealed record DashboardDispatchRun(
string TurnId,
string Note,
DateTimeOffset UpdatedAtUtc);
public sealed record DashboardTransportReceipt(
Guid AgentTransportReceiptId,
string RequestId,
string Title,
string TargetRepoName,
string TargetAgentIdentity,
string ActivityKind,
string Status,
string ActorName,
string Note,
DateTimeOffset OccurredAtUtc);

View file

@ -232,6 +232,43 @@
</section>
<section class="panel-grid" style="margin-top: 1.5rem;">
<article class="panel">
<div class="panel-header">
<div>
<h2>Transport receipts</h2>
<p class="muted">Queue, claim, release, and closure events recorded on the request lane.</p>
</div>
</div>
@if (Model.Snapshot.RecentTransportReceipts.Count == 0)
{
<div class="empty-state">No request-lane receipts have been recorded yet.</div>
}
else
{
<div class="list-grid">
@foreach (var receipt in Model.Snapshot.RecentTransportReceipts)
{
<div class="status-banner">
<strong>@receipt.TargetRepoName@if (!string.IsNullOrWhiteSpace(receipt.TargetAgentIdentity)) {<text> / @receipt.TargetAgentIdentity</text>}</strong>
<span class="muted">@receipt.Title</span>
<div class="inline-actions">
<span class="pill">@receipt.ActivityKind</span>
<span class="pill">@receipt.Status</span>
<span class="pill">@receipt.ActorName</span>
</div>
<div class="muted">@receipt.RequestId</div>
@if (!string.IsNullOrWhiteSpace(receipt.Note))
{
<div class="muted">@receipt.Note</div>
}
<div class="muted">@receipt.OccurredAtUtc.ToString("dd MMM yyyy HH:mm") UTC</div>
</div>
}
</div>
}
</article>
<article class="panel">
<div class="panel-header">
<div>

View file

@ -11,7 +11,7 @@ public sealed class IndexModel(
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
public DashboardSnapshot Snapshot { get; private set; } =
new(0, 0, 0, 0, 0, 0, 0, 0, 0m, [], [], [], [], [], [], [], []);
new(0, 0, 0, 0, 0, 0, 0, 0, 0m, [], [], [], [], [], [], [], [], []);
public async Task OnGetAsync(CancellationToken cancellationToken)
{

View file

@ -81,6 +81,7 @@ builder.Services.AddScoped<AuditTrailService>();
builder.Services.AddScoped<DashboardSnapshotService>();
builder.Services.AddScoped<BridgeActionService>();
builder.Services.AddScoped<AgentDispatchRunService>();
builder.Services.AddScoped<AgentTransportReceiptService>();
builder.Services.AddScoped<MembershipSynchronizationService>();
builder.Services.AddScoped<GitHubWebhookService>();
builder.Services.AddScoped<MotionGovernanceService>();
@ -536,6 +537,26 @@ dispatchRuns.MapPost("/{id:guid}/fail", async (
: JsonResult(result, appJsonSerializerOptions);
});
var transportReceipts = app.MapGroup("/transport/receipts");
transportReceipts.MapPost("", async (
HttpRequest request,
AgentTransportReceiptRequest command,
ICurrentBifrostActorAccessor actorAccessor,
AgentTransportReceiptService agentTransportReceiptService,
IOptions<BridgeOptions> bridgeOptions,
CancellationToken cancellationToken) =>
{
var actor = await actorAccessor.GetAsync(cancellationToken);
if (!HasValidLocalBridgeToken(request, bridgeOptions.Value) && !actor.IsActiveMember)
{
return Results.Unauthorized();
}
var result = await agentTransportReceiptService.RecordAsync(command, actor.UserAccount?.Id, cancellationToken);
return JsonResult(result, appJsonSerializerOptions, StatusCodes.Status202Accepted);
});
var eveGovernance = app.MapGroup("/eve/governance")
.RequireAuthorization(ActiveMemberRequirement.PolicyName);

View file

@ -96,6 +96,20 @@ public sealed class MemberConsoleTests : IClassFixture<TestWebApplicationFactory
UpdatedAtUtc = DateTimeOffset.UtcNow.AddMinutes(-2),
CompletedAtUtc = DateTimeOffset.UtcNow.AddMinutes(-2)
});
dbContext.AgentTransportReceipts.Add(new AgentTransportReceipt
{
RequestId = "req_transport_123",
Title = "Queue the GitHub bridge hardening pass",
TargetRepoName = "Bifrost",
TargetRepositoryFullName = "GameCult/Bifrost",
TargetAgentIdentity = "nibu",
ActivityKind = AgentTransportReceiptKind.Claimed,
Status = "claimed",
ActorUserAccountId = actor.Id,
ActorName = "bifrost-dispatcher",
Note = "Request claimed for Bifrost.",
OccurredAtUtc = DateTimeOffset.UtcNow.AddMinutes(-3)
});
dbContext.SaveChanges();
}
@ -106,6 +120,8 @@ public sealed class MemberConsoleTests : IClassFixture<TestWebApplicationFactory
var html = await response.Content.ReadAsStringAsync();
Assert.Contains("Agent runs", html);
Assert.Contains("req_dispatch_123", html);
Assert.Contains("Transport receipts", html);
Assert.Contains("req_transport_123", html);
Assert.Contains("Bridge receipts", html);
Assert.Contains("Draft motion implementation PR", html);
Assert.Contains("nibu", html);

View file

@ -506,6 +506,45 @@ public sealed class PlatformEndpointsTests : IClassFixture<TestWebApplicationFac
Assert.Contains(dbContext.AuditEvents, x => x.EntityType == nameof(AgentDispatchRun) && x.Action == "agent-dispatch.failed");
}
[Fact]
public async Task Local_bridge_token_can_record_transport_receipt()
{
using var client = _factory.CreateClient();
var payload = JsonSerializer.Serialize(new
{
requestId = "req_transport_123",
title = "Queue the GitHub bridge hardening pass",
targetRepoName = "Bifrost",
targetRepositoryFullName = "GameCult/Bifrost",
targetAgentIdentity = "nibu",
activityKind = "Claimed",
status = "claimed",
actorName = "bifrost-dispatcher",
note = "Request claimed for Bifrost."
});
using var request = new HttpRequestMessage(HttpMethod.Post, "/transport/receipts");
request.Headers.Add("X-Bifrost-Bridge-Token", "test-bridge-token");
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
var receipt = await response.Content.ReadFromJsonAsync<AgentTransportReceiptHttpResult>();
Assert.NotNull(receipt);
Assert.Equal("req_transport_123", receipt.RequestId);
Assert.Equal("Claimed", receipt.ActivityKind);
using var scope = _factory.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
var savedReceipt = dbContext.AgentTransportReceipts.Single(x => x.Id == receipt.Id);
Assert.Equal("Claimed", savedReceipt.ActivityKind.ToString());
Assert.Equal("bifrost-dispatcher", savedReceipt.ActorName);
Assert.Contains(dbContext.AuditEvents, x => x.EntityType == nameof(AgentTransportReceipt) && x.Action == "agent-transport.claimed");
}
private static string ComputeSignature(string secret, string payload)
{
using var hasher = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
@ -534,4 +573,13 @@ public sealed class PlatformEndpointsTests : IClassFixture<TestWebApplicationFac
public string Status { get; init; } = string.Empty;
}
private sealed class AgentTransportReceiptHttpResult
{
public Guid Id { get; init; }
public string RequestId { get; init; } = string.Empty;
public string ActivityKind { get; init; } = string.Empty;
}
}

View file

@ -162,6 +162,12 @@ async function enqueue(cache, options) {
await mirrorEnqueuedRequestOrThrow(request, options);
await cache.put(updateRequestDefinition, request.id, request);
await recordTransportReceiptOrThrow(request, {
activityKind: "Queued",
status: request.status,
actorName: request.createdByAgent ?? "system",
note: "Update request queued.",
});
printJson(request);
}
@ -286,6 +292,12 @@ async function claim(cache, options) {
updatedAt: now,
});
await cache.put(updateRequestDefinition, claimed.id, claimed);
await recordTransportReceiptOrThrow(claimed, {
activityKind: "Claimed",
status: claimed.status,
actorName: claimed.claimedByAgent ?? claimed.targetAgentIdentity ?? "codex",
note: `Request claimed for ${claimed.targetRepoName}.`,
});
printJson(claimed);
}
@ -310,6 +322,12 @@ async function closeRequest(cache, options) {
updatedAt: now,
});
await cache.put(updateRequestDefinition, closed.id, closed);
await recordTransportReceiptOrThrow(closed, {
activityKind: "Closed",
status: closed.status,
actorName: current.claimedByAgent ?? current.targetAgentIdentity ?? "system",
note: closed.closeNote || `Request closed as ${closed.status}.`,
});
printJson(closed);
}
@ -334,6 +352,12 @@ async function releaseRequest(cache, options) {
updatedAt: now,
});
await cache.put(updateRequestDefinition, released.id, released);
await recordTransportReceiptOrThrow(released, {
activityKind: "Released",
status: released.status,
actorName: current.claimedByAgent ?? current.targetAgentIdentity ?? "system",
note: released.closeNote || "Claim released back to the queue.",
});
printJson(released);
}
@ -379,6 +403,38 @@ async function applySnapshot(cache, options) {
});
}
async function recordTransportReceiptOrThrow(request, receipt) {
const baseUrl = optionalString(process.env.BIFROST_BRIDGE_BASE_URL);
const token = optionalString(process.env.BIFROST_BRIDGE_TOKEN);
if (!baseUrl || !token) {
return;
}
const response = await fetch(new URL("/transport/receipts", ensureTrailingSlash(baseUrl)), {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Bifrost-Bridge-Token": token,
},
body: JSON.stringify({
requestId: request.id,
title: request.title,
targetRepoName: request.targetRepoName,
targetRepositoryFullName: request.targetRepositoryFullName ?? "",
targetAgentIdentity: request.targetAgentIdentity ?? "",
activityKind: receipt.activityKind,
status: receipt.status,
actorName: receipt.actorName,
note: receipt.note,
}),
});
const text = await response.text();
if (response.status !== 202) {
throw new Error(`Bifrost transport receipt failed with ${response.status}: ${text}`);
}
}
function filteredRequests(cache, options) {
return cache.getAll(updateRequestDefinition)
.filter((request) => !options.status || request.status === options.status)
@ -550,6 +606,10 @@ function resolveOptionPath(path) {
return resolve(process.cwd(), path);
}
function ensureTrailingSlash(value) {
return value.endsWith("/") ? value : `${value}/`;
}
function runNodeJson(args, cwd) {
const result = spawnSync(process.execPath, args, {
cwd,